def test_can_lookup_variable_from_the_environment(self): env = Environment() env.set("a", 2.0) env.set("b", 3.0) parse_tree = [ OperatorFactory.make_operator("*"), Symbol("a"), Symbol("b") ] result = Evaluator.evaluate(parse_tree, env) self.assertEqual(result, 6.0)
def test_throws_exception_when_getting_unbound(self): env = Environment() with self.assertRaises(Exception) as context: env.get("a") self.assertEqual(str(context.exception), 'Unbound variable: a') with self.assertRaises(Exception) as context: env.get("b") self.assertEqual(str(context.exception), 'Unbound variable: b')
def test_can_create_new_function(self): # Create a square function (which will be added to the environment) env = Environment() square_function = "(defun square(x)(* x x)))" Evaluator.evaluate(Parser.parse(Tokenizer.tokenize(square_function)), env) self.assertTrue(env.get("square")) # Call the square function call_square_function = "(square 9)" returned_value = Evaluator.evaluate(Parser.parse(Tokenizer.tokenize(call_square_function)), env) self.assertEqual(returned_value, 81)
def test_getting_and_setting_variable(self): env = Environment() value = 2.3 env.set("a", value) self.assertEqual(value, env.get("a"))
def test_can_set_variable_to_the_environment(self): env = Environment() parse_tree = [ OperatorFactory.make_operator("set!"), Symbol("x"), Number(19) ] Evaluator.evaluate(parse_tree, env) self.assertEqual(env.get("x"), 19)