simplify termlog outfile handling

This commit is contained in:
Thomas Kriechbaumer 2017-01-25 17:45:45 +01:00
parent ab45e4d183
commit 3028e06fd2
2 changed files with 28 additions and 22 deletions

View File

@ -7,24 +7,21 @@ from mitmproxy import log
class TermLog: class TermLog:
def __init__(self, outfile=None): def __init__(self, outfile=None):
self.options = None self.options = None
self.outfile = outfile or sys.stdout self.outfile = outfile
def configure(self, options, updated): def configure(self, options, updated):
self.options = options self.options = options
def log(self, e): def log(self, e):
def determine_outfile():
if log.log_tier(e.level) == log.log_tier("error"): if log.log_tier(e.level) == log.log_tier("error"):
self.outfile = sys.stderr outfile = self.outfile or sys.stderr
else: else:
self.outfile = sys.stdout outfile = self.outfile or sys.stdout
determine_outfile()
if self.options.verbosity >= log.log_tier(e.level): if self.options.verbosity >= log.log_tier(e.level):
click.secho( click.secho(
e.msg, e.msg,
file=self.outfile, file=outfile,
fg=dict(error="red", warn="yellow").get(e.level), fg=dict(error="red", warn="yellow").get(e.level),
dim=(e.level == "debug"), dim=(e.level == "debug"),
err=(e.level == "error") err=(e.level == "error")

View File

@ -1,18 +1,27 @@
import sys
import pytest
from mitmproxy.addons import termlog from mitmproxy.addons import termlog
from mitmproxy import log from mitmproxy import log
from mitmproxy.tools import dump from mitmproxy.tools.dump import Options
from mitmproxy.test import taddons
class TestTermLog: class TestTermLog:
def test_simple(self, capsys): @pytest.mark.usefixtures('capfd')
t = termlog.TermLog() @pytest.mark.parametrize('outfile, expected_out, expected_err', [
t.configure(dump.Options(verbosity = 2), set([])) (None, 'one\nthree\n', 'four\n'),
(sys.stdout, 'one\nthree\nfour\n', ''),
(sys.stderr, '', 'one\nthree\nfour\n'),
])
def test_output(self, outfile, expected_out, expected_err, capfd):
t = termlog.TermLog(outfile=outfile)
with taddons.context(options=Options(verbosity=2)) as tctx:
tctx.configure(t)
t.log(log.LogEntry("one", "info")) t.log(log.LogEntry("one", "info"))
t.log(log.LogEntry("two", "debug")) t.log(log.LogEntry("two", "debug"))
t.log(log.LogEntry("three", "warn")) t.log(log.LogEntry("three", "warn"))
t.log(log.LogEntry("four", "error")) t.log(log.LogEntry("four", "error"))
out, err = capsys.readouterr() out, err = capfd.readouterr()
assert "one" in out assert out == expected_out
assert "two" not in out assert err == expected_err
assert "three" in out
assert "four" in err