def test_generic_redirect():
    expected_result = [
        ('[stdout] ', 'hello there!\n'),
        ('[stderr] ', 'meh meh mehhhh!\n'),
        ('[stdout] ', 'abcdefghij\n'),
        ('[stderr] ', 'ABCDEFGHIJ\n'),
        ('[stdout] ', 'klmn stranger\n'),
        ('[stdout] ', 'things\n'),
        ('[stdout] ', 'have\n'),
        ('[stderr] ', 'KLMN STRANGER\n'),
        ('[stderr] ', 'THINGS\n'),
        ('[stderr] ', 'HAVE\n'),
        ('[stdout] ', 'happened!\n'),
        ('[stderr] ', 'HAPPENED!\n')]

    # Used to retrieve the actual results from the TestOutputObserver subprocess.
    results = Queue()

    class TestOutputObserver(object):
        def __init__(self):
            self.actual_results = []

        def __call__(self, src, msg):
            self.actual_results.append((src, msg))

        def __enter__(self):
            pass

        # noinspection PyUnusedLocal
        def __exit__(self, exc_type, exc_val, exc_tb):
            results.put(self.actual_results)

    r = Redirect(TestOutputObserver())

    out = r.write_wrapper('[stdout] ')
    err = r.write_wrapper('[stderr] ')

    with r.context_manager():
        out.write('hello there!\n')
        err.write('meh meh mehhhh!\n')
        for c in 'abcde':
            out.write(c)
        for c in 'ABCDE':
            err.write(c)
        for c in 'fghij':
            out.write(c)
        for c in 'FGHIJ':
            err.write(c)
        out.write('\nklmn')
        err.write('\nKLMN')
        out.write(' stranger\nthings\nhave\nhappened!')
        err.write(' STRANGER\nTHINGS\nHAVE\nHAPPENED!')

    actual_results = results.get()

    pprint(actual_results)
    pprint(expected_result)

    assert actual_results == expected_result
Beispiel #2
0
class _SysRedirectWrapper(object):
    def __init__(self, output_observer, stdout_prefix='[stdout] ', stderr_prefix='[stderr] '):
        self.__stdout = sys.stdout
        self.__stderr = sys.stderr
        self.redirect = Redirect(output_observer)
        self.__stdout_proxy = self.redirect.write_wrapper(stdout_prefix)
        self.__stderr_proxy = self.redirect.write_wrapper(stderr_prefix)

    def __enter__(self):
        sys.stdout = self.__stdout_proxy
        sys.stderr = self.__stderr_proxy
        self.redirect.start()
        return self

    # noinspection PyUnusedLocal
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.redirect.stop()
        sys.stdout = self.__stdout
        sys.stderr = self.__stderr