exec_tests.py 2.16 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
import logging
import os
import shutil
from os import path
import sys
from mjtest.environment import TestMode, Environment
from mjtest.test.syntax_tests import BasicSyntaxTest
from mjtest.test.tests import TestCase, BasicDiffTestResult, BasicTestResult

_LOG = logging.getLogger("exec_tests")

class JavaExecTest(BasicSyntaxTest):
    """
    The MiniJava compiler should behave the same as javac
    """

    FILE_ENDINGS = [".java"]
    OUTPUT_FILE_ENDING = ".out"
    MODE = TestMode.comile_firm

    def __init__(self, env: Environment, type: str, file: str, preprocessed_file: str):
        super().__init__(env, type, file, preprocessed_file)
        self._expected_output_file = file + self.OUTPUT_FILE_ENDING
        self._has_expected_output_file = path.exists(self._expected_output_file)
        self._should_succeed = True

    def run(self) -> BasicDiffTestResult:
        base_filename = path.basename(self.file).split(".")[0]
        tmp_dir = self.env.create_tmpdir()
        shutil.copy(self.preprocessed_file, path.join(tmp_dir, base_filename + ".java"))
        cwd = os.getcwd()
        os.chdir(tmp_dir)
        exp_out = None
        if not self._has_expected_output_file:
            _, _, javac_rtcode = \
                self.env.run_command("javac", base_filename + ".java")
            if javac_rtcode != 0:
                _LOG.error("File \"{}\" isn't valid Java".format(self.preprocessed_file))
                raise InterruptedError()
            exp_out, _, _ = \
                self.env.run_command("java", base_filename)
        if self._has_expected_output_file and self.type == self.MODE and self.env.mode == self.MODE:
            with open(self._expected_output_file, "r") as f:
                exp_out = f.read()
        _, err, rtcode = self.env.run_mj_command(self.MODE, base_filename + ".java")
        out, _, _ = self.env.run_command(base_filename)
        os.chdir(cwd)
        if self.type == self.MODE and self.env.mode == self.MODE:
            return BasicDiffTestResult(self, rtcode, out.decode(), err.decode(), exp_out)
        return BasicTestResult(self, rtcode, out.decode(), err.decode())

TestCase.TEST_CASE_CLASSES[TestMode.comile_firm].append(JavaExecTest)