def test_eval_expr_proc(self): env = Env({'x': op.add, 'a': 111, 'b': 222}) self.assertEqual(eval_expr(['x', 'a', 'b'], env), 333) with self.assertRaises(TypeError) as cm: eval_expr(['a', 'b'], env) self.assertEqual( str(cm.exception), 'Expression "a" (int) not callable in "(a b)"')
def test_eval_expr_lambda(self): procedure = eval_expr(['lambda', 'x', ['+', 'x', 4]]) self.assertEqual(procedure(10), 14) procedure = eval_expr(['lambda', ['x'], ['+', 'x', 4]]) self.assertEqual(procedure(10), 14) procedure = eval_expr(['lambda', ['x', 'y'], ['+', 'x', 'y', 4]]) self.assertEqual(procedure(10, 20), 34)
def test_eval_expr_begin(self): with self.assertRaises(SyntaxError): eval_expr(['begin']) self.assertEqual(eval_expr(['begin', 1, 2, 3]), 3)
def test_eval_expr_define(self): env = Env({'var': 0}) self.assertIsNone(eval_expr(['define', 'var', 789], env)) self.assertEqual(env['var'], 789)
def test_eval_expr_define_modifies_current_env(self): outer = Env({'var': 0}) inner = Env({}, outer) self.assertIsNone(eval_expr(['define', 'var', 789], inner)) self.assertEqual(inner, {'var': 789}) self.assertEqual(outer, {'var': 0})
def test_eval_expr_set_modified_defining_env(self): outer = Env({'var': 0}) inner = Env({}, outer) self.assertIsNone(eval_expr(['set!', 'var', 789], inner)) self.assertEqual(inner, {}) self.assertEqual(outer, {'var': 789})
def test_eval_expr_set_raises_on_new(self): with self.assertRaises(NameError): eval_expr(['set!', 'new_variable', 0])
def test_eval_expr_if_evaluates_pred_conseq_and_alt(self): env = Env({'t':1, 'f':0, 'conseq':123, 'alt':456}) self.assertEqual(eval_expr(['if', 't', 'conseq', 'undef'], env), 123) self.assertEqual(eval_expr(['if', 'f', 'undef', 'alt'], env), 456)
def test_eval_expr_if(self): self.assertEqual(eval_expr(['if', 1, 123, 456]), 123) self.assertEqual(eval_expr(['if', 0, 123, 456]), 456)
def test_eval_expr_quote(self): self.assertEqual(eval_expr(['quote', 123]), 123) self.assertEqual(eval_expr(['quote', 'abc']), 'abc') self.assertEqual(eval_expr(['quote', ['+', 2, 3]]), ['+', 2, 3])
def test_eval_expr_variable_reference(self): self.assertEqual(eval_expr('x', Env({'x':123})), 123)
def test_eval_expr_constant_literals(self): self.assertEqual(eval_expr(123), 123) self.assertEqual(eval_expr(1.23), 1.23)