# Path: chopsticks/helpers.py
# def output_lines(*args, **kwargs):
#     """Return the lines of output from the given command args."""
#     return check_output(*args, **kwargs).splitlines()
# 
# Path: chopsticks/tunnel.py
# class Local(SubprocessTunnel):
#     """A tunnel to a subprocess on the same host."""
# 
#     def __init__(self, name='localhost'):
#         self.host = name
#         super(Local, self).__init__()
# 
# class Docker(SubprocessTunnel):
#     """A tunnel connected to a throwaway Docker container.
# 
#     :param name: The name of the Docker instance to create.
#     :param image: The Docker image to launch. By default, download and run an
#                   `official Docker Python image`__ corresponding to the
#                   running Python version. `Official images are curated by
#                   Docker`__.
#     :param rm: If true, destroy the container when the tunnel is closed.
# 
#     .. __: https://hub.docker.com/_/python/
#     .. __: https://docs.docker.com/docker-hub/official_repos/
# 
#     """
#     #: For the standard Python docker images, Python is not installed as
#     #: /usr/bin/python[23]
#     python2 = 'python'
#     python3 = 'python3'
# 
#     pyver = '{0}.{1}'.format(*sys.version_info)
# 
#     def __init__(self, name, image='python:' + pyver, rm=True):
#         self.host = name
#         self.image = image
#         self.rm = rm
#         super(Docker, self).__init__()
# 
#     def cmd_args(self):
#         base = super(Docker, self).cmd_args()
#         args = []
#         if self.rm:
#             args.append('--rm')
# 
#         return [
#             'docker',
#             'run',
#             '-i',
#             '--name',
#             self.host,
#         ] + args + [self.image] + base
# 
# class RemoteException(Exception):
#     """An exception from the remote agent."""
# 
# Path: chopsticks/facts.py
# def python_version(short=False):
#     """Get the Python version."""
#     if short:
#         return list(sys.version_info[:2])
#     return list(sys.version_info)


from unittest import TestCase
from chopsticks.helpers import output_lines
from chopsticks.tunnel import Local, Docker, RemoteException
from chopsticks.facts import python_version
"""Test that Chopsticks remote processes can launch tunnels."""


def ping_docker():
    """Start a docker container and read out its Python version."""
    with Docker('unittest-36', image='python:3.6') as tun:
        return tun.call(python_version)[:2]


def recursive():
    """Infinite recursion, requiring depth limit to stop."""
    with Local() as tun:
        tun.call(recursive)


class RecursiveTest(TestCase):
    docker_name = 'unittest-36'

    def tearDown(self):
        ls = output_lines(['docker', 'ps', '-a'])
        images = []
        for l in ls[1:]:
            ws = l.split()
            images.append(ws[-1])
        assert self.docker_name not in images, \
            "Image %r remained running after test" % self.docker_name

    def test_python_version(self):
        """We can start a sub-tunnel from within a tunnel."""

# Path: chopsticks/helpers.py
# def output_lines(*args, **kwargs):
#     """Return the lines of output from the given command args."""
#     return check_output(*args, **kwargs).splitlines()
# 
# Path: chopsticks/tunnel.py
# class Local(SubprocessTunnel):
#     """A tunnel to a subprocess on the same host."""
# 
#     def __init__(self, name='localhost'):
#         self.host = name
#         super(Local, self).__init__()
# 
# class Docker(SubprocessTunnel):
#     """A tunnel connected to a throwaway Docker container.
# 
#     :param name: The name of the Docker instance to create.
#     :param image: The Docker image to launch. By default, download and run an
#                   `official Docker Python image`__ corresponding to the
#                   running Python version. `Official images are curated by
#                   Docker`__.
#     :param rm: If true, destroy the container when the tunnel is closed.
# 
#     .. __: https://hub.docker.com/_/python/
#     .. __: https://docs.docker.com/docker-hub/official_repos/
# 
#     """
#     #: For the standard Python docker images, Python is not installed as
#     #: /usr/bin/python[23]
#     python2 = 'python'
#     python3 = 'python3'
# 
#     pyver = '{0}.{1}'.format(*sys.version_info)
# 
#     def __init__(self, name, image='python:' + pyver, rm=True):
#         self.host = name
#         self.image = image
#         self.rm = rm
#         super(Docker, self).__init__()
# 
#     def cmd_args(self):
#         base = super(Docker, self).cmd_args()
#         args = []
#         if self.rm:
#             args.append('--rm')
# 
#         return [
#             'docker',
#             'run',
#             '-i',
#             '--name',
#             self.host,
#         ] + args + [self.image] + base
# 
# class RemoteException(Exception):
#     """An exception from the remote agent."""
# 
# Path: chopsticks/facts.py
# def python_version(short=False):
#     """Get the Python version."""
#     if short:
#         return list(sys.version_info[:2])
#     return list(sys.version_info)


# Path: tests/test_recursive.py
from unittest import TestCase
from chopsticks.helpers import output_lines
from chopsticks.tunnel import Local, Docker, RemoteException
from chopsticks.facts import python_version

"""Test that Chopsticks remote processes can launch tunnels."""


def ping_docker():
    """Start a docker container and read out its Python version."""
    with Docker('unittest-36', image='python:3.6') as tun:
        return tun.call(python_version)[:2]


def recursive():
    """Infinite recursion, requiring depth limit to stop."""
    with Local() as tun:
        tun.call(recursive)


class RecursiveTest(TestCase):
    docker_name = 'unittest-36'

    def tearDown(self):
        ls = output_lines(['docker', 'ps', '-a'])
        images = []
        for l in ls[1:]:
            ws = l.split()
            images.append(ws[-1])
        assert self.docker_name not in images, \
            "Image %r remained running after test" % self.docker_name

    def test_python_version(self):
        """We can start a sub-tunnel from within a tunnel."""

        with Local() as tun: