diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py index 3b92c5444d..7f5fbbb0cb 100644 --- a/tests/integration/__init__.py +++ b/tests/integration/__init__.py @@ -24,7 +24,7 @@ import salt.minion import salt.runner from salt.utils import get_colors from salt.utils.verify import verify_env -from saltunittest import TestCase +from saltunittest import TestCase, RedirectStdStreams try: import console @@ -641,8 +641,9 @@ class ShellCase(TestCase): os.path.join(INTEGRATION_TEST_DIR, 'files', 'conf', 'master') ) opts.update({'doc': False, 'fun': fun, 'arg': arg}) - runner = salt.runner.Runner(opts) - ret['fun'] = runner.run() + with RedirectStdStreams(): + runner = salt.runner.Runner(opts) + ret['fun'] = runner.run() return ret def run_key(self, arg_str, catch_stderr=False): diff --git a/tests/saltunittest.py b/tests/saltunittest.py index 076d022b92..f430455dac 100644 --- a/tests/saltunittest.py +++ b/tests/saltunittest.py @@ -13,6 +13,9 @@ import sys import logging from functools import wraps +# Import salt libs +from salt.utils import fopen + # support python < 2.7 via unittest2 if sys.version_info[0:2] < (2, 7): try: @@ -55,6 +58,48 @@ def destructiveTest(func): return wrap +class RedirectStdStreams(object): + """ + Temporarily redirect system output to file like objects. + Default is to redirect to `os.devnull`, which just mutes output, `stdout` + and `stderr`. + """ + + def __init__(self, stdout=None, stderr=None): + if stdout is None: + stdout = fopen(os.devnull, 'w') + if stderr is None: + stderr = fopen(os.devnull, 'w') + + self.__stdout = stdout + self.__stderr = stderr + self.__redirected = False + + def __enter__(self): + self.redirect() + + def __exit__(self, exc_type, exc_value, traceback): + self.unredirect() + + def redirect(self): + self.old_stdout = sys.stdout + self.old_stdout.flush() + self.old_stderr = sys.stderr + self.old_stderr.flush() + sys.stdout = self.__stdout + sys.stderr = self.__stderr + self.__redirected = True + + def unredirect(self): + if not self.__redirected: + return + + self.__stdout.flush() + self.__stderr.flush() + sys.stdout = self.old_stdout + sys.stderr = self.old_stderr + + class TestsLoggingHandler(object): ''' Simple logging handler which can be used to test if certain logging