# Path: scripnix/pybin/top_level_pid.py
# COMMAND_NAME = "top-level-pid"
# 
# @common_command_and_options(command_name=COMMAND_NAME)
# @click.argument('pid', default=0)
# def main(pid):
#     """ Return the top-level parent (below the init or launchd process) Process ID (PID) for the given PID. If a PID is not specified, use
#         the current process.
# 
#         The top-level-pid command is part of Scripnix.
#     """
#     click.echo(penultimate_pid(pid))
# 
# def penultimate_pid(pid):
#     """ Recursively look up the parent PID and return the last PID found before pid==1 (init or launchd) is encountered.
#     """
#     if not pid:
#         pid = os.getpid()
# 
#     if pid == 1:
#         return pid
# 
#     try:
#         ppid = psutil.Process(pid).ppid()
#     except ValueError:
#         raise click.ClickException("Process ID '{}' must be a positive integer.".format(pid))
#     except psutil.NoSuchProcess:
#         raise click.ClickException("Process ID '{}' does not exist.".format(pid))
# 
#     if ppid in (0, 1) or pid == ppid:
#         return pid
#     else:
#         try:
#             return penultimate_pid(ppid)
#         except RuntimeError:
#             # Recursion depth reached: give up and return the last parent PID found.
#             return ppid
# 
# Path: tests/command.py
# def common_help_option(command_entry, command_name):
#     """ Test help message for both standard option switches."""
#     def version_option_switch(option_switch):
#         runner = CliRunner()
#         result = runner.invoke(command_entry, [option_switch])
#         assert result.exit_code == 0
#         match = HELP_OPTION_REGEX.match(result.output.replace("\n", ""))
#         assert match.group(1) == command_name
# 
#     version_option_switch("-h")
#     version_option_switch("--help")
# 
# def common_version_option(command_entry, command_name):
#     """ Test version message for both standard option switches."""
#     def version_option_switch(option_switch):
#         runner = CliRunner()
#         result = runner.invoke(command_entry, [option_switch])
#         assert result.exit_code == 0
#         match = VERSION_OPTION_REGEX.match(result.output.replace("\n", ""))
#         assert match.group(1) == command_name
#         assert match.group(2) == __version__
# 
#     version_option_switch("-V")
#     version_option_switch("--version")


import os
import click
import psutil
import pytest
from click.testing import CliRunner
from scripnix.pybin.top_level_pid import COMMAND_NAME, main, penultimate_pid
from .command import common_help_option, common_version_option

# This file is part of Scripnix. Copyright 2016 Dave Rogers <info@yukondude.com>. Licensed under the GNU General Public License, version 3.
# Refer to the attached LICENSE file or see <http://www.gnu.org/licenses/> for details.


# noinspection PyPackageRequirements




def test_help_option():
    common_help_option(command_entry=main, command_name=COMMAND_NAME)


def test_invalid_negative_penultimate_pid():
    with pytest.raises(click.ClickException) as excinfo:
        penultimate_pid(-1)

    assert str(excinfo).endswith("must be a positive integer.")


def test_invalid_pid_penultimate_pid():
    with pytest.raises(click.ClickException) as excinfo:
        penultimate_pid(999999)

    assert str(excinfo).endswith("does not exist.")


def test_main():
    runner = CliRunner()

# Path: scripnix/pybin/top_level_pid.py
# COMMAND_NAME = "top-level-pid"
# 
# @common_command_and_options(command_name=COMMAND_NAME)
# @click.argument('pid', default=0)
# def main(pid):
#     """ Return the top-level parent (below the init or launchd process) Process ID (PID) for the given PID. If a PID is not specified, use
#         the current process.
# 
#         The top-level-pid command is part of Scripnix.
#     """
#     click.echo(penultimate_pid(pid))
# 
# def penultimate_pid(pid):
#     """ Recursively look up the parent PID and return the last PID found before pid==1 (init or launchd) is encountered.
#     """
#     if not pid:
#         pid = os.getpid()
# 
#     if pid == 1:
#         return pid
# 
#     try:
#         ppid = psutil.Process(pid).ppid()
#     except ValueError:
#         raise click.ClickException("Process ID '{}' must be a positive integer.".format(pid))
#     except psutil.NoSuchProcess:
#         raise click.ClickException("Process ID '{}' does not exist.".format(pid))
# 
#     if ppid in (0, 1) or pid == ppid:
#         return pid
#     else:
#         try:
#             return penultimate_pid(ppid)
#         except RuntimeError:
#             # Recursion depth reached: give up and return the last parent PID found.
#             return ppid
# 
# Path: tests/command.py
# def common_help_option(command_entry, command_name):
#     """ Test help message for both standard option switches."""
#     def version_option_switch(option_switch):
#         runner = CliRunner()
#         result = runner.invoke(command_entry, [option_switch])
#         assert result.exit_code == 0
#         match = HELP_OPTION_REGEX.match(result.output.replace("\n", ""))
#         assert match.group(1) == command_name
# 
#     version_option_switch("-h")
#     version_option_switch("--help")
# 
# def common_version_option(command_entry, command_name):
#     """ Test version message for both standard option switches."""
#     def version_option_switch(option_switch):
#         runner = CliRunner()
#         result = runner.invoke(command_entry, [option_switch])
#         assert result.exit_code == 0
#         match = VERSION_OPTION_REGEX.match(result.output.replace("\n", ""))
#         assert match.group(1) == command_name
#         assert match.group(2) == __version__
# 
#     version_option_switch("-V")
#     version_option_switch("--version")


# Path: tests/test_top_level_pid.py
import os
import click
import psutil
import pytest
from click.testing import CliRunner
from scripnix.pybin.top_level_pid import COMMAND_NAME, main, penultimate_pid
from .command import common_help_option, common_version_option


# This file is part of Scripnix. Copyright 2016 Dave Rogers <info@yukondude.com>. Licensed under the GNU General Public License, version 3.
# Refer to the attached LICENSE file or see <http://www.gnu.org/licenses/> for details.


# noinspection PyPackageRequirements




def test_help_option():
    common_help_option(command_entry=main, command_name=COMMAND_NAME)


def test_invalid_negative_penultimate_pid():
    with pytest.raises(click.ClickException) as excinfo:
        penultimate_pid(-1)

    assert str(excinfo).endswith("must be a positive integer.")


def test_invalid_pid_penultimate_pid():
    with pytest.raises(click.ClickException) as excinfo:
        penultimate_pid(999999)

    assert str(excinfo).endswith("does not exist.")


def test_main():
    runner = CliRunner()

    result = runner.invoke(main)