From abf291b0f943e0755b2e7fb0be5c429a50324881 Mon Sep 17 00:00:00 2001 From: Nikos Filippakis Date: Fri, 24 Mar 2017 00:15:25 +0100 Subject: [PATCH] scripts: redirect stdout to ctx.log.warn Redirect messages written to stdout in scripts to ctx.log.warn. (closes #1530) Signed-off-by: Nikos Filippakis --- mitmproxy/addons/script.py | 16 +++++++++++++- test/mitmproxy/addons/test_script.py | 27 ++++++++++++++++++----- test/mitmproxy/data/addonscripts/print.py | 2 ++ 3 files changed, 38 insertions(+), 7 deletions(-) create mode 100644 test/mitmproxy/data/addonscripts/print.py diff --git a/mitmproxy/addons/script.py b/mitmproxy/addons/script.py index 4d893f1c1..3b7a4f793 100644 --- a/mitmproxy/addons/script.py +++ b/mitmproxy/addons/script.py @@ -65,14 +65,28 @@ def cut_traceback(tb, func_name): return tb +class StreamLog: + """ + A class for redirecting output using contextlib. + """ + def __init__(self, log): + self.log = log + + def write(self, buf): + if buf.strip(): + self.log(buf) + + @contextlib.contextmanager def scriptenv(path, args): oldargs = sys.argv sys.argv = [path] + args script_dir = os.path.dirname(os.path.abspath(path)) sys.path.append(script_dir) + stdout_replacement = StreamLog(ctx.log.warn) try: - yield + with contextlib.redirect_stdout(stdout_replacement): + yield except SystemExit as v: ctx.log.error("Script exited with code %s" % v.code) except Exception: diff --git a/test/mitmproxy/addons/test_script.py b/test/mitmproxy/addons/test_script.py index 168274883..84d36e2a6 100644 --- a/test/mitmproxy/addons/test_script.py +++ b/test/mitmproxy/addons/test_script.py @@ -5,6 +5,7 @@ import re import watchdog.events import pytest +from unittest import mock from mitmproxy.test import tflow from mitmproxy.test import tutils from mitmproxy.test import taddons @@ -97,12 +98,26 @@ class TestParseCommand: def test_load_script(): - ns = script.load_script( - tutils.test_data.path( - "mitmproxy/data/addonscripts/recorder.py" - ), [] - ) - assert ns.start + with taddons.context(): + ns = script.load_script( + tutils.test_data.path( + "mitmproxy/data/addonscripts/recorder.py" + ), [] + ) + assert ns.start + + +def test_script_print_stdout(): + with taddons.context() as tctx: + with mock.patch('mitmproxy.ctx.log.warn') as mock_warn: + with script.scriptenv("path", []): + ns = script.load_script( + tutils.test_data.path( + "mitmproxy/data/addonscripts/print.py" + ), [] + ) + ns.start(tctx.options) + mock_warn.assert_called_once_with("stdoutprint") class TestScript: diff --git a/test/mitmproxy/data/addonscripts/print.py b/test/mitmproxy/data/addonscripts/print.py new file mode 100644 index 000000000..fdfcc3d94 --- /dev/null +++ b/test/mitmproxy/data/addonscripts/print.py @@ -0,0 +1,2 @@ +def start(opts): + print("stdoutprint")