mirror of
https://github.com/Grasscutters/mitmproxy.git
synced 2024-11-23 00:01:36 +00:00
Merge pull request #2207 from nikofil/scripts-redirect-stdout
scripts: redirect stdout to ctx.log.warn
This commit is contained in:
commit
335861f490
@ -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:
|
||||
|
@ -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:
|
||||
|
2
test/mitmproxy/data/addonscripts/print.py
Normal file
2
test/mitmproxy/data/addonscripts/print.py
Normal file
@ -0,0 +1,2 @@
|
||||
def start(opts):
|
||||
print("stdoutprint")
|
Loading…
Reference in New Issue
Block a user