I need to solve the below task:
Create decorator validate, which validates arguments in the set_pixel function. All function parameters should be between 0(int) and 256(int) inclusive.
If all parameters are valid, the set_pixel function should return a “Pixel created!” message. Otherwise, it should return the “Function call is not valid!” message.
Use functools.wraps where necessary.
Don’t forget about doc strings.
Examples
set_pixel(0, 127, 300)
Function call is not valid!
set_pixel(0,127,250)
Pixel created!
I have been given a template as below:
def validate():
'''
Add corresponded arguments and implementation here.
'''
return wrapper
pass
@validate
def set_pixel(x: int, y: int, z: int) -> str:
return "Pixel created!
I have tried to solve the task with dozens of different ways without any success. One of the latest ones:
from inspect import signature
def validate(fn):
'''
Add corresponded arguments and implementation here.
'''
params = signature(fn).parameters.keys()
def wrapper(*args):
val_list = []
for name, val in zip(params, args):
if val > 256:
val_list.append(val)
if len(val_list) == 0:
fn(*args)
else:
msg = 'Function call is not valid!'
print(msg)
return wrapper
@validate
def set_pixel(x: int, y: int, z: int) -> str:
return print("Pixel created!")
What I have noticed so far is in the set_pixel function I inserted “print” command between “return” and the “Pixel created!” string, otherwise it did not give me any output when function is executed. Apart from that, although the above code is working normally in my pycharm editor, the automatic test environment which provided the task is rejecting my solutions based on similar to following reasons:
Test name: test_validate_decorator[parameters0-Function call is not valid!]
Failure message:
AssertionError: assert None == ‘Function call is not valid!’
show more
parameters = (0, 127, 300), expected = ‘Function call is not valid!’
@pytest.mark.parametrize(“parameters,expected”, [x for x in TEST_DATA])
def test_validate_decorator(parameters, expected):
result = task.validate(test_set_pixel)(*parameters)
assert result == expected
E AssertionError: assert None == ‘Function call is not valid!’
tests/test_task.py:21: AssertionError
Any help is really appreciated.