#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import os.path as osp
import re
import shutil
import unittest

from common import dict_conf, execcmd, tmpdir, aster_version
from data   import compilation_export, catapy_export, catalo_export


class TestDevelop(unittest.TestCase):

    def test01_compilation(self):
        from asrun.run import AsRunFactory
        run = AsRunFactory()
        orig_f = osp.join(run.get_version_path(aster_version), "bibfor", "supervis", "debut.f")
        export = osp.join(tmpdir, "compilation.export")
        with open(export, "w") as f:
            f.write(compilation_export % dict_conf)
        with open(orig_f, "r") as f:
            txt = f.read()
        new = re.sub("      END$", "      print *,'MCTEST_EXE_OK'\n      END", txt)
        with open(osp.join(tmpdir, "debut.f"), "w") as f:
            f.write(new)

        cmd = dict_conf["as_run"] + [export]
        iret = execcmd(cmd, "dvp.1")
        assert iret == 0


    def test02_catapy(self):
        from asrun.run import AsRunFactory
        run = AsRunFactory()
        orig_capy = osp.join(run.get_version_path(aster_version), "catapy", "commande", "debut.capy")
        export = osp.join(tmpdir, "catapy.export")
        with open(export, "w") as f:
            f.write(catapy_export % dict_conf)
        with open(orig_capy, "r") as f:
            txt = f.read()
        new = re.sub("PAR_LOT *=", '''MCTEST_CAPY=SIMP(statut="o",typ="TXM"), PAR_LOT =''', txt)
        with open(osp.join(tmpdir, "debut.capy"), "w")as f:
            f.write(new)

        cmd = dict_conf["as_run"] + [export]
        iret, out = execcmd(cmd, "dvp.2", return_output=True)
        assert iret == 0
        with open("%(TMPDIR)s/commande/cata.py" % dict_conf) as f:
            f_cata_py = f.read()
        assert len(re.findall("MCTEST_CAPY", f_cata_py)) == 1
        assert len(re.findall("DEBUT *= *MACRO", f_cata_py)) == 1
        assert re.search("DIAGNOSTIC JOB : OK", out) \
          or re.search("DIAGNOSTIC JOB :.*ALARM", out)



if __name__ == "__main__":
    unittest.main()
