def test_eval_method_with_false_expression(self): env = {"x": 0} while_stmt = WhileStatement( RelOpexpr(">", Varexpr("x"), Integer(10)), AssignStatement("x", BinOpexpr("+", Varexpr("x"), Integer(1)))) while_stmt.eval(env) self.assertEqual(env["x"], 0)
def parse_if_statement_method_with_else_statement(self): tokens = lex("if x > 22 then\nprint x;\nelse\nprint 0;\ndone\n") parser = Parser(tokens) parser.advance() ast = parser.parse_if_statement() expected_ast = IfStatement(RelOpexpr(">", Varexpr("x"), Integer(22)), AST([PrintStatement(Varexpr("x"))]), AST([PrintStatement(Integer(0))])) self.assertEqual(ast, expected_ast)
def test_parse_while_statement_method(self): tokens = lex("while x > 22 do\nprint x;\nx := x - 1;\ndone\n") parser = Parser(tokens) parser.advance() ast = parser.parse_while_statement() expected_ast = WhileStatement( RelOpexpr(">", Varexpr("x"), Integer(22)), AST([ PrintStatement(Varexpr("x")), AssignStatement("x", BinOpexpr("-", Varexpr("x"), Integer(1))) ]), ) self.assertEqual(ast, expected_ast)
def test_eval_method_with_defined_variable(self): env = {"x": 10} varexpr = Varexpr("x") result = varexpr.eval(env) self.assertEqual(result, 10)
def test___repr___method(self): varexpr = Varexpr("x") varexpr_repr = repr(varexpr) expected_repr = "Varexpr(x)" self.assertEqual(varexpr_repr, expected_repr)
def test_insert_node_method(self): ast = AST() ast.insert_node(Integer(10)) ast.insert_node(Varexpr("x")) expected_nodes = [Integer(10), Varexpr("x")] self.assertEqual(ast.nodes, expected_nodes)