1def type_check(check):
2 def types_helper(*types):
3 types = tuple(filter(lambda a: isinstance(a, type), types))
4 def helper(func):
5 def decorator(*args, **kwargs):
6 match check:
7 case "in":
8 invalid_kwargs = list(filter(lambda a: not isinstance(a, types), kwargs.values()))
9 invalid_args = list(filter(lambda a: not isinstance(a, types), args))
10 if types and (invalid_args or invalid_kwargs):
11 print(f"Invalid input arguments, expected {', '.join(str(t) for t in types)}!")
12 return func(*args, **kwargs)
13 case "out":
14 result = func(*args, **kwargs)
15 if not isinstance(result, types):
16 print(f"Invalid output arguments, expected {', '.join(str(t) for t in types)}!")
17 return result
18 return decorator
19 return helper
20 return types_helper
F..F
======================================================================
FAIL: test_check_both (test.TestTypeCheck.test_check_both)
The decorator should report invalid "in" and "out" together.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python3.12/unittest/mock.py", line 1390, in patched
return func(*newargs, **newkeywargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/test.py", line 98, in test_check_both
mock_print.assert_has_calls(
File "/usr/lib/python3.12/unittest/mock.py", line 981, in assert_has_calls
raise AssertionError(
AssertionError: Calls not found.
Expected: [call("Invalid input arguments, expected <class 'float'>!"),
call("Invalid output value, expected <class 'int'>!")]
Actual: [call("Invalid input arguments, expected <class 'float'>!"),
call("Invalid output arguments, expected <class 'int'>!")]
======================================================================
FAIL: test_check_out (test.TestTypeCheck.test_check_out)
The decorator should report an invalid "out" value.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python3.12/unittest/mock.py", line 1390, in patched
return func(*newargs, **newkeywargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/test.py", line 72, in test_check_out
mock_print.assert_has_calls([call(self.BASE_STRING_OUT.format("my type"))])
File "/usr/lib/python3.12/unittest/mock.py", line 981, in assert_has_calls
raise AssertionError(
AssertionError: Calls not found.
Expected: [call('Invalid output value, expected my type!')]
Actual: [call('Invalid output arguments, expected my type!')]
----------------------------------------------------------------------
Ran 4 tests in 0.004s
FAILED (failures=2)