# Path: temci/run/run_driver.py
# def is_perf_available() -> bool:
#     """
#     Is the ``perf`` tool available?
#     """
#     try:
#         subprocess.check_call("perf stat -x';' -e cycles,cpu-clock,task-clock,instructions,branch-misses,"
#                               "cache-references -- echo 1", shell=True,
#                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
#     except BaseException:
#         return False
#     return True
# 
# Path: temci/scripts/cli.py
# class ErrorCode(Enum):
#     NO_ERROR = 0
#     PROGRAM_ERROR = 1
#     TEMCI_ERROR = 255
# 
# Path: tests/utils.py
# def run_temci(args: str, settings: dict = None, files: Dict[str, Union[dict, list, str]] = None,
#               expect_success: bool = True, misc_env: Dict[str, str] = None, raise_exc: bool = False) \
#         -> Result:
#     """
#     Run temci with the passed arguments
# 
#     :param args: arguments for temci
#     :param settings: settings dictionary, stored in a file called `settings.yaml` and appended to the arguments
#     :param files: {file name: content as string or dictionary that is converted into YAML first}
#     :param expect_success: expect a zero return code
#     :param misc_env: additional environment variables
#     :return: result of the call
#     """
#     if os.getenv("TEMCI_TEST_CMD", "0") == "1":
#         return run_temci_proc(args, settings, files, expect_success, misc_env=misc_env)
#     return run_temci_click(args, settings, files, expect_success, misc_env=misc_env, raise_exc=raise_exc)
# 
# def run_temci_proc(args: str, settings: dict = None, files: Dict[str, Union[dict, list, str]] = None,
#                    expect_success: bool = True, misc_env: Dict[str, str] = None) \
#         -> Result:
#     """
#     Run temci with the passed arguments
#     :param args: arguments for temci
#     :param settings: settings dictionary, stored in a file called `settings.yaml` and appended to the arguments
#     :param files: {file name: content as string or dictionary that is converted into YAML first}c at
#     :param expect_success: expect a zero return code
# 
#     :return: result of the call
#     """
#     with tempfile.TemporaryDirectory() as d:
#         _store_files(files, str(d))
#         cmd = "python3 {}/temci/scripts/cli.py {}".format(os.path.dirname(os.path.dirname(__file__)), args)
#         if settings is not None:
#             with open(d + "/settings.yaml", "w") as f:
#                 yaml.dump(settings, f)
#             cmd += " --config settings.yaml"
#         env = os.environ.copy()
#         env["LC_ALL"] = "en_US.utf-8"
#         env.update(misc_env or {})
#         proc = subprocess.Popen(["/bin/sh", "-c", cmd],
#                                 stdout=subprocess.PIPE,
#                                 stderr=subprocess.PIPE,
#                                 cwd=str(d),
#                                 env=env,
#                                 universal_newlines=True)
#         out, err = proc.communicate()
#         file_contents, yaml_contents = _load_files(files, d=d)
#         ret = Result(str(out).strip(), str(err).strip(), proc.returncode, file_contents, yaml_contents)
#         if expect_success:
#             assert proc.returncode == 0, repr(ret)
#         return ret


from temci.run.run_driver import is_perf_available
from temci.scripts.cli import ErrorCode
from tests.utils import run_temci, run_temci_proc

def test_check_tag_attribute():
    assert run_temci("exec bla.yaml --runs 1", files={
        "bla.yaml": [
            {
                "run_config": {"cmd": "echo 1"},
                "attributes": {"tags": "slow"}
            }
        ]
    }, expect_success=False).ret_code != 0


def test_included_blocks():
    out = run_temci("short exec echo ls --included_blocks ls --runs 1").out
    assert "ls" in out and "echo" not in out


def test_discard_blocks_on_error():
    assert run_temci("short exec 'exit 1' --discard_all_data_for_block_on_error", expect_success=False).ret_code == ErrorCode.PROGRAM_ERROR.value


def test_temci_short_shell():
    assert "42" in run_temci_proc("short shell echo 42").out


def test_temci_short_shell_file_creation():
    assert "run_output.yaml" not in run_temci_proc("short shell echo 42").file_contents


def test_pass_arguments():

# Path: temci/run/run_driver.py
# def is_perf_available() -> bool:
#     """
#     Is the ``perf`` tool available?
#     """
#     try:
#         subprocess.check_call("perf stat -x';' -e cycles,cpu-clock,task-clock,instructions,branch-misses,"
#                               "cache-references -- echo 1", shell=True,
#                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
#     except BaseException:
#         return False
#     return True
# 
# Path: temci/scripts/cli.py
# class ErrorCode(Enum):
#     NO_ERROR = 0
#     PROGRAM_ERROR = 1
#     TEMCI_ERROR = 255
# 
# Path: tests/utils.py
# def run_temci(args: str, settings: dict = None, files: Dict[str, Union[dict, list, str]] = None,
#               expect_success: bool = True, misc_env: Dict[str, str] = None, raise_exc: bool = False) \
#         -> Result:
#     """
#     Run temci with the passed arguments
# 
#     :param args: arguments for temci
#     :param settings: settings dictionary, stored in a file called `settings.yaml` and appended to the arguments
#     :param files: {file name: content as string or dictionary that is converted into YAML first}
#     :param expect_success: expect a zero return code
#     :param misc_env: additional environment variables
#     :return: result of the call
#     """
#     if os.getenv("TEMCI_TEST_CMD", "0") == "1":
#         return run_temci_proc(args, settings, files, expect_success, misc_env=misc_env)
#     return run_temci_click(args, settings, files, expect_success, misc_env=misc_env, raise_exc=raise_exc)
# 
# def run_temci_proc(args: str, settings: dict = None, files: Dict[str, Union[dict, list, str]] = None,
#                    expect_success: bool = True, misc_env: Dict[str, str] = None) \
#         -> Result:
#     """
#     Run temci with the passed arguments
#     :param args: arguments for temci
#     :param settings: settings dictionary, stored in a file called `settings.yaml` and appended to the arguments
#     :param files: {file name: content as string or dictionary that is converted into YAML first}c at
#     :param expect_success: expect a zero return code
# 
#     :return: result of the call
#     """
#     with tempfile.TemporaryDirectory() as d:
#         _store_files(files, str(d))
#         cmd = "python3 {}/temci/scripts/cli.py {}".format(os.path.dirname(os.path.dirname(__file__)), args)
#         if settings is not None:
#             with open(d + "/settings.yaml", "w") as f:
#                 yaml.dump(settings, f)
#             cmd += " --config settings.yaml"
#         env = os.environ.copy()
#         env["LC_ALL"] = "en_US.utf-8"
#         env.update(misc_env or {})
#         proc = subprocess.Popen(["/bin/sh", "-c", cmd],
#                                 stdout=subprocess.PIPE,
#                                 stderr=subprocess.PIPE,
#                                 cwd=str(d),
#                                 env=env,
#                                 universal_newlines=True)
#         out, err = proc.communicate()
#         file_contents, yaml_contents = _load_files(files, d=d)
#         ret = Result(str(out).strip(), str(err).strip(), proc.returncode, file_contents, yaml_contents)
#         if expect_success:
#             assert proc.returncode == 0, repr(ret)
#         return ret


# Path: tests/test_run.py
from temci.run.run_driver import is_perf_available
from temci.scripts.cli import ErrorCode
from tests.utils import run_temci, run_temci_proc


def test_check_tag_attribute():
    assert run_temci("exec bla.yaml --runs 1", files={
        "bla.yaml": [
            {
                "run_config": {"cmd": "echo 1"},
                "attributes": {"tags": "slow"}
            }
        ]
    }, expect_success=False).ret_code != 0


def test_included_blocks():
    out = run_temci("short exec echo ls --included_blocks ls --runs 1").out
    assert "ls" in out and "echo" not in out


def test_discard_blocks_on_error():
    assert run_temci("short exec 'exit 1' --discard_all_data_for_block_on_error", expect_success=False).ret_code == ErrorCode.PROGRAM_ERROR.value


def test_temci_short_shell():
    assert "42" in run_temci_proc("short shell echo 42").out


def test_temci_short_shell_file_creation():
    assert "run_output.yaml" not in run_temci_proc("short shell echo 42").file_contents


def test_pass_arguments():

    assert run_temci("short exec exit --argument 1", expect_success=False).ret_code == ErrorCode.PROGRAM_ERROR.value