import pytest from base import BaseTest from conftest import NewOntology from core.BuiltinConcepts import BuiltinConcepts from core.error import ErrorContext from evaluators.PythonEvaluator import PythonEvaluator from evaluators.PythonParser import PythonParser from helpers import _rv, _rvf, define_new_concept, get_concepts, get_metadata from parsers.ParserInput import ParserInput def get_parser_input_from(sheerka, context, command): pi = ParserInput(command) pi.init() parser_start = _rv(sheerka.newn(BuiltinConcepts.PARSER_INPUT, pi=pi)) ret = PythonParser().eval(context, None, parser_start) return ret.new[0] class TestPythonEvaluator(BaseTest): @pytest.fixture() def evaluator(self, sheerka): return sheerka.evaluators[PythonEvaluator.NAME] def test_i_can_match(self, sheerka, context, evaluator): ret_val = _rv(sheerka.newn(BuiltinConcepts.PYTHON_CODE)) assert evaluator.matches(context, ret_val).status is True ret_val = _rv(sheerka.newn(BuiltinConcepts.UNKNOWN_CONCEPT)) # it responds to USER_INPUT only assert evaluator.matches(context, ret_val).status is False ret_val = _rvf(sheerka.newn(BuiltinConcepts.PYTHON_CODE)) # status should be true assert evaluator.matches(context, ret_val).status is False @pytest.mark.parametrize("text, expected", [ ("1 + 1", 2), ("echo('I have access to Sheerka !')", "I have access to Sheerka !"), ("sheerka.echo('I have access to Sheerka !')", "I have access to Sheerka !"), ("a=10\na", 10), ]) def test_i_can_evaluate_simple_expression(self, sheerka, context, evaluator, text, expected): start = get_parser_input_from(sheerka, context, text) ret = evaluator.eval(context, None, start) assert ret.eaten == [start] assert len(ret.new) == 1 assert ret.new[0].status is True assert ret.new[0].value == expected assert ret.new[0].parents == [start] def test_i_can_detect_evaluation_error(self, sheerka, context, evaluator): start = get_parser_input_from(sheerka, context, "a") ret = evaluator.eval(context, None, start) assert ret.eaten == [] assert len(ret.new) == 1 assert ret.new[0].status is False assert isinstance(ret.new[0].value, ErrorContext) assert ret.new[0].parents == [start]