Skip to content
This repository has been archived by the owner on Sep 17, 2019. It is now read-only.

Validate string before evaluating #274

Merged
merged 1 commit into from Jul 12, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 20 additions & 4 deletions napalm_base/validate.py
Expand Up @@ -14,6 +14,10 @@
import re


# We put it here to compile it only once
numeric_compare_regex = re.compile("^(<|>|<=|>=|==|!=)(\d+(\.\d+){0,1})$")


def _get_validation_file(validation_file):
try:
with open(validation_file, 'r') as stream:
Expand Down Expand Up @@ -139,10 +143,22 @@ def _compare_getter(src, dst):

def compare_numeric(src_num, dst_num):
"""Compare numerical values. You can use '<%d','>%d'."""
complies = eval(str(dst_num)+src_num)
if not isinstance(complies, bool):
return False
return complies
dst_num = float(dst_num)

match = numeric_compare_regex.match(src_num)
if not match:
error = "Failed numeric comparison. Collected: {}. Expected: {}".format(dst_num, src_num)
raise ValueError(error)

operand = {
"<": "__lt__",
">": "__gt__",
">=": "__ge__",
"<=": "__le__",
"==": "__eq__",
"!=": "__ne__",
}
return getattr(dst_num, operand[match.group(1)])(float(match.group(2)))


def empty_tree(input_list):
Expand Down
17 changes: 17 additions & 0 deletions test/unit/validate/test_unit.py
Expand Up @@ -274,3 +274,20 @@ class TestValidate:
def test__compare_getter_list(self, src, dst, result):
"""Test for _compare_getter_list."""
assert validate._compare_getter(src, dst) == result

def test_numeric_comparison(self):
assert validate.compare_numeric("<2", 1)
assert not validate.compare_numeric("<2", 3)
assert validate.compare_numeric("<=2", 2)
assert validate.compare_numeric("<3", "2")
assert validate.compare_numeric("!=3", "2")
with pytest.raises(ValueError):
assert validate.compare_numeric("a2a", 2)
with pytest.raises(ValueError):
assert validate.compare_numeric("<1a1", 2)
with pytest.raises(ValueError):
assert validate.compare_numeric("a<1", 2)
with pytest.raises(ValueError):
assert validate.compare_numeric("<1", "asdasd2")
with pytest.raises(ValueError):
assert validate.compare_numeric("<1", "2asdasd")