From 2d98c21927ed966d018d285bd81eb9d1a4a3e427 Mon Sep 17 00:00:00 2001 From: Dirk Thomas Date: Mon, 4 Dec 2017 12:58:45 -0800 Subject: [PATCH] support more operators in conditions --- ament_package/condition.py | 22 ++++++++++++++-------- test/test_package.py | 6 ++++++ 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/ament_package/condition.py b/ament_package/condition.py index 2f3fbd2..c9be3bf 100644 --- a/ament_package/condition.py +++ b/ament_package/condition.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import operator import pyparsing @@ -34,7 +35,7 @@ def _get_condition_expression(): global _condition_expression if not _condition_expression: pp = pyparsing - operator = pp.Regex('==|!=').setName('operator') + operator = pp.Regex('==|!=|>=|>|<=|<').setName('operator') identifier = pp.Word('$', pp.alphanums + '_', min=2) value = pp.Word(pp.alphanums + '_-') comparison_term = identifier | value @@ -67,10 +68,15 @@ def _evaluate(parse_results, context): _evaluate(parse_results[2], context) # handle comparison operators - assert parse_results[1] in ('==', '!=') - if parse_results[1] == '==': - return _evaluate(parse_results[0], context) == \ - _evaluate(parse_results[2], context) - if parse_results[1] == '!=': - return _evaluate(parse_results[0], context) != \ - _evaluate(parse_results[2], context) + operators = { + '==': operator.eq, + '!=': operator.ne, + '<=': operator.le, + '<': operator.lt, + '>=': operator.ge, + '>': operator.gt, + } + assert parse_results[1] in operators.keys() + return operators[parse_results[1]]( + _evaluate(parse_results[0], context), + _evaluate(parse_results[2], context)) diff --git a/test/test_package.py b/test/test_package.py index c0b6eb7..3123ce7 100644 --- a/test/test_package.py +++ b/test/test_package.py @@ -88,6 +88,12 @@ def test_init_dependency(self): self.assertTrue(dep.evaluated_condition) self.assertRaises(TypeError, Dependency, 'foo', unknownattribute=42) + dep = Dependency('foo', condition='foo > bar and bar < baz') + self.assertTrue(dep.evaluate_condition({})) + + dep = Dependency('foo', condition='foo <= bar or bar >= baz') + self.assertFalse(dep.evaluate_condition({})) + def test_init_kwargs_string(self): pack = Package(filename='foo', name='bar',