1def type_check(status):
2 def decorator(*accepted_types):
3 def wrapper(func):
4 def inner(*args, **kwargs):
5 accepted_types_strs = [str(accepted_type) for accepted_type in accepted_types]
6 if status == "in":
7 for arg in args:
8 if not isinstance(arg, accepted_types):
9 print("Invalid input arguments, expected {}!".format(", ".join(accepted_types_strs)))
10 result = func(*args, **kwargs)
11 if status == "out":
12 if not isinstance(result, accepted_types):
13 print("Invalid output value, expected {}!".format(", ".join(accepted_types_strs)))
14 return result
15 return inner
16 return wrapper
17 return decorator
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 101, in test_check_both
self.assertEqual(mock_print.call_count, 2)
AssertionError: 3 != 2
======================================================================
FAIL: test_check_in (test.TestTypeCheck.test_check_in)
The decorator should report invalid "in" arguments.
----------------------------------------------------------------------
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 43, in test_check_in
self.assertEqual(mock_print.call_count, 1)
AssertionError: 2 != 1
----------------------------------------------------------------------
Ran 4 tests in 0.003s
FAILED (failures=2)