示例#1
0
    def map_field(cls, exporter, entity_name, field_name, model_object):
        try:
            try:
                if hasattr(cls, "get_" + field_name):
                    mthd = getattr(cls, "get_" + field_name)
                    value = mthd(exporter,
                                 DynamicProxy.return_value(model_object))
                elif hasattr(cls, "map") and field_name in cls.map:
                    value = cls.map[field_name](
                        exporter, DynamicProxy.return_value(model_object))
                else:
                    value = getattr(model_object, field_name)

                # copy dict and sequence proxy before passing it to handler code
                if isinstance(value, (DynamicProxy, SequenceProxy)):
                    value = serialize_proxy(value)

                return value
            except UnknownException as e:
                return e.unknown

        except AttributeError as e:
            raise AttributeError(
                "Attribute %s does not exist on entity of type %s" %
                (field_name, entity_name))
示例#2
0
    def _load_resources(self, types):
        """
            Load all registered resources
        """
        entities = resource.get_entity_resources()
        resource_mapping = {}
        ignored_set = set()

        for entity in entities:
            if entity not in types:
                continue
            instances = types[entity].get_all_instances()
            if len(instances) > 0:
                for instance in instances:
                    try:
                        res = Resource.create_from_model(
                            self, entity, DynamicProxy.return_value(instance))
                        resource_mapping[instance] = res
                        self.add_resource(res)
                    except UnknownException:
                        ignored_set.add(instance)
                        # We get this exception when the attribute that is used to create the object id contains an unknown.
                        # We can safely ignore this resource == prune it
                        LOGGER.debug(
                            "Skipped resource of type %s because its id contains an unknown (location: %s)",
                            entity, instance.location)

                    except IgnoreResourceException:
                        ignored_set.add(instance)
                        LOGGER.info(
                            "Ignoring resource of type %s because it requested to ignore it. (location: %s)",
                            entity, instance.location)

        Resource.convert_requires(resource_mapping, ignored_set)
示例#3
0
 def new_arg(arg: object) -> object:
     if isinstance(arg, Context):
         return arg
     elif isinstance(arg, Unknown) and self.is_accept_unknowns():
         return arg
     else:
         return DynamicProxy.return_value(arg)
示例#4
0
def proxy_object(snippetcompiler, snippet, var):
    snippetcompiler.setup_for_snippet(snippet)
    (_, root) = compiler.do_compile()

    scope = root.get_child("__config__").scope

    value = scope.lookup(var).get_value()
    return DynamicProxy.return_value(value)
示例#5
0
文件: __init__.py 项目: inmanta/std
    def __getitem__(self, key):
        instance = self._get_instance()
        if not isinstance(key, str):
            raise RuntimeException(
                self,
                "Expected string key, but got %s, %s is a dict" %
                (key, self._get_instance()),
            )

        return DynamicProxy.return_value(instance[key])
示例#6
0
    def _get_instance_proxies_of_types(self, types):
        """
            Returns a dict of instances for the given types
        """
        proxies = {}
        for t in types:
            if self.types is not None and t in self.types:
                proxies[t] = [DynamicProxy.return_value(i) for i in self.types[t].get_all_instances()]
            else:
                proxies[t] = []

        return proxies
示例#7
0
    def __call__(self, *args):
        """
            The function call itself
        """
        self.check_requirements()
        new_args = []
        for arg in args:
            if isinstance(arg, Context):
                new_args.append(arg)
            else:
                new_args.append(DynamicProxy.return_value(arg))

        value = self.call(*new_args)

        value = DynamicProxy.unwrap(value)

        if self.returntype is not None and not isinstance(value, Unknown):
            valid = False
            exception = None

            try:
                valid = (value is None
                         or self._is_instance(value, self.returntype))
            except RuntimeException as e:
                raise e
            except Exception as exp:
                exception = exp

            if not valid:
                msg = ""
                if exception is not None:
                    msg = "\n\tException details: " + str(exception)

                raise Exception(
                    "Plugin %s should return value of type %s ('%s' was returned) %s"
                    % (self.__class__.__function_name__, self.returntype,
                       value, msg))

        return value
示例#8
0
    def _get_instance_proxies_of_types(
            self, types: List[str]) -> Dict[str, Sequence[ProxiedType]]:
        """Returns a dict of instances for the given types"""
        proxies: Dict[str, Sequence[ProxiedType]] = {}
        for t in types:
            if self.types is not None and t in self.types:
                proxies[t] = [
                    DynamicProxy.return_value(i)
                    for i in self.types[t].get_all_instances()
                ]
            else:
                proxies[t] = []

        return proxies
示例#9
0
    def __call__(self, *args: object, **kwargs: object) -> object:
        """
        The function call itself
        """
        self.check_requirements()

        def new_arg(arg: object) -> object:
            if isinstance(arg, Context):
                return arg
            elif isinstance(arg, Unknown) and self.is_accept_unknowns():
                return arg
            else:
                return DynamicProxy.return_value(arg)

        new_args = [new_arg(arg) for arg in args]
        new_kwargs = {k: new_arg(v) for k, v in kwargs.items()}

        value = self.call(*new_args, **new_kwargs)

        value = DynamicProxy.unwrap(value)

        if self.returntype is not None and not isinstance(value, Unknown):
            valid = False
            exception = None

            try:
                valid = value is None or self._is_instance(
                    value, self.returntype)
            except RuntimeException as e:
                raise e
            except Exception as exp:
                exception = exp

            if not valid:
                msg = ""
                if exception is not None:
                    msg = "\n\tException details: " + str(exception)

                raise Exception(
                    "Plugin %s should return value of type %s ('%s' was returned) %s"
                    % (self.__class__.__function_name__, self.returntype,
                       value, msg))

        return value
示例#10
0
 def get_instances(self, fortype: str = "std::Entity"):
     # extract all objects of a specific type from the compiler
     allof = self.types[fortype].get_all_instances()
     # wrap in DynamicProxy to hide internal compiler structure
     # and get inmanta objects as if they were python objects
     return [DynamicProxy.return_value(port) for port in allof]
示例#11
0
 def get_variable(self, name, scope):
     """
         Get the given variable
     """
     return DynamicProxy.return_value(
         self._scope.get_variable(name, scope).value)
示例#12
0
def test_unwrap_dict_key_validation():
    with pytest.raises(RuntimeException):
        DynamicProxy.unwrap({1: 2})
示例#13
0
def test_unwrap_list_dict_recurse():
    assert DynamicProxy.unwrap([{"null": None, "nulls": [None]}]) == [{"null": NoneValue(), "nulls": [NoneValue()]}]
示例#14
0
def test_unwrap_none():
    assert DynamicProxy.unwrap(None) == NoneValue()
示例#15
0
文件: __init__.py 项目: inmanta/std
 def __init__(self, mydict):
     DynamicProxy.__init__(self, mydict)