Skip to content

Commit

Permalink
utils: add validation errors functions (#6)
Browse files Browse the repository at this point in the history
The functions could be used from API scripts
to raise generic and validation errors
  • Loading branch information
gsanchietti authored Sep 19, 2023
1 parent 74d57b1 commit 94b46d2
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/nethsec/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,3 +323,50 @@ def get_group_macs(uci, group):
for u in uci.get('objects', group, 'user', list=True, default=[]):
macs = macs + get_user_macs(uci, u)
return macs


def validation_errors(errors):
'''
Generate a validation error for the APIs from an array.
Arguments:
- errors -- An array of array errors
Each array element is an array composed by 3 parameters:
- the name of the parameter
- the validation error reason
- the parameter original value that caused the error
Returns:
- A validation error object
'''
verrors = []
for e in errors:
verrors.append({"parameter": e[0], "message": e[1].strip().replace(" ", "_").lower(), "value": e[2]})

return {"validation": {"errors": verrors}}

def validation_error(parameter, message="", value=""):
'''
Generate a validation error for the APIs.
Arguments:
- parameter -- The name of the parameter
- message -- The validation error reason, default is empty
- value -- The parmeter original value that caused the error
Returns:
- A validation error object
'''
return validation_errors([[parameter, message, value]])

def generic_error(error):
'''
Generate a generic error for the APIs.
Arguments:
- message -- An error message
Returns:
- A validation error object
'''
return {"error": error.strip().replace(" ", "_").lower()}
17 changes: 17 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,20 @@ def test_get_random_id():
assert len(id1) == 11
assert id1[0:3] == "ns_"
assert id1 != id2

def test_error():
obj = utils.generic_error("my Error ")
assert obj == {"error": "my_error"}

def test_validation_error():
er1 = utils.validation_error("param1", "my Error ", "val1")
assert er1 == {"validation": {"errors": [{"parameter": "param1", "message": "my_error", "value": "val1"}]}}
er2 = utils.validation_error("param1")
assert er2 == {"validation": {"errors": [{"parameter": "param1", "message": "", "value": ""}]}}

def test_validation_errors():
er1 = utils.validation_errors([
["param1", " my Error ", "val1"],
["param2", " invalid_value ", False],
])
assert er1 == {"validation": {"errors": [{"parameter": "param1", "message": "my_error", "value": "val1"}, {"parameter": "param2", "message": "invalid_value", "value": False}]}}

0 comments on commit 94b46d2

Please sign in to comment.