# Path: alibuild_helpers/cmd.py
# def execute(command, printer=debug):
#   kwargs = {} if sys.version_info.major < 3 else {"encoding": "utf-8"}
#   popen = Popen(command, shell=is_string(command), stdout=PIPE,
#                 universal_newlines=True, **kwargs)
#   lines_iterator = iter(popen.stdout.readline, "")
#   for line in lines_iterator:
#     if not line: break
#     printer("%s", line.strip("\n"))
#   out = popen.communicate()[0].strip("\n")
#   if out:
#     printer(out)
#   return popen.returncode
# 
# class DockerRunner:
#   """A context manager for running commands inside a Docker container.
# 
#   If the Docker image given is None or empty, the commands are run on the host
#   instead.
#   """
# 
#   def __init__(self, docker_image, docker_run_args=()):
#     self._docker_image = docker_image
#     self._docker_run_args = docker_run_args
#     self._container = None
# 
#   def __enter__(self):
#     if self._docker_image:
#       # "sleep inf" pauses forever, until we kill it.
#       cmd = ["docker", "run", "--detach", "--rm"]
#       cmd += self._docker_run_args
#       cmd += [self._docker_image, "sleep", "inf"]
#       self._container = getoutput(cmd).strip()
# 
#     def getstatusoutput_docker(cmd):
#       if self._container is None:
#         return getstatusoutput("{} -c {}".format(BASH, quote(cmd)))
#       return getstatusoutput("docker container exec {} bash -c {}"
#                              .format(quote(self._container), quote(cmd)))
# 
#     return getstatusoutput_docker
# 
#   def __exit__(self, exc_type, exc_value, traceback):
#     if self._container is not None:
#       # 'docker container stop' sends SIGTERM, which doesn't work on 'sleep'
#       # for some reason. Kill it directly instead, so we don't have to wait.
#       getstatusoutput("docker container kill " + quote(self._container))
#     self._container = None
#     return False   # propagate any exception that may have occurred


    from unittest import mock  # In Python 3, mock is built-in
from alibuild_helpers.cmd import execute, DockerRunner
    import mock  # Python 2
import unittest
# Assuming you are using the mock library to ... mock things
try:
except ImportError:



class CmdTestCase(unittest.TestCase):
    @mock.patch("alibuild_helpers.cmd.debug")
    def test_execute(self, mock_debug):
        err = execute("echo foo", mock_debug)
        self.assertEqual(err, 0)
        self.assertEqual(mock_debug.mock_calls, [mock.call("%s", "foo")])
        mock_debug.reset_mock()
        err = execute("echoo 2> /dev/null", mock_debug)
        self.assertEqual(err, 127)
        self.assertEqual(mock_debug.mock_calls, [])

    @mock.patch("alibuild_helpers.cmd.getoutput")
    @mock.patch("alibuild_helpers.cmd.getstatusoutput")
    def test_DockerRunner(self, mock_getstatusoutput, mock_getoutput):
        mock_getoutput.side_effect = lambda cmd: "container-id\n"
        with DockerRunner("image", ["extra arg"]) as getstatusoutput_docker:
            mock_getoutput.assert_called_with(["docker", "run", "--detach", "--rm",
                                               "extra arg", "image", "sleep", "inf"])
            getstatusoutput_docker("echo foo")
            mock_getstatusoutput.assert_called_with("docker container exec container-id bash -c 'echo foo'")
        mock_getstatusoutput.assert_called_with("docker container kill container-id")

        mock_getoutput.reset_mock()
        mock_getstatusoutput.reset_mock()

# Path: alibuild_helpers/cmd.py
# def execute(command, printer=debug):
#   kwargs = {} if sys.version_info.major < 3 else {"encoding": "utf-8"}
#   popen = Popen(command, shell=is_string(command), stdout=PIPE,
#                 universal_newlines=True, **kwargs)
#   lines_iterator = iter(popen.stdout.readline, "")
#   for line in lines_iterator:
#     if not line: break
#     printer("%s", line.strip("\n"))
#   out = popen.communicate()[0].strip("\n")
#   if out:
#     printer(out)
#   return popen.returncode
# 
# class DockerRunner:
#   """A context manager for running commands inside a Docker container.
# 
#   If the Docker image given is None or empty, the commands are run on the host
#   instead.
#   """
# 
#   def __init__(self, docker_image, docker_run_args=()):
#     self._docker_image = docker_image
#     self._docker_run_args = docker_run_args
#     self._container = None
# 
#   def __enter__(self):
#     if self._docker_image:
#       # "sleep inf" pauses forever, until we kill it.
#       cmd = ["docker", "run", "--detach", "--rm"]
#       cmd += self._docker_run_args
#       cmd += [self._docker_image, "sleep", "inf"]
#       self._container = getoutput(cmd).strip()
# 
#     def getstatusoutput_docker(cmd):
#       if self._container is None:
#         return getstatusoutput("{} -c {}".format(BASH, quote(cmd)))
#       return getstatusoutput("docker container exec {} bash -c {}"
#                              .format(quote(self._container), quote(cmd)))
# 
#     return getstatusoutput_docker
# 
#   def __exit__(self, exc_type, exc_value, traceback):
#     if self._container is not None:
#       # 'docker container stop' sends SIGTERM, which doesn't work on 'sleep'
#       # for some reason. Kill it directly instead, so we don't have to wait.
#       getstatusoutput("docker container kill " + quote(self._container))
#     self._container = None
#     return False   # propagate any exception that may have occurred


# Path: tests/test_cmd.py
    from unittest import mock  # In Python 3, mock is built-in
from alibuild_helpers.cmd import execute, DockerRunner
    import mock  # Python 2
import unittest

# Assuming you are using the mock library to ... mock things
try:
except ImportError:



class CmdTestCase(unittest.TestCase):
    @mock.patch("alibuild_helpers.cmd.debug")
    def test_execute(self, mock_debug):
        err = execute("echo foo", mock_debug)
        self.assertEqual(err, 0)
        self.assertEqual(mock_debug.mock_calls, [mock.call("%s", "foo")])
        mock_debug.reset_mock()
        err = execute("echoo 2> /dev/null", mock_debug)
        self.assertEqual(err, 127)
        self.assertEqual(mock_debug.mock_calls, [])

    @mock.patch("alibuild_helpers.cmd.getoutput")
    @mock.patch("alibuild_helpers.cmd.getstatusoutput")
    def test_DockerRunner(self, mock_getstatusoutput, mock_getoutput):
        mock_getoutput.side_effect = lambda cmd: "container-id\n"
        with DockerRunner("image", ["extra arg"]) as getstatusoutput_docker:
            mock_getoutput.assert_called_with(["docker", "run", "--detach", "--rm",
                                               "extra arg", "image", "sleep", "inf"])
            getstatusoutput_docker("echo foo")
            mock_getstatusoutput.assert_called_with("docker container exec container-id bash -c 'echo foo'")
        mock_getstatusoutput.assert_called_with("docker container kill container-id")

        mock_getoutput.reset_mock()
        mock_getstatusoutput.reset_mock()

        with DockerRunner("") as getstatusoutput_docker: