<commit_before># vim: set fileencoding=utf-8 :

"""Unit Tests
"""

# Standard Library
from __future__ import absolute_import, division, print_function
import logging
import os

# Third-party
try:
    import mock
except ImportError:
    import unittest.mock as mock
import pytest

# Local/library specific
from opscripts.utils import v8 as ops_utils

MODULE = "opscripts.utils.v8"
DOC = """\
Alfa        Bravo    Charlie
----        -----    -------
apple           1          x
banana         22  xxxxxxxxx
Clementine    333         xx\
"""


def _get_job_mock(exit_status, stdout, stderr):
    """Set up a mock process as return from Popen()"""
    job_mock = mock.Mock()
    b_stdout = stdout.encode()
    b_stderr = stderr.encode()
    attrs = {"wait.return_value": exit_status,
             "stdout.read.return_value": b_stdout,
             "stderr.read.return_value": b_stderr}
    job_mock.configure_mock(**attrs)
    return job_mock


@mock.patch("os.link")
def test_back_up_file_success(mock_link):
    # GIVEN I have a legitimate file to back up
    file = "/foo/bar/baz.py"

    # WHEN I back it up
    backup_file = ops_utils.back_up_file(file)

    # THEN I get the path to the backup
    assert backup_file == "/foo/bar/baz.py_orig"
    mock_link.assert_called_with(file, backup_file)


@mock.patch("os.link")
def test_back_up_file_rel_success(mock_link):
    # GIVEN I have a relative file to back up
    file = "baz.py"

    # WHEN I back it up
    backup_file = ops_utils.back_up_file(file)

    # THEN I get the full path to the backup
    assert backup_file == os.path.join(os.getcwd(), file + "_orig")
    mock_link.assert_called_with(file, backup_file)


@mock.patch("os.link")
def test_back_up_file_custom_suffix(mock_link):
    # GIVEN I have a legitimate file to back up
    file = "baz.py"
    suffix = "_bak"
    target_dir = "/foo/bar/"

    # WHEN I specify a custom dir and suffix
    backup_file = ops_utils.back_up_file(file, target_dir, suffix)

    # THEN the backup path reflects them
    assert backup_file == os.path.join(target_dir, file + suffix)
    mock_link.assert_called_with(file, backup_file)


@mock.patch("os.link")
def test_back_up_file_bad_file(mock_link):
    # GIVEN I have a path to a directory
    file = "/foo/bar/"

    # WHEN I back it up
    backup_file = ops_utils.back_up_file(file)

    # THEN we do not attempt to link
    assert backup_file is False
    assert mock_link.called is False


@mock.patch("os.link")
def test_back_up_file_bad_input(mock_link):
    # GIVEN I have an integer
    file = 123

    # WHEN I back it up
    # THEN we explode and do not attempt to link
    with pytest.raises(AttributeError):
        ops_utils.back_up_file(file)

    assert mock_link.called is False

    file = None
    with pytest.raises(AttributeError):
        ops_utils.back_up_file(file)

    assert mock_link.called is False


def test_exec_cmd_debug_success():
    # GIVEN the pwd command with root as the working directory
    cmd_args = ["pwd"]
    cwd = "/"
    uid = None
    gids = None
    # WHEN the command is executed
    exit_status, stdout, stderr = ops_utils.exec_cmd_debug(cmd_args, cwd=cwd,
                                                           uid=uid, gids=gids)
    # THEN exit status should be 0 and
    #      stdout should be root directory ("/")
    #      stderr should be empty
    assert exit_status == 0
    assert stdout == "/"
    assert stderr == ""


@mock.patch('subprocess.Popen')
def test_exec_cmd_fail_hard_fail(mock_subp):
    # GIVEN a command will exit with a non-zero return code
    cmd_args = ["foobar"]
    stdout = "This is output"<commit_msg>updated for Python 3.6 compatibility<commit_after># vim: set fileencoding=utf-8 :

"""Unit Tests
"""

# Standard Library
from __future__ import absolute_import, division, print_function
import logging
import os

# Third-party
try:
    import mock
except ImportError:
    import unittest.mock as mock
import pytest

# Local/library specific
from opscripts.utils import v8 as ops_utils

MODULE = "opscripts.utils.v8"
DOC = """\
Alfa        Bravo    Charlie
----        -----    -------
apple           1          x
banana         22  xxxxxxxxx
Clementine    333         xx\
"""


def _get_job_mock(exit_status, stdout, stderr):
    """Set up a mock process as return from Popen()"""
    job_mock = mock.Mock()
    b_stdout = stdout.encode()
    b_stderr = stderr.encode()
    attrs = {"wait.return_value": exit_status,
             "stdout.read.return_value": b_stdout,
             "stderr.read.return_value": b_stderr}
    job_mock.configure_mock(**attrs)
    return job_mock


@mock.patch("os.link")
def test_back_up_file_success(mock_link):
    # GIVEN I have a legitimate file to back up
    file = "/foo/bar/baz.py"

    # WHEN I back it up
    backup_file = ops_utils.back_up_file(file)

    # THEN I get the path to the backup
    assert backup_file == "/foo/bar/baz.py_orig"
    mock_link.assert_called_with(file, backup_file)


@mock.patch("os.link")
def test_back_up_file_rel_success(mock_link):
    # GIVEN I have a relative file to back up
    file = "baz.py"

    # WHEN I back it up
    backup_file = ops_utils.back_up_file(file)

    # THEN I get the full path to the backup
    assert backup_file == os.path.join(os.getcwd(), file + "_orig")
    mock_link.assert_called_with(file, backup_file)


@mock.patch("os.link")
def test_back_up_file_custom_suffix(mock_link):
    # GIVEN I have a legitimate file to back up
    file = "baz.py"
    suffix = "_bak"
    target_dir = "/foo/bar/"

    # WHEN I specify a custom dir and suffix
    backup_file = ops_utils.back_up_file(file, target_dir, suffix)

    # THEN the backup path reflects them
    assert backup_file == os.path.join(target_dir, file + suffix)
    mock_link.assert_called_with(file, backup_file)


@mock.patch("os.link")
def test_back_up_file_bad_file(mock_link):
    # GIVEN I have a path to a directory
    file = "/foo/bar/"

    # WHEN I back it up
    backup_file = ops_utils.back_up_file(file)

    # THEN we do not attempt to link
    assert backup_file is False
    assert mock_link.called is False


@mock.patch("os.link")
def test_back_up_file_bad_input(mock_link):
    # GIVEN I have an integer or None
    file1 = 123
    file2 = None

    # WHEN I back it up
    # THEN we explode and do not attempt to link
    try:
        # Python 3.6
        with pytest.raises(TypeError):
            ops_utils.back_up_file(file1)
    except:
        # Python 2.7 - 3.5
        with pytest.raises(AttributeError):
            ops_utils.back_up_file(file1)
    assert mock_link.called is False

    try:
        # Python 3.6
        with pytest.raises(TypeError):
            ops_utils.back_up_file(file2)
    except:
        # Python 2.7 - 3.5
        with pytest.raises(AttributeError):
            ops_utils.back_up_file(file2)
    assert mock_link.called is False


def test_exec_cmd_debug_success():
    # GIVEN the pwd command with root as the working directory
    cmd_args = ["pwd"]
    cwd = "/"
    uid = None
    gids = None
    # WHEN the command is executed
    exit_status, stdout, stderr = ops_utils.exec_cmd_debug(cmd_args, cwd=cwd,
                                                           uid=uid, gids=gids)
    # THEN exit status should be 0 and
    #      stdout should be root directory ("/")
    #      stderr should be empty
    assert exit_status == 0
    assert stdout == "/"
    assert stderr == ""


@mock.patch('subprocess.Popen')
def test_exec_cmd_fail_hard_fail(mock_subp):
    # GIVEN a command will exit with a non-zero return code
    cmd_args = ["foobar"]
    stdout = "This is output"
{'fraction_non_alphanumeric': 0.09404839764551995, 'fraction_numerical': 0.006278613472858077, 'mean_word_length': 2.711650485436893, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '720302', 'n_tokens_mistral': 2594, 'n_tokens_neox': 2486, 'n_words': 713}