aboutsummaryrefslogtreecommitdiffstats
path: root/python_moonutilities
diff options
context:
space:
mode:
authorahmed.helmy <ahmad.helmy@orange.com>2018-04-05 15:41:37 +0200
committerDuval Thomas <thomas.duval@orange.com>2018-05-09 11:27:35 +0200
commit5dffe7e0889dd76885d313c1d44a4b389f4b8667 (patch)
tree6ff2f953ee16392bf6c0914744af258d61a237fa /python_moonutilities
parent1c249823b9a15d4dd3e2e5eae90c09131bc7f09b (diff)
continue integrating validation
Change-Id: Ifbda169affd649f9125581ac5b688b509d1f0d82 Signed-off-by: ahmed.helmy <ahmad.helmy@orange.com>
Diffstat (limited to 'python_moonutilities')
-rw-r--r--python_moonutilities/python_moonutilities/security_functions.py111
-rw-r--r--python_moonutilities/tests/unit_python/test_validated_input.py191
2 files changed, 301 insertions, 1 deletions
diff --git a/python_moonutilities/python_moonutilities/security_functions.py b/python_moonutilities/python_moonutilities/security_functions.py
index 15cbc8be..84e9ab7d 100644
--- a/python_moonutilities/python_moonutilities/security_functions.py
+++ b/python_moonutilities/python_moonutilities/security_functions.py
@@ -22,7 +22,6 @@ __targets = {}
def filter_input(func_or_str):
-
def __filter(string):
if string and type(string) is str:
return "".join(re.findall("[\w\- +]*", string))
@@ -82,15 +81,124 @@ def filter_input(func_or_str):
return None
+"""
+To do should check value of Dictionary but it's dependent on from where it's coming
+"""
+
+
+def validate_data(data):
+ def __validate_string(string):
+ if not string:
+ raise ValueError('Empty String')
+ '''
+ is it valid to contains space inbetween
+
+ '''
+
+ if " " in string:
+ raise ValueError('String contains space')
+
+ def __validate_list_or_tuple(container):
+ if not container:
+ raise ValueError('Empty Container')
+ for i in container:
+ validate_data(i)
+
+ def __validate_dict(dictionary):
+ if not dictionary:
+ raise ValueError('Empty Dictionary')
+ for key in dictionary:
+ validate_data(dictionary[key])
+
+ if isinstance(data, str):
+ __validate_string(data)
+ elif isinstance(data, list) or isinstance(data, tuple):
+ __validate_list_or_tuple(data)
+ elif isinstance(data, dict):
+ __validate_dict(data)
+ else:
+ raise ValueError('Value is Not String or Container or Dictionary')
+
+
+def validate_input(type, args_state=[], kwargs_state=[], body_state=[]):
+ """
+ this fucntion works only on List or tuple or dictionary of Strings ,and String direct
+ Check if input of function is Valid or not, Valid if not has spaces and values is not None or empty.
+
+ :param type: type of request if function is used as decorator
+ :param args_state: list of Booleans for args,
+ values must be order as target values of arguments,
+ True if None is not Allowed and False if is allowed
+ :param kwargs_state: list of Booleans for kwargs as order of input kwargs,
+ values must be order as target values of arguments,
+ True if None is not Allowed and False if is allowed
+ :param body_state: list of Booleans for arguments in body of request if request is post,
+ values must be order as target values of arguments,
+ True if None is not Allowed and False if is allowed
+ :return:
+ """
+
+ def validate_input_decorator(func):
+ def wrapped(*args, **kwargs):
+
+ temp_args = []
+ """
+ this loop made to filter args from object class,
+ when put this function as decorator in function control
+ then there is copy of this class add to front of args
+ """
+ for arg in args:
+ if isinstance(arg, str) == True or \
+ isinstance(arg, list) == True or \
+ isinstance(arg, dict) == True:
+ temp_args.append(arg)
+
+ while len(args_state) < len(temp_args):
+ args_state.append(True)
+
+ for i in range(0, len(temp_args)):
+ if args_state[i]:
+ validate_data(temp_args[i])
+
+ while len(kwargs_state) < len(kwargs):
+ kwargs_state.append(True)
+ counter = 0
+ for i in kwargs:
+ if kwargs_state[counter]:
+ validate_data({i: kwargs[i]})
+
+ counter = counter + 1
+
+ if type == "post" or type == "patch":
+ body = request.json
+ while len(body_state) < len(body):
+ body_state.append(True)
+ counter = 0
+ for i in body:
+ if body_state[counter]:
+ validate_data({i: body[i]})
+
+ counter = counter + 1
+
+ return func(*args, **kwargs)
+
+ return wrapped
+
+ return validate_input_decorator
+
+
def enforce(action_names, object_name, **extra):
"""Fake version of the enforce decorator"""
+
def wrapper_func(func):
def wrapper_args(*args, **kwargs):
# LOG.info("kwargs={}".format(kwargs))
# kwargs['user_id'] = kwargs.pop('user_id', "admin")
# LOG.info("Calling enforce on {} with args={} kwargs={}".format(func.__name__, args, kwargs))
return func(*args, **kwargs)
+
return wrapper_args
+
return wrapper_func
@@ -221,4 +329,5 @@ def check_auth(function):
user_id = kwargs.pop("user_id", token)
result = function(*args, **kwargs, user_id=user_id)
return result
+
return wrapper
diff --git a/python_moonutilities/tests/unit_python/test_validated_input.py b/python_moonutilities/tests/unit_python/test_validated_input.py
new file mode 100644
index 00000000..c8e681e9
--- /dev/null
+++ b/python_moonutilities/tests/unit_python/test_validated_input.py
@@ -0,0 +1,191 @@
+import pytest
+
+
+def test_valid_string():
+ from python_moonutilities.security_functions import validate_data
+ validate_data("CorrectString")
+
+def test_unvalid_string():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data("Notcorrect String")
+
+ assert str(exception_info.value) == 'String contains space'
+
+def test_empty_string():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data("")
+
+ assert str(exception_info.value) == 'Empty String'
+
+
+def test_none_value():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data(None)
+
+ assert str(exception_info.value) == 'Value is Not String or Container or Dictionary'
+
+
+def test_int_value():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data(1)
+
+ assert str(exception_info.value) == 'Value is Not String or Container or Dictionary'
+
+
+def test_float_value():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data(1.23)
+
+ assert str(exception_info.value) == 'Value is Not String or Container or Dictionary'
+
+
+def test_correct_list():
+ from python_moonutilities.security_functions import validate_data
+ validate_data(["skjdnfa","dao","daosdjpw"])
+
+
+def test_correct_list():
+ from python_moonutilities.security_functions import validate_data
+ validate_data(["skjdnfa"])
+
+
+def test_correct_instead_list():
+ from python_moonutilities.security_functions import validate_data
+ validate_data([["skjdnfa","daswi"],[["daskdlw"],["daklwo"]],["dawl","afioa"],["dawno"]])
+
+
+def test_empty_list():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data([])
+
+ assert str(exception_info.value) == 'Empty Container'
+
+
+def test_empty_list_inside_other_list():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data(["dajiwdj",[]])
+
+ assert str(exception_info.value) == 'Empty Container'
+
+
+def test_incorrect_string_inside_list():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data(["dajiwdj",["dakwe","daow awoepa"]])
+
+ assert str(exception_info.value) == 'String contains space'
+
+
+def test_empty_string_inside_list():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data(["dajiwdj", ["dakwe", ""]])
+
+ assert str(exception_info.value) == 'Empty String'
+
+
+def test_correct_tuples():
+ from python_moonutilities.security_functions import validate_data
+ validate_data(("dasdw","dawdwa"))
+
+
+def test_empty_tuples():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data(())
+
+ assert str(exception_info.value) == 'Empty Container'
+
+def test_correct_tuple_of_tuple():
+ from python_moonutilities.security_functions import validate_data
+ validate_data(("gjosjefa",("diwajdi","oejfoea"),(("jwdi","fjia"),("nfioa","ifao"))))
+
+
+def test_incorrect_tuple():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data(("djawo","dowa afw"))
+
+ assert str(exception_info.value) == 'String contains space'
+
+
+def test_correct_dictionary():
+ from python_moonutilities.security_functions import validate_data
+ validate_data({"daiwdw":"dwioajd"})
+
+
+def test_incorrect_dictionary():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data({"daiwdw":"dwioa jd"})
+
+ assert str(exception_info.value) == 'String contains space'
+
+def test_empty_dictionary():
+ from python_moonutilities.security_functions import validate_data
+ with pytest.raises(Exception) as exception_info:
+ validate_data({})
+
+ assert str(exception_info.value) == 'Empty Dictionary'
+
+
+def test_correct_function_pass():
+ from python_moonutilities.security_functions import validate_input
+
+ @validate_input()
+ def temp_function(string,list,tuple):
+ if string!="teststring" :
+ raise ValueError("values which passed incorrect")
+
+ temp_function("teststring",["teststring",["teststring"]],("teststring",("teststring")))
+
+def test_incorrect_function_pass1():
+ from python_moonutilities.security_functions import validate_input
+
+ @validate_input()
+ def temp_function(string, list, tuple):
+ if string != "teststring":
+ raise ValueError("values which passed incorrect")
+
+ with pytest.raises(Exception) as exception_info:
+ temp_function("teststring",list=["teststring", ["testst ring"]],tuple=("teststring", ("teststri ng")))
+
+ assert str(exception_info.value) == 'String contains space'
+
+
+def test_incorrect_function_pass2():
+ from python_moonutilities.security_functions import validate_input
+
+ @validate_input()
+ def temp_function(string, list, dictionary):
+ if string != "teststring":
+ raise ValueError("values which passed incorrect")
+
+ with pytest.raises(Exception) as exception_info:
+ temp_function("teststring", ["teststring", ["teststri ng"]], {"teststring": ("teststring")})
+
+ assert str(exception_info.value) == 'String contains space'
+
+
+def test_incorrect_function_pass3():
+ from python_moonutilities.security_functions import validate_input
+
+ class x:
+ @validate_input()
+ def temp_function(string, list, dictionary):
+ if string != "teststring":
+ raise ValueError("values which passed incorrect")
+
+ e=x;
+
+ with pytest.raises(Exception) as exception_info:
+ e.temp_function("teststring", ["teststring", ["teststri ng"]], {"teststring": ("teststring")})
+
+ assert str(exception_info.value) == 'String contains space'