diff --git a/README.md b/README.md index 8116da2..4fa1ed2 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ This is a wrapper of the [pyjexl](https://pypi.org/project/pyjexl/) library, including a set of default transformations (detailed in [this section](#included-transformations)) +Current version of the tcjexl library embeds the pyjexl code (as in [0.3.0 release](https://files.pythonhosted.org/packages/ab/1d/757ac4c9ae2da97cbb2c844fb70395990b5bbacccff5c0297ceefd670c62/pyjexl-0.3.0.tar.gz)) in order to apply some fixes. Ideally, the fix should be applied on the upstream library (in this sense, ve have created [this PR](https://github.com/mozilla/pyjexl/pull/30)) but it hasn't been merged yet at the moment of writing this by pyjexl mantainers. Hopefully, if at some moment the fix is applied on pyjexl we could simplify this (it would be a matter of rollback [this PR](https://github.com/telefonicasc/tcjexl/pull/6) and set the proper pyjexl dependency, e.g. `pyjexl==0.4.0`) + Example: ```python @@ -141,6 +143,8 @@ upload process you will be prompted to provide your user and password. ## Changelog +- Add: allow to use context for transformations arguments (using a patched version of pyjexl) + 0.1.0 (March 6th, 2024) - Initial release diff --git a/setup.py b/setup.py index 34cd4b2..3e03703 100644 --- a/setup.py +++ b/setup.py @@ -33,7 +33,8 @@ # Required packages. They will be installed if not already installed INSTALL_REQUIRES = [ - 'pyjexl==0.3.0' + 'parsimonious==0.10.0', + 'future==1.0.0' ] setup( diff --git a/tcjexl/jexl.py b/tcjexl/jexl.py index 62f04ce..d13fb00 100644 --- a/tcjexl/jexl.py +++ b/tcjexl/jexl.py @@ -16,7 +16,7 @@ # along with IoT orchestrator. If not, see http://www.gnu.org/licenses/. -import pyjexl +from .pyjexl.jexl import JEXL as pyJEXL import random import datetime import math @@ -25,7 +25,7 @@ from datetime import timezone from .expression_functions import linearInterpolator, linearSelector, randomLinearInterpolator, zipStrList, valueResolver -class JEXL(pyjexl.JEXL): +class JEXL(pyJEXL): def __init__(self, context=None, now=datetime.datetime.now(timezone.utc)): super().__init__(context=context) diff --git a/tcjexl/pyjexl/LICENSE b/tcjexl/pyjexl/LICENSE new file mode 100644 index 0000000..f87f40f --- /dev/null +++ b/tcjexl/pyjexl/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2016 Michael Kelly. + +bin/build-package.sh and CI configurations were taken from +https://github.com/atom/ci and are Copyright (c) 2015 GitHub Inc. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tcjexl/pyjexl/__init__.py b/tcjexl/pyjexl/__init__.py new file mode 100644 index 0000000..cca8d96 --- /dev/null +++ b/tcjexl/pyjexl/__init__.py @@ -0,0 +1,3 @@ +# flake8: noqa +from .exceptions import EvaluationError, JEXLException, MissingTransformError +from .jexl import JEXL diff --git a/tcjexl/pyjexl/analysis.py b/tcjexl/pyjexl/analysis.py new file mode 100644 index 0000000..8e5487c --- /dev/null +++ b/tcjexl/pyjexl/analysis.py @@ -0,0 +1,24 @@ +class JEXLAnalyzer(object): + def __init__(self, jexl_config): + self.config = jexl_config + + def visit(self, expression): + method = getattr(self, 'visit_' + type(expression).__name__, self.generic_visit) + return method(expression) + + def generic_visit(self, expression): + raise NotImplementedError() + + +class ValidatingAnalyzer(JEXLAnalyzer): + def visit_Transform(self, transform): + if transform.name not in self.config.transforms: + yield "The `{name}` transform is undefined.".format(name=transform.name) + for t in self.generic_visit(transform): + yield t + + def generic_visit(self, expression): + for child in expression.children: + assert child is not None + for c in self.visit(child): + yield c diff --git a/tcjexl/pyjexl/evaluator.py b/tcjexl/pyjexl/evaluator.py new file mode 100644 index 0000000..b68f611 --- /dev/null +++ b/tcjexl/pyjexl/evaluator.py @@ -0,0 +1,115 @@ +try: + from collections.abc import MutableMapping +except ImportError: + # Python 2.7 compat + # TODO: Decide if we stop supporting 2.7 + # as it's been EOL for a while now + from collections import MutableMapping + +from .exceptions import MissingTransformError + + +class Context(MutableMapping): + def __init__(self, context_data=None): + self.data = context_data or {} + self.relative_value = {} + + def __getitem__(self, key): + return self.data[key] + + def __setitem__(self, key, value): + self.data[key] = value + + def __delitem__(self, key): + del self.data[key] + + def __iter__(self): + return iter(self.data) + + def __len__(self): + return len(self.data) + + def with_relative(self, relative_value): + new_context = Context(self.data) + new_context.relative_value = relative_value + return new_context + + +class Evaluator(object): + def __init__(self, jexl_config): + self.config = jexl_config + + def evaluate(self, expression, context=None): + method = getattr(self, 'visit_' + type(expression).__name__, self.generic_visit) + context = context or Context() + return method(expression, context) + + def visit_BinaryExpression(self, exp, context): + return exp.operator.do_evaluate( + lambda: self.evaluate(exp.left, context), + lambda: self.evaluate(exp.right, context) + ) + + def visit_UnaryExpression(self, exp, context): + return exp.operator.do_evaluate(lambda: self.evaluate(exp.right, context)) + + def visit_Literal(self, literal, context): + return literal.value + + def visit_Identifier(self, identifier, context): + if identifier.relative: + subject = context.relative_value + elif identifier.subject: + subject = self.evaluate(identifier.subject, context) + else: + subject = context + + return subject.get(identifier.value, None) + + def visit_ObjectLiteral(self, object_literal, context): + return dict( + (key, self.evaluate(value, context)) + for key, value in object_literal.value.items() + ) + + def visit_ArrayLiteral(self, array_literal, context): + return [self.evaluate(value, context) for value in array_literal.value] + + def visit_Transform(self, transform, context): + try: + transform_func = self.config.transforms[transform.name] + except KeyError: + raise MissingTransformError( + 'No transform found with the name "{name}"'.format(name=transform.name) + ) + + args = [self.evaluate(arg, context) for arg in transform.args] + return transform_func(self.evaluate(transform.subject, context), *args) + + def visit_FilterExpression(self, filter_expression, context): + values = self.evaluate(filter_expression.subject, context) + if filter_expression.relative: + return [ + value for value in values + if self.evaluate(filter_expression.expression, context.with_relative(value)) + ] + else: + filter_value = self.evaluate(filter_expression.expression, context) + if filter_value is True: + return values + elif filter_value is False: + return None + else: + try: + return values[filter_value] + except (IndexError, KeyError): + return None + + def visit_ConditionalExpression(self, conditional, context): + if self.evaluate(conditional.test, context): + return self.evaluate(conditional.consequent, context) + else: + return self.evaluate(conditional.alternate, context) + + def generic_visit(self, expression, context): + raise ValueError('Could not evaluate expression: ' + repr(expression)) diff --git a/tcjexl/pyjexl/exceptions.py b/tcjexl/pyjexl/exceptions.py new file mode 100644 index 0000000..e140b27 --- /dev/null +++ b/tcjexl/pyjexl/exceptions.py @@ -0,0 +1,18 @@ +class JEXLException(Exception): + """Base class for all pyjexl exceptions.""" + + +class ParseError(JEXLException): + """An error during the parsing of an expression.""" + + +class InvalidOperatorError(ParseError): + """An invalid operator was used.""" + + +class EvaluationError(JEXLException): + """An error during evaluation of a parsed expression.""" + + +class MissingTransformError(EvaluationError): + """An unregistered transform was used.""" diff --git a/tcjexl/pyjexl/jexl.py b/tcjexl/pyjexl/jexl.py new file mode 100644 index 0000000..8f74586 --- /dev/null +++ b/tcjexl/pyjexl/jexl.py @@ -0,0 +1,93 @@ +from builtins import str +from collections import namedtuple +from functools import wraps + +from parsimonious.exceptions import ParseError as ParsimoniousParseError + +from .analysis import ValidatingAnalyzer +from .evaluator import Context, Evaluator +from .exceptions import ParseError +from .operators import default_binary_operators, default_unary_operators, Operator +from .parser import jexl_grammar, Parser + + +#: Encapsulates the variable parts of JEXL that affect parsing and +#: evaluation. +JEXLConfig = namedtuple('JEXLConfig', ['transforms', 'unary_operators', 'binary_operators']) + + +def invalidates_grammar(func): + @wraps(func) + def wrapper(self, *args, **kwargs): + self._grammar = None + return func(self, *args, **kwargs) + return wrapper + + +class JEXL(object): + def __init__(self, context=None): + self.context = Context(context or {}) + self.config = JEXLConfig( + transforms={}, + unary_operators=default_unary_operators.copy(), + binary_operators=default_binary_operators.copy() + ) + + self._grammar = None + + @property + def grammar(self): + if not self._grammar: + self._grammar = jexl_grammar(self.config) + return self._grammar + + @invalidates_grammar + def add_binary_operator(self, operator, precedence, func): + self.config.binary_operators[operator] = Operator(operator, precedence, func) + + @invalidates_grammar + def remove_binary_operator(self, operator): + del self.config.binary_operators[operator] + + @invalidates_grammar + def add_unary_operator(self, operator, func): + self.config.unary_operators[operator] = Operator(operator, 1000, func) + + @invalidates_grammar + def remove_unary_operator(self, operator): + del self.config.unary_operators[operator] + + def add_transform(self, name, func): + self.config.transforms[name] = func + + def remove_transform(self, name): + del self.config.transforms[name] + + def transform(self, name=None): + def wrapper(func): + self.config.transforms[name or func.__name__] = func + return func + return wrapper + + def parse(self, expression): + try: + return Parser(self.config).visit(self.grammar.parse(expression)) + except ParsimoniousParseError: + raise ParseError('Could not parse expression: ' + expression) + + def analyze(self, expression, AnalyzerClass): + parsed_expression = self.parse(expression) + visitor = AnalyzerClass(self.config) + return visitor.visit(parsed_expression) + + def validate(self, expression): + try: + for res in self.analyze(expression, ValidatingAnalyzer): + yield res + except ParseError as err: + yield str(err) + + def evaluate(self, expression, context=None): + parsed_expression = self.parse(expression) + context = Context(context) if context is not None else self.context + return Evaluator(self.config).evaluate(parsed_expression, context) diff --git a/tcjexl/pyjexl/operators.py b/tcjexl/pyjexl/operators.py new file mode 100644 index 0000000..58ed2f5 --- /dev/null +++ b/tcjexl/pyjexl/operators.py @@ -0,0 +1,51 @@ +import operator + + +class Operator(object): + __slots__ = ('symbol', 'precedence', 'evaluate', '_evaluate_lazy') + + def __init__(self, symbol, precedence, evaluate, evaluate_lazy=False): + """Operator definition. + + If evaluate_lazy is set to True, the `evaluate()` method will receive + it's parameters as a lambda expression that needs to be called to + receive the value of the expression. Otherwise, the values will + already be evaluated. + """ + self.symbol = symbol + self.precedence = precedence + self.evaluate = evaluate + self._evaluate_lazy = evaluate_lazy + + def do_evaluate(self, *args): + if self._evaluate_lazy: + return self.evaluate(*args) + return self.evaluate(*(arg() for arg in args)) + + def __repr__(self): + return 'Operator({})'.format(repr(self.symbol)) + + +default_binary_operators = { + '+': Operator('+', 30, operator.add), + '-': Operator('-', 30, operator.sub), + '*': Operator('*', 40, operator.mul), + '//': Operator('//', 40, operator.floordiv), + '/': Operator('/', 40, operator.truediv), + '%': Operator('%', 50, operator.mod), + '^': Operator('^', 50, operator.pow), + '==': Operator('==', 20, operator.eq), + '!=': Operator('!=', 20, operator.ne), + '>=': Operator('>=', 20, operator.ge), + '>': Operator('>', 20, operator.gt), + '<=': Operator('<=', 20, operator.le), + '<': Operator('<', 20, operator.lt), + '&&': Operator('&&', 10, lambda a, b: a() and b(), evaluate_lazy=True), + '||': Operator('||', 10, lambda a, b: a() or b(), evaluate_lazy=True), + 'in': Operator('in', 20, lambda a, b: a in b), +} + + +default_unary_operators = { + '!': Operator('!', 1000, operator.not_), +} diff --git a/tcjexl/pyjexl/parser.py b/tcjexl/pyjexl/parser.py new file mode 100644 index 0000000..eb52be6 --- /dev/null +++ b/tcjexl/pyjexl/parser.py @@ -0,0 +1,388 @@ +import ast +from future.builtins.misc import super +from future.utils import with_metaclass + +from parsimonious import Grammar, NodeVisitor + +from .exceptions import InvalidOperatorError +from .operators import Operator + + +def operator_pattern(operators): + """Generate a grammar rule to match a dict of operators.""" + # Sort operators and reverse them so that operators sharing a prefix + # always have the shortest forms last. Otherwise, the shorter forms + # will match operators early, i.e. `<` will match `<=` and ignore + # the `=`, causing a parse error. + operators = sorted(operators, key=lambda op: op.symbol, reverse=True) + operator_literals = ['"{}"'.format(op.symbol) for op in operators] + return ' / '.join(operator_literals) + + +def jexl_grammar(jexl_config): + return Grammar(r""" + expression = ( + _ (conditional_expression / binary_expression / unary_expression / complex_value) _ + ) + + conditional_expression = ( + conditional_test _ "?" _ expression _ ":" _ expression + ) + conditional_test = (binary_expression / unary_expression / complex_value) + + binary_expression = binary_operand (_ binary_operator _ binary_operand)+ + binary_operator = {binary_op_pattern} + binary_operand = (unary_expression / complex_value) + + unary_expression = unary_operator _ unary_operand + unary_operator = {unary_op_pattern} + unary_operand = (unary_expression / complex_value) + + complex_value = value (transform / attribute / filter_expression)* + + transform = "|" identifier transform_arguments? + transform_arguments = "(" _ value_list _ ")" + + attribute = "." identifier + + filter_expression = "[" _ expression _ "]" + + value = ( + boolean / string / numeric / subexpression / object_literal / + array_literal / identifier / relative_identifier + ) + + subexpression = "(" _ expression _ ")" + + object_literal = "{{" _ object_key_value_list? _ "}}" + object_key_value_list = object_key_value (_ "," _ object_key_value)* + object_key_value = identifier _ ":" _ expression + + array_literal = "[" _ value_list? _ "]" + value_list = expression (_ "," _ expression)* + + identifier = ~r"[a-zA-Z_\$][a-zA-Z0-9_\$]*" + relative_identifier = "." identifier + + boolean = "true" / "false" + string = ~"\"[^\"\\\\\\n\\r]*(?:\\\\.[^\"\\\\\\n\\r]*)*\""is / + ~"'[^'\\\\\\n\\r]*(?:\\\\.[^'\\\\\\n\\r]*)*'"is + numeric = "-"? number ("." number)? + + number = ~r"[0-9]+" + + _ = ~r"\s*" + """.format( + binary_op_pattern=operator_pattern(jexl_config.binary_operators.values()), + unary_op_pattern=operator_pattern(jexl_config.unary_operators.values()) + )) + + +class Parser(NodeVisitor): + def __init__(self, jexl_config): + self.config = jexl_config + self._relative = 0 + + def visit_expression(self, node, children): + return children[1][0] + + def visit_subexpression(self, node, children): + (left_paren, _, expression, _, right_paren) = children + return expression + + def visit_binary_expression(self, node, children): + pieces = [children[0]] + for op_value in node.children[1].children: + op_symbol = self.visit(op_value.children[1]) + value = self.visit(op_value.children[3]) + pieces.append(op_symbol) + pieces.append(value) + + # Build a tree of binary operators based on precedence. Adapted + # from JEXL's parser code for handling binary operators. + cursor = pieces.pop(0) + for piece in pieces: + if not isinstance(piece, Operator): + cursor.right = piece + piece.parent = cursor + cursor = piece + continue + + # Parents are always operators + parent = cursor.parent + while parent is not None and parent.operator.precedence >= piece.precedence: + cursor = parent + parent = cursor.parent + + node = BinaryExpression(operator=piece, left=cursor, parent=parent) + cursor.parent = node + if parent is not None: + parent.right = node + cursor = node + + return cursor.root() + + def visit_conditional_expression(self, node, children): + (test, _, question, _, consequent, _, colon, _, alternate) = children + return ConditionalExpression(test=test, consequent=consequent, alternate=alternate) + + def visit_conditional_test(self, node, children): + return children[0] + + def visit_binary_operator(self, node, children): + try: + return self.config.binary_operators[node.text] + except KeyError: + raise InvalidOperatorError(node.text) + + def visit_binary_operand(self, node, children): + return children[0] + + def visit_unary_expression(self, node, children): + (operator, _, value) = children + return UnaryExpression(operator=operator, right=value) + + def visit_unary_operator(self, node, children): + try: + return self.config.unary_operators[node.text] + except KeyError: + raise InvalidOperatorError(node.text) + + def visit_unary_operand(self, node, children): + return children[0] + + def visit_object_literal(self, node, children): + (left_brace, _, value, _, right_brace) = children + + return ObjectLiteral(value=value[0] if isinstance(value, list) else {}) + + def visit_object_key_value_list(self, node, children): + key_values = [children[0]] + for (_, comma, _, key_value) in children[1]: + key_values.append(key_value) + + return {identifier.value: value for identifier, value in key_values} + + def visit_object_key_value(self, node, children): + (identifier, _, colon, _, value) = children + return (identifier, value) + + def visit_array_literal(self, node, children): + (left_bracket, _, value, _, right_bracket) = children + return ArrayLiteral(value=value[0] if isinstance(value, list) else []) + + def visit_value_list(self, node, children): + values = [children[0]] + for (_, comma, _, value) in children[1]: + values.append(value) + + return values + + def visit_complex_value(self, node, children): + (value, modifiers) = children + + current = value + for (modifier,) in modifiers: + modifier.subject = current + current = modifier + + return current + + def visit_attribute(self, node, children): + (dot, identifier) = children + return identifier + + def visit_transform(self, node, children): + (bar, identifier, arguments) = children + transform = Transform(name=identifier.value, args=[]) + + try: + transform.args = arguments[0] + except (IndexError, TypeError): + pass + + return transform + + def visit_transform_arguments(self, node, children): + (left_paren, _, values, _, right_paren) = children + return values + + def visit_filter_expression(self, node, children): + (left_bracket, _, expression, _, right_bracket) = children + return FilterExpression(expression=expression, relative=expression.contains_relative()) + + def visit_identifier(self, node, children): + return Identifier(value=node.text, relative=False) + + def visit_relative_identifier(self, node, children): + (dot, identifier) = children + identifier.relative = True + return identifier + + def visit_value(self, node, children): + return children[0] + + def visit_boolean(self, node, children): + if node.text == 'true': + return Literal(True) + elif node.text == 'false': + return Literal(False) + else: + raise ValueError('Could not parse boolean: ' + node.text) + + def visit_numeric(self, node, children): + number_type = float if '.' in node.text else int + return Literal(number_type(node.text)) + + def visit_string(self, node, children): + return Literal(ast.literal_eval(node.text)) + + def generic_visit(self, node, visited_children): + return visited_children or node + + +class NodeMeta(type): + """ + Metaclass for making AST nodes. Handles adding the Node's custom + fields to __slots__ and ensures every Node has a parent field. + """ + def __new__(meta, classname, bases, classdict): + if 'parent' not in classdict['fields']: + classdict['fields'].append('parent') + classdict.update({ + '__slots__': classdict['fields'], + }) + return type.__new__(meta, classname, bases, classdict) + + +class Node(with_metaclass(NodeMeta, object)): + """ + Base class for AST Nodes. + + Nodes are like mutable namedtuples. Each node type should declare a + fields attribute on the class that lists the desired attributes for + the class. + """ + fields = [] + + def __init__(self, *args, **kwargs): + """ + Accepts values for this node's fields as both positional (in the + order defined in self.fields) and keyword arguments. + """ + for index, field in enumerate(self.fields): + if len(args) > index: + setattr(self, field, args[index]) + else: + setattr(self, field, kwargs.get(field, None)) + + def __repr__(self): + kwargs = [ + '='.join([field, repr(getattr(self, field))]) + for field in self.fields if field != 'parent' + ] + + return '{name}({kwargs})'.format( + name=type(self).__name__, + kwargs=', '.join(kwargs) + ) + + def __eq__(self, other): + return isinstance(other, type(self)) and all( + getattr(self, field) == getattr(other, field) + for field in self.fields if field != 'parent' + ) + + @property + def children(self): + return iter(()) + + def root(self): + if self.parent is None: + return self + else: + return self.parent.root() + + def contains_relative(self): + children_relative = any( + child.contains_relative() for child in self.children if child is not None + ) + return getattr(self, 'relative', children_relative) + + +class BinaryExpression(Node): + fields = ['operator', 'left', 'right'] + + @property + def children(self): + yield self.left + yield self.right + + +class UnaryExpression(Node): + fields = ['operator', 'right'] + + @property + def children(self): + yield self.right + + +class Literal(Node): + fields = ['value'] + + +class Identifier(Node): + fields = ['value', 'subject', 'relative'] + + def __init__(self, *args, **kwargs): + kwargs.setdefault('relative', False) + super().__init__(*args, **kwargs) + + @property + def children(self): + if self.subject is not None: + yield self.subject + + +class ObjectLiteral(Node): + fields = ['value'] + + +class ArrayLiteral(Node): + fields = ['value'] + + +class Transform(Node): + fields = ['name', 'args', 'subject'] + + @property + def children(self): + yield self.subject + for arg in self.args: + yield arg + + +class FilterExpression(Node): + fields = ['expression', 'subject', 'relative'] + + def __init__(self, *args, **kwargs): + kwargs.setdefault('relative', False) + super().__init__(*args, **kwargs) + + @property + def children(self): + yield self.expression + yield self.subject + + def contains_relative(self): + return self.subject.contains_relative() + + +class ConditionalExpression(Node): + fields = ['test', 'consequent', 'alternate'] + + @property + def children(self): + yield self.test + yield self.consequent + yield self.alternate diff --git a/tests/test_context_as_argument.py b/tests/test_context_as_argument.py new file mode 100644 index 0000000..bc4ca4d --- /dev/null +++ b/tests/test_context_as_argument.py @@ -0,0 +1,36 @@ +# Copyright 2024 Telefónica Soluciones de Informática y Comunicaciones de España, S.A.U. +# +# This file is part of tcjexl +# +# tcjexl 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. +# +# tcjexl 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 IoT orchestrator. If not, see http://www.gnu.org/licenses/. + + +import unittest +from tcjexl import JEXL + + +class TestContextAsArgument(unittest.TestCase): + + def test_context_as_argument(self): + jexl = JEXL() + + context1 = {"haystack": "long string", "needle": "long"} + context2 = {"haystack": "long string", "needle": "short"} + expression = 'haystack|includes(needle)' + + result = jexl.evaluate(expression, context1) + self.assertEqual(result, True) + + result = jexl.evaluate(expression, context2) + self.assertEqual(result, False)