<commit_before>from __future__ import absolute_import, print_function

from copy import deepcopy
import errno
import platform
import os

from project.commands.main import _parse_args_and_run_subcommand
from project.commands.launch import launch_command, main
from project.internal.test.tmpfile_utils import with_directory_contents
from project.prepare import UI_MODE_NOT_INTERACTIVE
from project.project_file import DEFAULT_PROJECT_FILENAME

from project.test.project_utils import project_dir_disable_dedicated_env


class Args(object):
    def __init__(self, **kwargs):
        self.project_dir = "."
        self.ui_mode = UI_MODE_NOT_INTERACTIVE
        for key in kwargs:
            setattr(self, key, kwargs[key])


def test_launch_command(monkeypatch):

    executed = {}

    def mock_execvpe(file, args, env):
        executed['file'] = file
        executed['args'] = args
        executed['env'] = env

    mock_environ = deepcopy(os.environ)
    mock_environ['FOO'] = 'bar'

    monkeypatch.setattr('os.environ', mock_environ)
    monkeypatch.setattr('os.execvpe', mock_execvpe)

    def check_launch(dirname):
        project_dir_disable_dedicated_env(dirname)

        result = launch_command(dirname, UI_MODE_NOT_INTERACTIVE)
        assert result is None
        assert 'file' in executed
        assert 'args' in executed
        assert 'env' in executed
        binary_name = "python"
        if platform.system() == 'Windows':
            binary_name = "python.exe"
        assert executed['file'].endswith(binary_name)
        assert executed['args'][0].endswith(binary_name)
        assert '--version' == executed['args'][1]
        assert 'bar' == executed['env']['FOO']

    with_directory_contents(
        {DEFAULT_PROJECT_FILENAME: """
runtime:
  FOO: {}

commands:
  default:
    conda_app_entry: python --version

"""}, check_launch)


def test_launch_command_no_app_entry(capsys):
    def check_launch_no_app_entry(dirname):
        project_dir_disable_dedicated_env(dirname)
        result = launch_command(dirname, UI_MODE_NOT_INTERACTIVE)
        assert result is None

    with_directory_contents({DEFAULT_PROJECT_FILENAME: """

"""}, check_launch_no_app_entry)

    out, err = capsys.readouterr()
    assert out == ""
    assert 'No known launch command' in err


def test_launch_command_failed_prepare(capsys):
    def check_launch_failed_prepare(dirname):
        project_dir_disable_dedicated_env(dirname)
        result = launch_command(dirname, UI_MODE_NOT_INTERACTIVE)
        assert result is None

    with_directory_contents({DEFAULT_PROJECT_FILENAME: """
runtime:
  - WILL_NOT_BE_SET
"""}, check_launch_failed_prepare)

    out, err = capsys.readouterr()
    assert out == ""
    assert 'Environment variable WILL_NOT_BE_SET is not set' in err


def test_main(monkeypatch, capsys):
    executed = {}

    def mock_execvpe(file, args, env):
        executed['file'] = file
        executed['args'] = args
        executed['env'] = env

    monkeypatch.setattr('os.execvpe', mock_execvpe)

    def check_launch_main(dirname):
        project_dir_disable_dedicated_env(dirname)
        result = main(Args(project_dir=dirname))

        assert 1 == result
        assert 'file' in executed
        assert 'args' in executed
        assert 'env' in executed
        assert executed['file'].endswith("python")
        assert executed['args'][0].endswith("python")
        assert '--version' == executed['args'][1]

    with_directory_contents(
        {DEFAULT_PROJECT_FILENAME: """
commands:
  default:
    conda_app_entry: python --version

"""}, check_launch_main)

    out, err = capsys.readouterr()
    assert "" == out
    assert "" == err


def test_main_failed_exec(monkeypatch, capsys):
    def mock_execvpe(file, args, env):
        raise OSError(errno.ENOMEM, "It did not work, Michael")

    monkeypatch.setattr('os.execvpe', mock_execvpe)

    def check_launch_main(dirname):
        project_dir_disable_dedicated_env(dirname)
        result = main(Args(project_dir=dirname))

        assert 1 == result

    with_directory_contents(
        {DEFAULT_PROJECT_FILENAME: """
commands:
  default:
    conda_app_entry: python --version

"""}, check_launch_main)

    out, err = capsys.readouterr()
    assert "" == out
    assert 'Failed to execute' in err
    assert 'It did not work, Michael' in err


def test_main_dirname_not_provided_use_pwd(monkeypatch, capsys):
    executed = {}

    def mock_execvpe(file, args, env):
        executed['file'] = file
        executed['args'] = args
        executed['env'] = env

    monkeypatch.setattr('os.execvpe', mock_execvpe)

    def check_launch_main(dirname):
        from os.path import abspath as real_abspath

        def mock_abspath(path):
            if path == ".":
                return dirname
            else:
                return real_abspath(path)

        monkeypatch.setattr('os.path.abspath', mock_abspath)

        project_dir_disable_dedicated_env(dirname)
        result = _parse_args_and_run_subcommand(['anaconda-project', 'launch'])

        assert 1 == result
        assert 'file' in executed
        assert 'args' in executed
        assert 'env' in executed
        assert executed['file'].endswith("python")
        assert executed['args'][0].endswith("python")
        assert '--version' == executed['args'][1]

    with_directory_contents(
        {DEFAULT_PROJECT_FILENAME: """
commands:
  default:
    conda_app_entry: python --version

"""}, check_launch_main)

    out, err = capsys.readouterr()
    assert "" == out
    assert "" == err<commit_msg>Fix test_launch failures on Windows<commit_after>from __future__ import absolute_import, print_function

from copy import deepcopy
import errno
import platform
import os

from project.commands.main import _parse_args_and_run_subcommand
from project.commands.launch import launch_command, main
from project.internal.test.tmpfile_utils import with_directory_contents
from project.prepare import UI_MODE_NOT_INTERACTIVE
from project.project_file import DEFAULT_PROJECT_FILENAME

from project.test.project_utils import project_dir_disable_dedicated_env


class Args(object):
    def __init__(self, **kwargs):
        self.project_dir = "."
        self.ui_mode = UI_MODE_NOT_INTERACTIVE
        for key in kwargs:
            setattr(self, key, kwargs[key])


python_exe = "python"
if platform.system() == 'Windows':
    python_exe = "python.exe"


def test_launch_command(monkeypatch):

    executed = {}

    def mock_execvpe(file, args, env):
        executed['file'] = file
        executed['args'] = args
        executed['env'] = env

    mock_environ = deepcopy(os.environ)
    mock_environ['FOO'] = 'bar'

    monkeypatch.setattr('os.environ', mock_environ)
    monkeypatch.setattr('os.execvpe', mock_execvpe)

    def check_launch(dirname):
        project_dir_disable_dedicated_env(dirname)

        result = launch_command(dirname, UI_MODE_NOT_INTERACTIVE)
        assert result is None
        assert 'file' in executed
        assert 'args' in executed
        assert 'env' in executed
        assert executed['file'].endswith(python_exe)
        assert executed['args'][0].endswith(python_exe)
        assert '--version' == executed['args'][1]
        assert 'bar' == executed['env']['FOO']

    with_directory_contents(
        {DEFAULT_PROJECT_FILENAME: """
runtime:
  FOO: {}

commands:
  default:
    conda_app_entry: python --version

"""}, check_launch)


def test_launch_command_no_app_entry(capsys):
    def check_launch_no_app_entry(dirname):
        project_dir_disable_dedicated_env(dirname)
        result = launch_command(dirname, UI_MODE_NOT_INTERACTIVE)
        assert result is None

    with_directory_contents({DEFAULT_PROJECT_FILENAME: """

"""}, check_launch_no_app_entry)

    out, err = capsys.readouterr()
    assert out == ""
    assert 'No known launch command' in err


def test_launch_command_failed_prepare(capsys):
    def check_launch_failed_prepare(dirname):
        project_dir_disable_dedicated_env(dirname)
        result = launch_command(dirname, UI_MODE_NOT_INTERACTIVE)
        assert result is None

    with_directory_contents({DEFAULT_PROJECT_FILENAME: """
runtime:
  - WILL_NOT_BE_SET
"""}, check_launch_failed_prepare)

    out, err = capsys.readouterr()
    assert out == ""
    assert 'Environment variable WILL_NOT_BE_SET is not set' in err


def test_main(monkeypatch, capsys):
    executed = {}

    def mock_execvpe(file, args, env):
        executed['file'] = file
        executed['args'] = args
        executed['env'] = env

    monkeypatch.setattr('os.execvpe', mock_execvpe)

    def check_launch_main(dirname):
        project_dir_disable_dedicated_env(dirname)
        result = main(Args(project_dir=dirname))

        assert 1 == result
        assert 'file' in executed
        assert 'args' in executed
        assert 'env' in executed
        assert executed['file'].endswith(python_exe)
        assert executed['args'][0].endswith(python_exe)
        assert '--version' == executed['args'][1]

    with_directory_contents(
        {DEFAULT_PROJECT_FILENAME: """
commands:
  default:
    conda_app_entry: python --version

"""}, check_launch_main)

    out, err = capsys.readouterr()
    assert "" == out
    assert "" == err


def test_main_failed_exec(monkeypatch, capsys):
    def mock_execvpe(file, args, env):
        raise OSError(errno.ENOMEM, "It did not work, Michael")

    monkeypatch.setattr('os.execvpe', mock_execvpe)

    def check_launch_main(dirname):
        project_dir_disable_dedicated_env(dirname)
        result = main(Args(project_dir=dirname))

        assert 1 == result

    with_directory_contents(
        {DEFAULT_PROJECT_FILENAME: """
commands:
  default:
    conda_app_entry: python --version

"""}, check_launch_main)

    out, err = capsys.readouterr()
    assert "" == out
    assert 'Failed to execute' in err
    assert 'It did not work, Michael' in err


def test_main_dirname_not_provided_use_pwd(monkeypatch, capsys):
    executed = {}

    def mock_execvpe(file, args, env):
        executed['file'] = file
        executed['args'] = args
        executed['env'] = env

    monkeypatch.setattr('os.execvpe', mock_execvpe)

    def check_launch_main(dirname):
        from os.path import abspath as real_abspath

        def mock_abspath(path):
            if path == ".":
                return dirname
            else:
                return real_abspath(path)

        monkeypatch.setattr('os.path.abspath', mock_abspath)

        project_dir_disable_dedicated_env(dirname)
        result = _parse_args_and_run_subcommand(['anaconda-project', 'launch'])

        assert 1 == result
        assert 'file' in executed
        assert 'args' in executed
        assert 'env' in executed
        assert executed['file'].endswith(python_exe)
        assert executed['args'][0].endswith(python_exe)
        assert '--version' == executed['args'][1]

    with_directory_contents(
        {DEFAULT_PROJECT_FILENAME: """
commands:
  default:
    conda_app_entry: python --version

"""}, check_launch_main)

    out, err = capsys.readouterr()
    assert "" == out
    assert "" == err
{'fraction_non_alphanumeric': 0.10241718889883616, 'fraction_numerical': 0.0016114592658907788, 'mean_word_length': 3.3181291070738306, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1867890', 'n_tokens_mistral': 3520, 'n_tokens_neox': 3391, 'n_words': 735}