# coverage run -m pytest -rA tests/test_subprocessor.py --no-header --html=./reports/pytest/report.html --self-contained-html && coverage html #noqa E501

import pytest

import wox.python_discoverer as python_discoverer
import wox.venv_management as venv_manager

from wox.subprocessor import sanitize_command
from wox.wox_exceptions import CommandNotFoundError, PythonInterpreterCallError


# python -B -m pytest -rA -k "test_sanitize_command"
def test_sanitize_command(monkeypatch, tmp_path):
    """
        The python interpreter must be added to PATH environment variable, ensuring
        the system will use the right python interpreter.


        If the command is 'python', the python interpreter path provided by the virtual
        environment must be casted into string for compatibility with shutil.which().
    """

    env = 'py311'

    python_interpreter = python_discoverer.python_discovery(env)

    env_path = tmp_path / env

    venv_manager.create_venv(env_path, python_interpreter)

    venv_python_interpreter = python_discoverer.locate_venv_python_exe(env_path)

    assert venv_python_interpreter.path.exists()

    def patched_which(cmd = None, path = None):
        patched_which.cmd = cmd
        patched_which.path = path
        return venv_python_interpreter

    monkeypatch.setattr('shutil.which', patched_which)

    sanitize_command('python -V', venv_python_interpreter.path)

    assert isinstance(patched_which.cmd, str)
    assert str(venv_python_interpreter.path.parent) in patched_which.path

# python -B -m pytest -rA -k "test_python_interpreter_call_error"
def test_python_interpreter_call_error():
    """
        PythonInterpreterCallError must raise if the command
        would run the python REPL.
    """

    with pytest.raises(PythonInterpreterCallError):
        sanitize_command('python')

# python -B -m pytest -rA -k "test_command_not_found_error"
def test_command_not_found_error():
    """
        CommandNotFoundError must raise if the command doesn't exist.
    """

    with pytest.raises(CommandNotFoundError):
        sanitize_command('cowsa')
