# Path: cloudify/exceptions.py
# class CommandExecutionException(Exception):
# 
#     """
#     Indicates a command was executed, however some sort of error happened,
#     resulting in a non-zero return value of the process.
# 
#     :param command: The command executed
#     :param code: process exit code
#     :param error: process stderr output
#     :param output: process stdout output
#     """
# 
#     def __init__(self, command, error, output, code):
#         self.command = command
#         self.error = error
#         self.code = code
#         self.output = output
#         Exception.__init__(self, self.__str__())
# 
#     def __str__(self):
#         return "Command '{0}' executed with an error." \
#                "\ncode: {1}" \
#                "\nerror: {2}" \
#                "\noutput: {3}" \
#             .format(self.command, self.code,
#                     self.error or None,
#                     self.output or None)
# 
# Path: cloudify/utils.py
# def setup_logger(logger_name,
#                  logger_level=logging.INFO,
#                  handlers=None,
#                  remove_existing_handlers=True,
#                  logger_format=None,
#                  propagate=True):
#     """
#     :param logger_name: Name of the logger.
#     :param logger_level: Level for the logger (not for specific handler).
#     :param handlers: An optional list of handlers (formatter will be
#                      overridden); If None, only a StreamHandler for
#                      sys.stdout will be used.
#     :param remove_existing_handlers: Determines whether to remove existing
#                                      handlers before adding new ones
#     :param logger_format: the format this logger will have.
#     :param propagate: propagate the message the parent logger.
# 
#     :return: A logger instance.
#     :rtype: logging.Logger
#     """
#     if logger_format is None:
#         logger_format = '%(asctime)s [%(levelname)s] [%(name)s] %(message)s'
#     logger = logging.getLogger(logger_name)
# 
#     if remove_existing_handlers:
#         for handler in logger.handlers:
#             logger.removeHandler(handler)
# 
#     if not handlers:
#         handler = logging.StreamHandler(sys.stdout)
#         handler.setLevel(logging.DEBUG)
#         handlers = [handler]
# 
#     formatter = logging.Formatter(fmt=logger_format,
#                                   datefmt='%H:%M:%S')
#     for handler in handlers:
#         handler.setFormatter(formatter)
#         logger.addHandler(handler)
# 
#     logger.setLevel(logger_level)
#     if not propagate:
#         logger.propagate = False
#     return logger
# 
# def get_exec_tempdir():
#     """
#     Returns the directory to use for temporary files, when the intention
#     is to place an executable file there.
#     This is needed because some production systems disallow executions from
#     the default temporary directory.
#     """
#     return os.environ.get(CFY_EXEC_TEMPDIR_ENVVAR) or tempfile.gettempdir()
# 
# class LocalCommandRunner(object):
# 
#     def __init__(self, logger=None, host='localhost'):
# 
#         """
#         :param logger: This logger will be used for
#                        printing the output and the command.
#         """
# 
#         logger = logger or setup_logger('LocalCommandRunner')
#         self.logger = logger
#         self.host = host
# 
#     def run(self, command,
#             exit_on_failure=True,
#             stdout_pipe=True,
#             stderr_pipe=True,
#             cwd=None,
#             execution_env=None):
# 
#         """
#         Runs local commands.
# 
#         :param command: The command to execute.
#         :param exit_on_failure: False to ignore failures.
#         :param stdout_pipe: False to not pipe the standard output.
#         :param stderr_pipe: False to not pipe the standard error.
#         :param cwd: the working directory the command will run from.
#         :param execution_env: dictionary of environment variables that will
#                               be present in the command scope.
# 
#         :return: A wrapper object for all valuable info from the execution.
#         :rtype: cloudify.utils.CommandExecutionResponse
#         """
# 
#         if isinstance(command, list):
#             popen_args = command
#         else:
#             popen_args = _shlex_split(command)
#         self.logger.debug('[{0}] run: {1}'.format(self.host, popen_args))
#         stdout = subprocess.PIPE if stdout_pipe else None
#         stderr = subprocess.PIPE if stderr_pipe else None
#         command_env = os.environ.copy()
#         command_env.update(execution_env or {})
#         p = subprocess.Popen(args=popen_args, stdout=stdout,
#                              stderr=stderr, cwd=cwd, env=command_env)
#         out, err = p.communicate()
#         if out:
#             out = out.rstrip()
#         if err:
#             err = err.rstrip()
# 
#         if p.returncode != 0:
#             error = CommandExecutionException(
#                 command=command,
#                 error=err,
#                 output=out,
#                 code=p.returncode)
#             if exit_on_failure:
#                 raise error
#             else:
#                 self.logger.error(error)
# 
#         return CommandExecutionResponse(
#             command=command,
#             std_out=out,
#             std_err=err,
#             return_code=p.returncode)


import os
import mock
import logging
import tempfile
import unittest
from cloudify.exceptions import CommandExecutionException
from cloudify.utils import setup_logger, get_exec_tempdir, LocalCommandRunner
########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
#    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    * See the License for the specific language governing permissions and
#    * limitations under the License.




class LocalCommandRunnerTest(unittest.TestCase):

    runner = None

    @classmethod
    def setUpClass(cls):

# Path: cloudify/exceptions.py
# class CommandExecutionException(Exception):
# 
#     """
#     Indicates a command was executed, however some sort of error happened,
#     resulting in a non-zero return value of the process.
# 
#     :param command: The command executed
#     :param code: process exit code
#     :param error: process stderr output
#     :param output: process stdout output
#     """
# 
#     def __init__(self, command, error, output, code):
#         self.command = command
#         self.error = error
#         self.code = code
#         self.output = output
#         Exception.__init__(self, self.__str__())
# 
#     def __str__(self):
#         return "Command '{0}' executed with an error." \
#                "\ncode: {1}" \
#                "\nerror: {2}" \
#                "\noutput: {3}" \
#             .format(self.command, self.code,
#                     self.error or None,
#                     self.output or None)
# 
# Path: cloudify/utils.py
# def setup_logger(logger_name,
#                  logger_level=logging.INFO,
#                  handlers=None,
#                  remove_existing_handlers=True,
#                  logger_format=None,
#                  propagate=True):
#     """
#     :param logger_name: Name of the logger.
#     :param logger_level: Level for the logger (not for specific handler).
#     :param handlers: An optional list of handlers (formatter will be
#                      overridden); If None, only a StreamHandler for
#                      sys.stdout will be used.
#     :param remove_existing_handlers: Determines whether to remove existing
#                                      handlers before adding new ones
#     :param logger_format: the format this logger will have.
#     :param propagate: propagate the message the parent logger.
# 
#     :return: A logger instance.
#     :rtype: logging.Logger
#     """
#     if logger_format is None:
#         logger_format = '%(asctime)s [%(levelname)s] [%(name)s] %(message)s'
#     logger = logging.getLogger(logger_name)
# 
#     if remove_existing_handlers:
#         for handler in logger.handlers:
#             logger.removeHandler(handler)
# 
#     if not handlers:
#         handler = logging.StreamHandler(sys.stdout)
#         handler.setLevel(logging.DEBUG)
#         handlers = [handler]
# 
#     formatter = logging.Formatter(fmt=logger_format,
#                                   datefmt='%H:%M:%S')
#     for handler in handlers:
#         handler.setFormatter(formatter)
#         logger.addHandler(handler)
# 
#     logger.setLevel(logger_level)
#     if not propagate:
#         logger.propagate = False
#     return logger
# 
# def get_exec_tempdir():
#     """
#     Returns the directory to use for temporary files, when the intention
#     is to place an executable file there.
#     This is needed because some production systems disallow executions from
#     the default temporary directory.
#     """
#     return os.environ.get(CFY_EXEC_TEMPDIR_ENVVAR) or tempfile.gettempdir()
# 
# class LocalCommandRunner(object):
# 
#     def __init__(self, logger=None, host='localhost'):
# 
#         """
#         :param logger: This logger will be used for
#                        printing the output and the command.
#         """
# 
#         logger = logger or setup_logger('LocalCommandRunner')
#         self.logger = logger
#         self.host = host
# 
#     def run(self, command,
#             exit_on_failure=True,
#             stdout_pipe=True,
#             stderr_pipe=True,
#             cwd=None,
#             execution_env=None):
# 
#         """
#         Runs local commands.
# 
#         :param command: The command to execute.
#         :param exit_on_failure: False to ignore failures.
#         :param stdout_pipe: False to not pipe the standard output.
#         :param stderr_pipe: False to not pipe the standard error.
#         :param cwd: the working directory the command will run from.
#         :param execution_env: dictionary of environment variables that will
#                               be present in the command scope.
# 
#         :return: A wrapper object for all valuable info from the execution.
#         :rtype: cloudify.utils.CommandExecutionResponse
#         """
# 
#         if isinstance(command, list):
#             popen_args = command
#         else:
#             popen_args = _shlex_split(command)
#         self.logger.debug('[{0}] run: {1}'.format(self.host, popen_args))
#         stdout = subprocess.PIPE if stdout_pipe else None
#         stderr = subprocess.PIPE if stderr_pipe else None
#         command_env = os.environ.copy()
#         command_env.update(execution_env or {})
#         p = subprocess.Popen(args=popen_args, stdout=stdout,
#                              stderr=stderr, cwd=cwd, env=command_env)
#         out, err = p.communicate()
#         if out:
#             out = out.rstrip()
#         if err:
#             err = err.rstrip()
# 
#         if p.returncode != 0:
#             error = CommandExecutionException(
#                 command=command,
#                 error=err,
#                 output=out,
#                 code=p.returncode)
#             if exit_on_failure:
#                 raise error
#             else:
#                 self.logger.error(error)
# 
#         return CommandExecutionResponse(
#             command=command,
#             std_out=out,
#             std_err=err,
#             return_code=p.returncode)


# Path: cloudify/tests/test_utils.py
import os
import mock
import logging
import tempfile
import unittest
from cloudify.exceptions import CommandExecutionException
from cloudify.utils import setup_logger, get_exec_tempdir, LocalCommandRunner

########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
#    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    * See the License for the specific language governing permissions and
#    * limitations under the License.




class LocalCommandRunnerTest(unittest.TestCase):

    runner = None

    @classmethod
    def setUpClass(cls):

        cls.logger = setup_logger(cls.__name__)