Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _check_result(self, result: typing.Any) -> None:
hints = typing.get_type_hints(self.func)
if 'return' not in hints:
return
typeguard.check_type(
argname='return',
value=result,
expected_type=hints['return'],
)
)
calculated_type_str = models_file._model._type.model(artifacts=artifacts)
calculated_type = eval(calculated_type_str) # pylint: disable=eval-used
# Creating models
base.metadata.create_all(engine)
# Creating model instance
model_instance = model(column=value)
session = sessionmaker()
session.add(model_instance)
session.flush()
# Querying session
queried_model = session.query(model).first()
assert queried_model.column == value
typeguard.check_type("queried_model.column", queried_model.column, calculated_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))
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]))
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]))
# fix the qualnames and modules of the methods defined above
for name in dir(Class):
val = getattr(Class, name)
if (not inspect.isroutine(val)
or inspect.ismethoddescriptor(val) and val.__objclass__ is not Class):
continue
if inspect.ismethod(val):
val = val.__func__
if val.__module__ == __name__:
val.__module__ = _module_name
val.__qualname__ = typename+'.'+val.__name__
Class.assert_type = typeguard.check_type # EXTERNAL DEPENDENCY
all_variant_fields = uniq( sum(Class._variant_id_fields, ()) )
variant_ids_that_have_field = {
attr: [
id_ for id_ in Class._variant_ids
if attr in Class._variant_id_fields[id_]
]
for attr in all_variant_fields
}
real_attr_for_variant_id_and_field = {
(id_, field): '_{}'.format(ix)
for id_ in Class._variant_ids
for (ix, field) in enumerate(Class._variant_id_fields[id_])
}
def _check_class_type_annotations(instance: Any) -> None:
"""Check that the type annotations for the class still hold.
"""
klass = instance.__class__
cls_annotations = typing.get_type_hints(klass)
for attr, annotation in cls_annotations.items():
value = getattr(instance, attr)
try:
check_type(attr, value, annotation)
except TypeError:
raise AssertionError(
f'{repr(value)} did not match type annotation for attribute "{attr}: {annotation}"')
except TypeError:
raise AssertionError(
f'{wrapped.__name__} argument {repr(arg)} did not match type annotation for parameter \
"{param}: {annotations[param]}"')
# Check function preconditions
preconditions = parse_assertions(wrapped.__doc__ or '')
function_locals = dict(zip(params, args_with_self))
_check_assertions(wrapped, function_locals, preconditions)
# Check return type
r = wrapped(*args, **kwargs)
if 'return' in annotations:
return_type = annotations['return']
try:
check_type('return', r, return_type)
except TypeError:
raise AssertionError(
f'{wrapped.__name__} return value {r} does not match annotated return type {return_type}')
return r
def __init__(self, msg: str='', at: Optional[Tuple[str, int, int, str]]=None, token: Optional[TokenInfo]=None, got: Optional[TokenInfo]=None):
"""
Args:
msg (str, optional): The error message. Defaults to ''.
at (Tuple[str, int, int, str], optional): A tuple of (filename, line, column, line string). Defaults to None.
token (TokenInfo, optional): The error token. Defaults to None.
got (TokenInfo, optional): The token which was gotten (adjusts the error message slightly). Defaults to None.
"""
if got is None:
check_type('token', token, Optional[TokenInfo])
else:
if token is not None:
raise ValueError("arguments 'token' and 'got' are mutually exclusive")
check_type('got', got, TokenInfo)
msg = str(msg).strip()
if token is not None:
msg += ' (token ' + simple_token_str(token) + ')'
elif got is not None:
msg += ', got ' + simple_token_str(got)
if at is not None:
if not isinstance(at, tuple) or len(at) != 4 \
or not isinstance(at[0], str) \
or not isinstance(at[1], int) \
or not isinstance(at[2], int) \
or not isinstance(at[3], str):
raise TypeError(f"argument 'at' must be string or (filename: str, line#: int, column#: int, line: str) tuple, not {typename(at)!r}")
# msg = msg.strip() + ' '