def run(self, x):
     # Typecheck the input and output by deferring to the typing module's method
     # This works for both Python's type and typing's _GenericAlias
     check_type("Input", x, self.Input)
     out = self._run(x)
     check_type("Output", out, self.Output)
     return out
Пример #2
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     type = self.type()
     check_type("type", type, Optional[k8sv1.SecretType])
     if type:  # omit empty
         v["type"] = type
     return v
Пример #3
0
async def test_cache_instruments(dummy_instruments, loop):
    hw_api = await hc.API.build_hardware_simulator(
        attached_instruments=dummy_instruments, loop=loop)
    await hw_api.cache_instruments()
    attached = hw_api.attached_instruments
    typeguard.check_type('left mount dict', attached[types.Mount.LEFT],
                         PipetteDict)
Пример #4
0
async def test_cache_instruments_hc(monkeypatch, dummy_instruments,
                                    hardware_controller_lockfile,
                                    running_on_pi, cntrlr_mock_connect, loop):
    hw_api_cntrlr = await hc.API.build_hardware_controller(loop=loop)

    def mock_driver_model(mount):
        attached_pipette = {'left': LEFT_PIPETTE_MODEL, 'right': None}
        return attached_pipette[mount]

    def mock_driver_id(mount):
        attached_pipette = {'left': LEFT_PIPETTE_ID, 'right': None}
        return attached_pipette[mount]

    monkeypatch.setattr(hw_api_cntrlr._backend._smoothie_driver,
                        'read_pipette_model', mock_driver_model)
    monkeypatch.setattr(hw_api_cntrlr._backend._smoothie_driver,
                        'read_pipette_id', mock_driver_id)

    await hw_api_cntrlr.cache_instruments()
    attached = hw_api_cntrlr.attached_instruments
    typeguard.check_type('left mount dict default', attached[types.Mount.LEFT],
                         PipetteDict)

    # If we pass a conflicting expectation we should get an error
    with pytest.raises(RuntimeError):
        await hw_api_cntrlr.cache_instruments({types.Mount.LEFT: 'p300_multi'})

    # If we pass a matching expects it should work
    await hw_api_cntrlr.cache_instruments(
        {types.Mount.LEFT: LEFT_PIPETTE_PREFIX})
    attached = hw_api_cntrlr.attached_instruments
    typeguard.check_type('left mount dict after expects',
                         attached[types.Mount.LEFT], PipetteDict)
Пример #5
0
def _function_has_keyword_parameters(func, kwargs):
    """ Raise `TypeError` if `func` does not accept all the keyword arguments in `kwargs`.

    Args:
        func (callable)
        kwargs (dict): Some keyword arguments.
    """
    parameters = _get_function_parameters(func)
    has_var_keyword = any([
        parameter.kind == inspect.Parameter.VAR_KEYWORD for parameter in list(parameters.values())
    ])
    type_hints = get_type_hints(func)

    for kwarg in kwargs.keys():
        if not has_var_keyword and (kwarg not in parameters or
                                    parameters[kwarg].kind == inspect.Parameter.VAR_POSITIONAL):
            raise TypeError('Function `%s` does not accept configured parameter `%s`.' %
                            (_get_function_signature(func), kwarg))

        try:
            if (kwarg in parameters and parameters[kwarg].default is not inspect.Parameter.empty and
                    isinstance(parameters[kwarg].default, _HParam)):
                check_type(kwarg, kwargs[kwarg], parameters[kwarg].default.type)
        except TypeError:
            raise TypeError('Function `%s` requires parameter `%s` to be of type `%s`.' %
                            (_get_function_signature(func), kwarg, parameters[kwarg].default.type))

        try:
            if kwarg in type_hints:
                check_type(kwarg, kwargs[kwarg], type_hints[kwarg])
        except TypeError:
            raise TypeError('Function `%s` requires parameter `%s` to be of type `%s`.' %
                            (_get_function_signature(func), kwarg, type_hints[kwarg]))
Пример #6
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     revision = self.revision()
     check_type("revision", revision, Optional[int])
     if revision:  # omit empty
         v["revision"] = revision
     return v
Пример #7
0
def execute_action(system: 'System', driver: AppDriver,
                   current: GUIState) -> GUIState:
    """
    Pop action from the buffer, and execute it, update the gui state
    :param system: `System` object
    :param driver: `AppDriver` object, used to perform operations on whatsapp gui
    :param current: current gui state
    :return: resultant state of gui after action is executed
    """
    try:
        action: Action = system.action_buffer.pop()
    except IndexError:
        return current

    meta = actions[action.name]

    try:
        check_type(action.name.name, action.data, meta.data_type)
    except TypeError:
        system.logger.warning(
            "Action Data Typing incorrect for {} : got {} expected {}".format(
                action.name, action.data, meta.data_type))

        return current

    current = meta.run(driver, current, system, action.data)
    return current
Пример #8
0
 def __check_attr_type(self, field: str, attribute: Any) -> int:
     try:
         field_type = self.__annotations__[field]
         check_type(field, attribute, field_type)
     except TypeError as err:
         raise PyNFTException(-1, str(self), str(err))
     return 0
Пример #9
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     replicas = self.replicas()
     check_type("replicas", replicas, Optional[int])
     if replicas:  # omit empty
         v["replicas"] = replicas
     return v
Пример #10
0
    def sane_timing_types(job_type: JobType, timing: TimingJobUnion) -> None:
        """
        Determine if the `JobType` is fulfilled by the type of the specified `timing`.

        Parameters
        ----------
        job_type : JobType
            :class:`~scheduler.job.JobType` to test agains.
        timing : TimingJobUnion
            The `timing` object to be tested.

        Raises
        ------
        TypeError
            If the `timing` object has the wrong `Type` for a specific `JobType`.
        """
        try:
            tg.check_type("timing", timing,
                          JOB_TIMING_TYPE_MAPPING[job_type]["type"])
            if job_type == JobType.CYCLIC:
                if not len(timing) == 1:
                    raise TypeError
        except TypeError as err:
            raise SchedulerError(
                JOB_TIMING_TYPE_MAPPING[job_type]["err"]) from err
Пример #11
0
    def load(cls: Type[T]) -> T:
        """Load a section of the configuration file.

        To load a new section, subclass ConfigSection and document the
        fields that you expect to parse, e.g.

        @dataclass
        class MyConfig(ConfigSection):
            title = "my_config_subsection"
            option : str = "default value"

        my_config = MyConfig.load()

        If the package typeguard is installed type defined in the metaclass
        will be verified.
        """
        schema = get_type_hints(cls)
        cls_fields = {
            f.name: schema[f.name]
            for f in fields(cls) if f.name != "title"
        }
        kwargs = {}

        for k, v in Config.load_section(cls.title).items():
            if k in cls_fields:
                ftype = cls_fields[k]
                try:
                    if CONFIG_CHECK_TYPE:
                        check_type(f"{cls.title}.{k}", v, ftype)
                except TypeError as err:
                    logging.error(str(err))
                else:
                    kwargs[k] = v

        return cls(**kwargs)  # type: ignore
Пример #12
0
 def __call__(self,
              *,
              x: float = None,
              y: float = None,
              z: float = None,
              distance: float = None,
              dx: float = None,
              dy: float = None,
              dz: float = None,
              scores: dict = None,
              tag: str = None,
              team: Union[str, bool] = None,
              limit: int = None,
              sort: target.sort = None,
              level: int = None,
              gamemode: Any = None,
              name: str = None,
              x_rotation: float = None,
              y_rotation: float = None,
              advancements: dict = None,
              nbt: dict = None):
     assert check_argument_types()
     # Check gamemode this way to avoid a circular import
     from . import GamemodeType
     check_type("gamemode", gamemode, Optional[GamemodeType])
Пример #13
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     namespace = self.namespace()
     check_type("namespace", namespace, Optional[str])
     if namespace:  # omit empty
         v["namespace"] = namespace
     return v
Пример #14
0
def checked_cast_complex(typ: Type[T], val: V, message: Optional[str] = None) -> T:
    """
    Cast a value to a type (with a runtime safety check).  Used for subscripted generics
    which isinstance cannot run against.

    Returns the value unchanged and checks its type at runtime. This signals to the
    typechecker that the value has the designated type.

    Like `typing.cast`_ ``check_cast`` performs no runtime conversion on its argument,
    but, unlike ``typing.cast``, ``checked_cast`` will throw an error if the value is
    not of the expected type.

    Args:
        typ: the type to cast to
        val: the value that we are casting
        message: message to print on error
    Returns:
        the ``val`` argument casted to typ

    .. _typing.cast: https://docs.python.org/3/library/typing.html#typing.cast
    """
    try:
        check_type("val", val, typ)
        return cast(T, val)
    except TypeError:
        raise ValueError(message or f"Value was not of type {typ}: {val}")
Пример #15
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     image = self.image()
     check_type("image", image, Optional[str])
     if image:  # omit empty
         v["image"] = image
     return v
Пример #16
0
def _validate_argument_type(expected_type, name: str, value) -> None:
    if "~" in str(expected_type):
        # this means that we have a TypeVar type, and those require
        # checking all the types of all the params as a whole, but we
        # don't have a good way of getting right now
        # TODO: #165
        return

    original_check_type = typeguard.check_type
    original_qualified_name = typeguard.qualified_name

    def wrapped_qualified_name(obj):
        """Needed to be able to show the useful qualified name for mock specs"""
        if isinstance(obj, WrappedMock):
            return obj.get_qualified_name()

        return original_qualified_name(obj)

    def wrapped_check_type(
        argname,
        inner_value,
        inner_expected_type,
        *args,
        globals: Optional[Dict[str, Any]] = None,
        locals: Optional[Dict[str, Any]] = None,
        **kwargs,
    ):

        if _is_a_mock(inner_value):
            inner_type = _extract_mock_template(inner_value)
            if inner_type is None:
                return

            # Ugly hack to make mock objects not be subclass of Mock
            inner_value = WrappedMock(spec=inner_type)

        # typeguard only checks the previous caller stack, so in order to be
        # able to do forward type references we have to extract the caller
        # stack ourselves.
        if kwargs.get("memo") is None and globals is None and locals is None:
            globals, locals = _get_caller_vars()

        return original_check_type(
            argname,
            inner_value,
            inner_expected_type,
            *args,
            globals=globals,
            locals=locals,
            **kwargs,
        )

    with unittest.mock.patch.object(
            typeguard, "check_type",
            new=wrapped_check_type), unittest.mock.patch.object(
                typeguard, "qualified_name", new=wrapped_qualified_name):
        try:
            typeguard.check_type(name, value, expected_type)
        except TypeError as type_error:
            raise TypeCheckError(str(type_error))
Пример #17
0
    def __setattr__(self, name: str, value: Any) -> None:
        """Setup new config values. Define logic when setting attributes from other subconfig class."""
        if (name == "config_fields" or not self.config_fields.frozen
                or name in [
                    *self.config_fields.vars,
                    *self.config_fields.myproperties_list,
                    *self.config_fields.properties_list,
                ]):
            if name != "config_fields" and name in self.config_fields.types:
                check_type(expected_type=self.config_fields.types[name],
                           value=value,
                           argname=name)

            object.__setattr__(self, name, value)

        elif name in self.config_fields.base_config_map:
            setattr(
                self.config_fields.base_config_map[name],
                name,
                value,
            )

        else:
            raise AttributeError(
                f"Object {str(self)} is frozen. New attributes cannot be set and attribute '{name}' "
                "not found. Maybe you misspelled name. If you really need to change the value, set "
                "attribute frozen to false.")
Пример #18
0
 def validate(self, *, prefix=''):
     assert is_dataclass(self), f"You forgot to annotate {type(self)} with @dataclass"
     for f in fields(self):
         fieldval = getattr(self, f.name)
         check_type(prefix + f.name, fieldval, f.type)
         if isinstance(fieldval, HParams):
             fieldval.validate(prefix=prefix + f.name + '.')
Пример #19
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     management_state = self.management_state()
     check_type("management_state", management_state,
                Optional[operatorv1.ManagementState])
     if management_state:  # omit empty
         v["managementState"] = management_state
     samples_registry = self.samples_registry()
     check_type("samples_registry", samples_registry, Optional[str])
     if samples_registry:  # omit empty
         v["samplesRegistry"] = samples_registry
     architectures = self.architectures()
     check_type("architectures", architectures, Optional[List[str]])
     if architectures:  # omit empty
         v["architectures"] = architectures
     skipped_imagestreams = self.skipped_imagestreams()
     check_type("skipped_imagestreams", skipped_imagestreams,
                Optional[List[str]])
     if skipped_imagestreams:  # omit empty
         v["skippedImagestreams"] = skipped_imagestreams
     skipped_templates = self.skipped_templates()
     check_type("skipped_templates", skipped_templates, Optional[List[str]])
     if skipped_templates:  # omit empty
         v["skippedTemplates"] = skipped_templates
     return v
Пример #20
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     ready = self.ready()
     check_type("ready", ready, Optional[bool])
     if ready is not None:  # omit empty
         v["ready"] = ready
     return v
Пример #21
0
    def check_result_or_error(cls, values):
        # Workaround until pydantic supports StrictUnion
        # https://github.com/samuelcolvin/pydantic/pull/2092
        id_val = values.get('id')
        check_type('', id_val, Union[int, str])

        return values
Пример #22
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     webhooks = self.webhooks()
     check_type("webhooks", webhooks, Optional[List["ValidatingWebhook"]])
     if webhooks:  # omit empty
         v["webhooks"] = webhooks
     return v
Пример #23
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     count = self.count()
     check_type("count", count, Optional[int])
     if count is not None:  # omit empty
         v["count"] = count
     return v
Пример #24
0
    def new_setattr(self: klass, name: str, value: Any) -> None:
        """Set the value of the given attribute on self to the given value.

        Check representation invariants for this class when not within an instance method of the class.
        """
        cls_annotations = typing.get_type_hints(klass)

        if name in cls_annotations:
            try:
                _debug(
                    f'Checking type of attribute {attr} for {klass.__qualname__} instance'
                )
                check_type(name, value, cls_annotations[name])
            except TypeError:
                raise AssertionError(
                    f'{repr(value)} did not match type annotation for attribute "{name}: {cls_annotations[name]}"'
                )

        super(klass, self).__setattr__(name, value)
        curframe = inspect.currentframe()
        callframe = inspect.getouterframes(curframe, 2)
        frame_locals = callframe[1].frame.f_locals
        if self is not frame_locals.get('self'):
            # Only validating if the attribute is not being set in a instance/class method
            init = getattr(klass, '__init__')
            try:
                _check_invariants(self, rep_invariants, init.__globals__)
            except AssertionError as e:
                raise AssertionError(str(e)) from None
Пример #25
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     egress_selections = self.egress_selections()
     check_type("egress_selections", egress_selections,
                List["EgressSelection"])
     v["egressSelections"] = egress_selections
     return v
Пример #26
0
 def checker(x):
     try:
         check_type('check', x, val)
     except TypeError:
         return False
     else:
         return True
Пример #27
0
def type_check(value, expected_type) -> bool:
    """Check that the `value` satisfies type `expected_type`."""
    if is_factory_instance(value):
        # If `value` is a @factory instance, what's relevant is the return type
        # of the `build()` method: we want to check if the return type is a
        # sub-type of the expected type.
        try:
            # If they are both classes, this is easy...
            return issubclass(value.__component_factory_return_type__,
                              expected_type)
        except TypeError:
            # ...but in general this might fail (`issubclass` can't be used with
            # subscripted generics in Python 3.7, or with any type from the
            # `typing` module in Python 3.6). If the check fails we should print
            # a warning and conservatively return `True`.
            warn(
                f"Unable to check that {value.__component_factory_return_type__} is a "
                f"sub-type of {expected_type}.")
            return True
    try:
        # typeguard.check_type requires a name as the first argument for their
        # error message, but we want to catch their error so we can pass an
        # empty string.
        typeguard.check_type("", value, expected_type)
    except TypeError:
        return False
    return True
Пример #28
0
    def new_setattr(self: klass, name: str, value: Any) -> None:
        """Set the value of the given attribute on self to the given value.

        Check representation invariants for this class when not within an instance method of the class.
        """
        cls_annotations = typing.get_type_hints(klass)

        if name in cls_annotations:
            try:
                _debug(
                    f"Checking type of attribute {attr} for {klass.__qualname__} instance"
                )
                check_type(name, value, cls_annotations[name])
            except TypeError:
                raise AssertionError(
                    f"Value {_display_value(value)} did not match type annotation for attribute "
                    f"{name}: {_display_annotation(cls_annotations[name])}"
                ) from None

        super(klass, self).__setattr__(name, value)
        curframe = inspect.currentframe()
        callframe = inspect.getouterframes(curframe, 2)
        frame_locals = callframe[1].frame.f_locals
        if self is not frame_locals.get("self"):
            # Only validating if the attribute is not being set in a instance/class method
            klass_mod = sys.modules.get(klass.__module__)
            if klass_mod is not None:
                try:
                    _check_invariants(self, klass, klass_mod.__dict__)
                except PyTAContractError as e:
                    raise AssertionError(str(e)) from None
Пример #29
0
 def _root(self) -> Dict[str, Any]:
     v = super()._root()
     partition = self.partition()
     check_type("partition", partition, Optional[int])
     if partition is not None:  # omit empty
         v["partition"] = partition
     return v
def _construct_from_json(ty, json_val, key=""):
    """
    Construct a value of type `ty` based on the json value `json_val`.
    """
    if json_val is None:
        return json_val
    if is_hparam_type(ty):
        if isinstance(json_val, ty):
            return json_val
        if not isinstance(json_val, dict):
            raise TypeError(
                f"Tried to construct attribute {key} of type {ty} with value {json_val}"
            )
        x = ty()
        x.override_from_json(json_val, key=key)
        return x
    if _is_list_type(ty):
        subtype = ty.__args__[0]
        return [
            _construct_from_json(subtype, y, key + ".listitem")
            for y in json_val
        ]
    if _is_dict_type(ty):
        ktype = ty.__args__[0]
        vtype = ty.__args__[1]
        return {
            _construct_from_json(ktype, k, key + ".dictkey"):
            _construct_from_json(vtype, v, key + ".dictitem")
            for k, v in json_val.items()
        }
    check_type(key, json_val, ty)
    return json_val
Пример #31
0
def match_type(value: Any, type_: Type) -> bool:
    try:
        check_type("value", value, type_, None)  # type: ignore
    except TypeError:
        return False
    return True