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

Commit

Permalink
Release 0.24.3 (#276)
Browse files Browse the repository at this point in the history
* Validate string before evaluating (#274)

* Bump version to 0.24.3 (#275)
  • Loading branch information
dbarrosop committed Jul 12, 2017
1 parent e8af3eb commit 1be299a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
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
2 changes: 1 addition & 1 deletion setup.py
Expand Up @@ -12,7 +12,7 @@

setup(
name="napalm-base",
version='0.24.2',
version='0.24.3',
packages=find_packages(),
author="David Barroso, Kirk Byers, Mircea Ulinic",
author_email="dbarrosop@dravetech.com, ping@mirceaulinic.net, ktbyers@twb-tech.com",
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")

0 comments on commit 1be299a

Please sign in to comment.