# -*- coding: utf-8 -*-
'''
This module implements unit tests of the actev get-system command.
'''

import sys
import os
import shutil
import unittest

from diva_evaluation_cli.bin.cli import cli_parser

tmp_folder = '/tmp/cli_tests'


def _clean_tmp_folder():
    try:
        shutil.rmtree(tmp_folder)
    except Exception:
        pass
    finally:
        os.mkdir(tmp_folder)


class TestGetSystemGit(unittest.TestCase):
    """
    Test the actev get-system git --sha CLI call, using valid and invalid
    parameters
    """

    def setUp(self):
        self.gitURL = "https://gitlab.kitware.com/actev/diva_evaluation_cli" \
                      ".git"
        _clean_tmp_folder()

    def test_git_subcommand(self):
        def _update_argv(args: list):
            # Use this to modify CLI parameters
            if isinstance(args, str):
                args = [args]
            sys.argv[1:] = ['get-system', 'git'] + args

        ##################
        # Checking --sha #
        ##################
        args = ['-u',
                self.gitURL,
                '-l',
                tmp_folder,
                '--sha']

        # 0. No parameter
        _update_argv(args)
        with self.assertRaises(SystemExit):
            cli_parser()
            self.fail('System does not stop on invalid input.')
        _clean_tmp_folder()

        # 1. Correct tag
        args.append('tags/1.0')
        _update_argv(args)
        try:
            cli_parser()
        except Exception:
            self.fail('Could not checkout on tag `development`')
        _clean_tmp_folder()

        # 2. Incorrect tag
        args[-1] = 'tags/0.1'
        _update_argv(args)
        with self.assertRaises(SystemExit):
            cli_parser()
            self.fail('The system managed to checkout on invalid tag `0.1`')

        # 3. Correct SHA
        args[-1] = 'eb26f205'
        _update_argv(args)
        try:
            cli_parser()
        except Exception:
            self.fail('Could not checkout on commit `eb26f205`')
        _clean_tmp_folder()

        # 4. Incorrect SHA
        args[-1] = 'abcdefgh'
        _update_argv(args)
        with self.assertRaises(SystemExit):
            cli_parser()
            self.fail(
                'The system managed to checkout on invalid commit `abcdefgh`')
        _clean_tmp_folder()

    def tearDown(self):
        # Clear archive and repository
        shutil.rmtree(tmp_folder)
        pass


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