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

"""
Test du suivi interactif.
"""
# ne devrait plus y avoir de problème après simplication de system.local_shell

import os
from os import path as osp
import sys
import unittest
import shutil

from common import tmpdir, on_dev_machine, dict_conf

from asrun.core import magic
from asrun.run import AsRunFactory
from asrun.mystring import file_cleanCR



class TestSystem(unittest.TestCase):

    def test01_scroll(self):
        # ssnl127d can be useful to test the scrolling
        can_follow = not sys.stdout.isatty()
        run = AsRunFactory()
        run.print_timer = True

        cmd = 'ls -lR /usr/lib'
        run.timer.Start('mise en "cache"')
        iret, output = run.Shell(cmd, follow_output=False)
        run.timer.Stop('mise en "cache"')

        run.timer.Start('follow_output=False')
        iret, output = run.Shell(cmd, follow_output=False)
        run.timer.Stop('follow_output=False')

        run.timer.Start('follow_output=True')
        iret, output = run.Shell(cmd, follow_output=can_follow)
        run.timer.Stop('follow_output=True')

        cpu1, sys1, elap1 = run.timer.StopAndGet('follow_output=False')
        cpu2, sys2, elap2 = run.timer.StopAndGet('follow_output=True')
        ecart = (elap2 - elap1) / elap1 * 100.
        ok1 = elap1 < 5.
        ok2 = elap2 < elap1 * 1.2

        f_output = open(osp.join(tmpdir, "system.1.out"), "w")
        sys.stdout = f_output
        print('Taille output = %d bytes' % len(output))
        print('Temps 1 = %.2f s // ok ? %s' % (elap1, ok1))
        print('Temps 2 = %.2f s // ok ? %s' % (elap2, ok2))
        print('Ecart elapsed 1/2 = %.2f %%' % ecart)
        f_output.close()
        sys.stdout = sys.__stdout__
        assert ok1
        assert ok2


    def test02_addtoenv(self):
        if not on_dev_machine():
            return
        run = AsRunFactory()
        path = osp.join(dict_conf['DATA'], "test_profile.sh")
        run.AddToEnv(path)
        assert os.environ.get('TESTVAR') is not None
        assert len(os.environ["TESTVAR"].split(":")) == 2, os.environ['TESTVAR']


    def test03_utils(self):
        run = AsRunFactory()
        path = osp.join(dict_conf['DATA'], "study.comm")
        assert run.IsText(path)
        assert not run.IsTextFileWithCR(path)
        path = osp.join(dict_conf['DATA'], "with_win_CR.export")
        assert run.IsText(path)
        assert run.IsTextFileWithCR(path)

        path_clean = osp.join(tmpdir, "test_cleanCR.out")
        shutil.copy(path, path_clean)
        file_cleanCR(path_clean)
        assert run.IsText(path_clean)
        assert not run.IsTextFileWithCR(path_clean)


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