exec_tests.py 2.61 KB
Newer Older
1 2 3 4 5 6 7 8
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
9
from mjtest.util.shell import SigKill
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

_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))
40 41
                os.chdir(cwd)
                shutil.rmtree(tmp_dir)
42 43 44
                raise InterruptedError()
            exp_out, _, _ = \
                self.env.run_command("java", base_filename)
45
            exp_out = exp_out.decode().strip()
46 47 48
        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()
49 50 51 52 53 54 55 56 57
        try:
            _, err, rtcode = self.env.run_mj_command(self.MODE, base_filename + ".java")
            out, _, _ = self.env.run_command("./" + base_filename)
            out = out.decode().strip()
            os.chdir(cwd)
            shutil.rmtree(tmp_dir)
            if self.type == self.MODE and self.env.mode == self.MODE:
                return BasicDiffTestResult(self, rtcode, out, err.decode(), exp_out)
            return BasicTestResult(self, rtcode, out.decode(), err.decode())
58 59 60
        except SigKill as sig:
            os.chdir(cwd)
            return BasicTestResult(self, sig.retcode, "", exp_out, sig.name)
61 62 63
        except:
            os.chdir(cwd)
            raise
64 65

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