# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/Integration_Test_Generator.ipynb.

# %% auto 0
__all__ = ['set_cwd', 'run_integration_test']

# %% ../../nbs/Integration_Test_Generator.ipynb 1
from typing import *
import shutil
from pathlib import Path
import os
from tempfile import TemporaryDirectory
from contextlib import contextmanager
import subprocess # nosec: B404: Consider possible security implications associated with the subprocess module.

from yaspin import yaspin

from .logger import get_logger
from faststream_gen._code_generator.helper import (
    download_and_extract_faststream_archive,
    write_file_contents,
    read_file_contents,
)

# %% ../../nbs/Integration_Test_Generator.ipynb 3
@contextmanager
def set_cwd(cwd_path: Union[Path, str]) -> Generator:
    """Set the current working directory for the duration of the context manager.

    Args:
        cwd_path: The path to the new working directory.

    !!! note

        The above docstring is autogenerated by docstring-gen library (https://github.com/airtai/docstring-gen)
    """
    cwd_path = Path(cwd_path)
    original_cwd = os.getcwd()
    os.chdir(cwd_path)

    try:
        yield
    finally:
        os.chdir(original_cwd)

# %% ../../nbs/Integration_Test_Generator.ipynb 4
def _setup_venv_and_run_tests(
    env_name: str = "venv", file_to_test: Optional[str] = None
) -> bool:
    try:
        # Create virtual environment
        subprocess.run(["python3", "-m", "venv", env_name], check=True) # nosec: B602, B603, B607 subprocess call - check for execution of untrusted input.

        # Install requirements and run pytest
        commands = [
            "venv/bin/pip install --upgrade pip",
            "venv/bin/pip install -q -r dev_requirements.txt",
            "venv/bin/python -m pytest"
            if not file_to_test
            else f"venv/bin/python -m pytest {file_to_test}",
        ]

        for command in commands:
            # nosemgrep: python.lang.security.audit.subprocess-shell-true.subprocess-shell-true
            subprocess.run( # nosec: B602, B603 subprocess call - check for execution of untrusted input.
                command,
                check=True,
                shell=True,
                executable="/bin/bash",
                stderr=subprocess.DEVNULL,
                stdout=subprocess.PIPE,
            )
        return True
    except Exception as e:
        return False

# %% ../../nbs/Integration_Test_Generator.ipynb 7
def run_integration_test(src_dir: str) -> None:
    with yaspin(
        text="Running integration tests...", color="cyan", spinner="clock"
    ) as sp:
        with TemporaryDirectory() as d:
            shutil.copytree(src_dir, d, dirs_exist_ok=True)
            with set_cwd(d):
                status_ok = _setup_venv_and_run_tests()
            sp.text = ""
            if status_ok:
                message = " ✔ Integration tests were successfully completed."
            else:
                message = " ✘ Error: Integration tests failed."
                sp.color = "red"
            sp.ok(message)
