authentic/tests/test_utils_evaluate.py

74 lines
2.4 KiB
Python

# authentic2 - versatile identity manager
# Copyright (C) 2010-2019 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import ast
import pytest
from authentic2.utils.evaluate import (
BaseExpressionValidator, ConditionValidator, ExpressionError,
evaluate_condition)
def test_base():
v = BaseExpressionValidator()
# assert v('1')[0] is False
# assert v('\'a\'')[0] is False
# assert v('x')[0] is False
v = BaseExpressionValidator(authorized_nodes=[ast.Num, ast.Str])
assert v('1')
assert v('\'a\'')
# code object is cached
assert v('1') is v('1')
assert v('\'a\'') is v('\'a\'')
with pytest.raises(ExpressionError):
assert v('x')
def test_condition_validator():
v = ConditionValidator()
assert v('x < 2 and y == \'u\' or \'a\' in z')
with pytest.raises(ExpressionError) as raised:
v('a and _b')
assert raised.value.code == 'invalid-variable'
assert raised.value.text == '_b'
with pytest.raises(ExpressionError) as raised:
v('a + b')
with pytest.raises(ExpressionError) as raised:
v('1 + 2')
def test_evaluate_condition():
v = ConditionValidator()
assert evaluate_condition('False', validator=v) is False
assert evaluate_condition('True', validator=v) is True
assert evaluate_condition('True and False', validator=v) is False
assert evaluate_condition('True or False', validator=v) is True
assert evaluate_condition('a or b', ctx=dict(a=True, b=False), validator=v) is True
assert evaluate_condition('a < 1', ctx=dict(a=0), validator=v) is True
with pytest.raises(ExpressionError) as exc_info:
evaluate_condition('a < 1', validator=v)
assert exc_info.value.code == 'undefined-variable'
assert evaluate_condition('a < 1', validator=v, on_raise=False) is False