The following issues were found
examples/contrib/webscanner_helper/urldict.py
14 issues
Line: 7
Column: 1
from collections.abc import MutableMapping
from typing import Any, Dict, Generator, List, TextIO, Callable
from mitmproxy import flowfilter
from mitmproxy.http import HTTPFlow
def f_id(x):
return x
Reported by Pylint.
Line: 8
Column: 1
from typing import Any, Dict, Generator, List, TextIO, Callable
from mitmproxy import flowfilter
from mitmproxy.http import HTTPFlow
def f_id(x):
return x
Reported by Pylint.
Line: 54
Column: 5
if flowfilter.match(fltr, flow):
yield value
def get(self, flow: HTTPFlow, default=None, *, count=0) -> List[Any]:
try:
return self.__getitem__(flow, count=count)
except KeyError:
return default
Reported by Pylint.
Line: 1
Column: 1
import itertools
import json
import typing
from collections.abc import MutableMapping
from typing import Any, Dict, Generator, List, TextIO, Callable
from mitmproxy import flowfilter
from mitmproxy.http import HTTPFlow
Reported by Pylint.
Line: 11
Column: 1
from mitmproxy.http import HTTPFlow
def f_id(x):
return x
class URLDict(MutableMapping):
"""Data structure to store information using filters as keys."""
Reported by Pylint.
Line: 11
Column: 1
from mitmproxy.http import HTTPFlow
def f_id(x):
return x
class URLDict(MutableMapping):
"""Data structure to store information using filters as keys."""
Reported by Pylint.
Line: 27
Column: 9
else:
ret = list(self.get_generator(key))
if ret:
return ret
else:
raise KeyError
def __setitem__(self, key: str, value):
Reported by Pylint.
Line: 48
Column: 5
def __len__(self):
return self.store.__len__()
def get_generator(self, flow: HTTPFlow) -> Generator[Any, None, None]:
for fltr, value in self.store.items():
if flowfilter.match(fltr, flow):
yield value
Reported by Pylint.
Line: 68
Column: 5
return url_dict
@classmethod
def load(cls, f: TextIO, value_loader: Callable = f_id):
json_obj = json.load(f)
return cls._load(json_obj, value_loader)
@classmethod
def loads(cls, json_str: str, value_loader: Callable = f_id):
Reported by Pylint.
Line: 68
Column: 5
return url_dict
@classmethod
def load(cls, f: TextIO, value_loader: Callable = f_id):
json_obj = json.load(f)
return cls._load(json_obj, value_loader)
@classmethod
def loads(cls, json_str: str, value_loader: Callable = f_id):
Reported by Pylint.
mitmproxy/tools/console/grideditor/col_text.py
14 issues
Line: 12
Column: 1
from mitmproxy.tools.console.grideditor import col_bytes
class Column(col_bytes.Column):
def __init__(self, heading, encoding="utf8", errors="surrogateescape"):
super().__init__(heading)
self.encoding_args = encoding, errors
def Display(self, data):
Reported by Pylint.
Line: 17
Column: 5
super().__init__(heading)
self.encoding_args = encoding, errors
def Display(self, data):
return TDisplay(data, self.encoding_args)
def Edit(self, data):
return TEdit(data, self.encoding_args)
Reported by Pylint.
Line: 17
Column: 5
super().__init__(heading)
self.encoding_args = encoding, errors
def Display(self, data):
return TDisplay(data, self.encoding_args)
def Edit(self, data):
return TEdit(data, self.encoding_args)
Reported by Pylint.
Line: 20
Column: 5
def Display(self, data):
return TDisplay(data, self.encoding_args)
def Edit(self, data):
return TEdit(data, self.encoding_args)
def blank(self):
return ""
Reported by Pylint.
Line: 20
Column: 5
def Display(self, data):
return TDisplay(data, self.encoding_args)
def Edit(self, data):
return TEdit(data, self.encoding_args)
def blank(self):
return ""
Reported by Pylint.
Line: 23
Column: 5
def Edit(self, data):
return TEdit(data, self.encoding_args)
def blank(self):
return ""
# This is the same for both edit and display.
class EncodingMixin:
Reported by Pylint.
Line: 23
Column: 5
def Edit(self, data):
return TEdit(data, self.encoding_args)
def blank(self):
return ""
# This is the same for both edit and display.
class EncodingMixin:
Reported by Pylint.
Line: 28
Column: 1
# This is the same for both edit and display.
class EncodingMixin:
def __init__(self, data, encoding_args):
self.encoding_args = encoding_args
super().__init__(data.__str__().encode(*self.encoding_args))
def get_data(self):
Reported by Pylint.
Line: 28
Column: 1
# This is the same for both edit and display.
class EncodingMixin:
def __init__(self, data, encoding_args):
self.encoding_args = encoding_args
super().__init__(data.__str__().encode(*self.encoding_args))
def get_data(self):
Reported by Pylint.
Line: 33
Column: 5
self.encoding_args = encoding_args
super().__init__(data.__str__().encode(*self.encoding_args))
def get_data(self):
data = super().get_data()
try:
return data.decode(*self.encoding_args)
except ValueError:
signals.status_message.send(
Reported by Pylint.
test/filename_matching.py
14 issues
Line: 62
Column: 3
unknown_test_files = check_test_files_have_src()
if unknown_test_files:
# TODO: enable this in the future
# exitcode += 1
for f, p in sorted(unknown_test_files):
print(f"{f} DOES NOT MATCH a source file! Expected to find: {p}")
sys.exit(exitcode)
Reported by Pylint.
Line: 1
Column: 1
#!/usr/bin/env python3
import os
import re
import glob
import sys
def check_src_files_have_test():
Reported by Pylint.
Line: 9
Column: 1
import sys
def check_src_files_have_test():
missing_test_files = []
excluded = [
'mitmproxy/contrib/',
'mitmproxy/io/proto/',
Reported by Pylint.
Line: 23
Column: 9
src_files = glob.glob('mitmproxy/**/*.py', recursive=True)
src_files = [f for f in src_files if os.path.basename(f) != '__init__.py']
src_files = [f for f in src_files if not any(os.path.normpath(p) in f for p in excluded)]
for f in src_files:
p = os.path.join("test", os.path.dirname(f), "test_" + os.path.basename(f))
if not os.path.isfile(p):
missing_test_files.append((f, p))
return missing_test_files
Reported by Pylint.
Line: 24
Column: 9
src_files = [f for f in src_files if os.path.basename(f) != '__init__.py']
src_files = [f for f in src_files if not any(os.path.normpath(p) in f for p in excluded)]
for f in src_files:
p = os.path.join("test", os.path.dirname(f), "test_" + os.path.basename(f))
if not os.path.isfile(p):
missing_test_files.append((f, p))
return missing_test_files
Reported by Pylint.
Line: 31
Column: 1
return missing_test_files
def check_test_files_have_src():
unknown_test_files = []
excluded = [
'test/mitmproxy/data/',
'test/mitmproxy/net/data/',
Reported by Pylint.
Line: 43
Column: 9
test_files = glob.glob('test/mitmproxy/**/*.py', recursive=True)
test_files = [f for f in test_files if os.path.basename(f) != '__init__.py']
test_files = [f for f in test_files if not any(os.path.normpath(p) in f for p in excluded)]
for f in test_files:
p = os.path.join(re.sub('^test/', '', os.path.dirname(f)), re.sub('^test_', '', os.path.basename(f)))
if not os.path.isfile(p):
unknown_test_files.append((f, p))
return unknown_test_files
Reported by Pylint.
Line: 44
Column: 1
test_files = [f for f in test_files if os.path.basename(f) != '__init__.py']
test_files = [f for f in test_files if not any(os.path.normpath(p) in f for p in excluded)]
for f in test_files:
p = os.path.join(re.sub('^test/', '', os.path.dirname(f)), re.sub('^test_', '', os.path.basename(f)))
if not os.path.isfile(p):
unknown_test_files.append((f, p))
return unknown_test_files
Reported by Pylint.
Line: 44
Column: 9
test_files = [f for f in test_files if os.path.basename(f) != '__init__.py']
test_files = [f for f in test_files if not any(os.path.normpath(p) in f for p in excluded)]
for f in test_files:
p = os.path.join(re.sub('^test/', '', os.path.dirname(f)), re.sub('^test_', '', os.path.basename(f)))
if not os.path.isfile(p):
unknown_test_files.append((f, p))
return unknown_test_files
Reported by Pylint.
Line: 51
Column: 1
return unknown_test_files
def main():
exitcode = 0
missing_test_files = check_src_files_have_test()
if missing_test_files:
exitcode += 1
Reported by Pylint.
test/mitmproxy/contentviews/image/test_image_parser.py
14 issues
Line: 1
Column: 1
import pytest
from mitmproxy.contentviews.image import image_parser
@pytest.mark.parametrize("filename, metadata", {
# no textual data
"mitmproxy/data/image_parser/ct0n0g04.png": [
('Format', 'Portable network graphics'),
Reported by Pylint.
Line: 1
Column: 1
import pytest
from mitmproxy.contentviews.image import image_parser
@pytest.mark.parametrize("filename, metadata", {
# no textual data
"mitmproxy/data/image_parser/ct0n0g04.png": [
('Format', 'Portable network graphics'),
Reported by Pylint.
Line: 71
Column: 1
('aspect', '72 x 72'),
('date:create', '2012-07-11T14:04:52-07:00'),
('date:modify', '2012-07-11T14:04:52-07:00')
],
}.items())
def test_parse_png(filename, metadata, tdata):
with open(tdata.path(filename), "rb") as f:
assert metadata == image_parser.parse_png(f.read())
Reported by Pylint.
Line: 74
Column: 46
],
}.items())
def test_parse_png(filename, metadata, tdata):
with open(tdata.path(filename), "rb") as f:
assert metadata == image_parser.parse_png(f.read())
@pytest.mark.parametrize("filename, metadata", {
# check comment
Reported by Pylint.
Line: 75
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
}.items())
def test_parse_png(filename, metadata, tdata):
with open(tdata.path(filename), "rb") as f:
assert metadata == image_parser.parse_png(f.read())
@pytest.mark.parametrize("filename, metadata", {
# check comment
"mitmproxy/data/image_parser/hopper.gif": [
Reported by Bandit.
Line: 101
Column: 1
('Version', 'GIF89a'),
('Size', '245 x 245 px'),
('background', '0')
],
}.items())
def test_parse_gif(filename, metadata, tdata):
with open(tdata.path(filename), 'rb') as f:
assert metadata == image_parser.parse_gif(f.read())
Reported by Pylint.
Line: 104
Column: 46
],
}.items())
def test_parse_gif(filename, metadata, tdata):
with open(tdata.path(filename), 'rb') as f:
assert metadata == image_parser.parse_gif(f.read())
@pytest.mark.parametrize("filename, metadata", {
# check app0
Reported by Pylint.
Line: 105
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
}.items())
def test_parse_gif(filename, metadata, tdata):
with open(tdata.path(filename), 'rb') as f:
assert metadata == image_parser.parse_gif(f.read())
@pytest.mark.parametrize("filename, metadata", {
# check app0
"mitmproxy/data/image_parser/example.jpg": [
Reported by Bandit.
Line: 164
Column: 1
'\\r\\nTitle: Inferno, from the Divine Comedy by Dante (Folio 1v)\\r\\nTime-line:'
' 1401-1450\\r\\nSchool: Italian\\r\\nForm: illumination\\r\\nType: other\\r\\n\''),
('Size', '750 x 1055 px')
],
}.items())
def test_parse_jpeg(filename, metadata, tdata):
with open(tdata.path(filename), 'rb') as f:
assert metadata == image_parser.parse_jpeg(f.read())
Reported by Pylint.
Line: 167
Column: 46
],
}.items())
def test_parse_jpeg(filename, metadata, tdata):
with open(tdata.path(filename), 'rb') as f:
assert metadata == image_parser.parse_jpeg(f.read())
@pytest.mark.parametrize("filename, metadata", {
"mitmproxy/data/image.ico": [
Reported by Pylint.
test/individual_coverage.py
14 issues
Line: 11
Column: 1
import multiprocessing
import configparser
import itertools
import pytest
def run_tests(src, test, fail):
stderr = io.StringIO()
stdout = io.StringIO()
Reported by Pylint.
Line: 80
Column: 9
if any(e != 0 for _, _, e in result):
sys.exit(1)
pass
if __name__ == '__main__':
main()
Reported by Pylint.
Line: 1
Column: 1
#!/usr/bin/env python3
import io
import contextlib
import os
import sys
import glob
import multiprocessing
import configparser
Reported by Pylint.
Line: 14
Column: 1
import pytest
def run_tests(src, test, fail):
stderr = io.StringIO()
stdout = io.StringIO()
with contextlib.redirect_stderr(stderr):
with contextlib.redirect_stdout(stdout):
e = pytest.main([
Reported by Pylint.
Line: 19
Column: 13
stdout = io.StringIO()
with contextlib.redirect_stderr(stderr):
with contextlib.redirect_stdout(stdout):
e = pytest.main([
'-qq',
'--disable-pytest-warnings',
'--cov', src.replace('.py', '').replace('/', '.'),
'--cov-fail-under', '100',
'--cov-report', 'term-missing:skip-covered',
Reported by Pylint.
Line: 31
Column: 1
if e == 0:
if fail:
print("FAIL DUE TO UNEXPECTED SUCCESS:", src, "Please remove this file from setup.cfg tool:individual_coverage/exclude.")
e = 42
else:
print(".")
else:
if fail:
Reported by Pylint.
Line: 32
Column: 13
if e == 0:
if fail:
print("FAIL DUE TO UNEXPECTED SUCCESS:", src, "Please remove this file from setup.cfg tool:individual_coverage/exclude.")
e = 42
else:
print(".")
else:
if fail:
print("Ignoring allowed fail:", src)
Reported by Pylint.
Line: 38
Column: 13
else:
if fail:
print("Ignoring allowed fail:", src)
e = 0
else:
cov = [l for l in stdout.getvalue().split("\n") if (src in l) or ("was never imported" in l)]
if len(cov) == 1:
print("FAIL:", cov[0])
else:
Reported by Pylint.
Line: 40
Column: 1
print("Ignoring allowed fail:", src)
e = 0
else:
cov = [l for l in stdout.getvalue().split("\n") if (src in l) or ("was never imported" in l)]
if len(cov) == 1:
print("FAIL:", cov[0])
else:
print("FAIL:", src, test, stdout.getvalue(), stdout.getvalue())
print(stderr.getvalue())
Reported by Pylint.
Line: 51
Column: 1
sys.exit(e)
def start_pytest(src, test, fail):
# run pytest in a new process, otherwise imports and modules might conflict
proc = multiprocessing.Process(target=run_tests, args=(src, test, fail))
proc.start()
proc.join()
return (src, test, proc.exitcode)
Reported by Pylint.
test/mitmproxy/test_command_lexer.py
14 issues
Line: 2
Column: 1
import pyparsing
import pytest
from hypothesis import given, example
from hypothesis.strategies import text
from mitmproxy import command_lexer
@pytest.mark.parametrize(
Reported by Pylint.
Line: 3
Column: 1
import pyparsing
import pytest
from hypothesis import given, example
from hypothesis.strategies import text
from mitmproxy import command_lexer
@pytest.mark.parametrize(
Reported by Pylint.
Line: 4
Column: 1
import pyparsing
import pytest
from hypothesis import given, example
from hypothesis.strategies import text
from mitmproxy import command_lexer
@pytest.mark.parametrize(
Reported by Pylint.
Line: 1
Column: 1
import pyparsing
import pytest
from hypothesis import given, example
from hypothesis.strategies import text
from mitmproxy import command_lexer
@pytest.mark.parametrize(
Reported by Pylint.
Line: 19
Column: 1
('''"foo ''', True),
('''"foo 'bar' ''', True),
('"foo\\', True),
]
)
def test_partial_quoted_string(test_input, valid):
if valid:
assert command_lexer.PartialQuotedString.parseString(test_input, parseAll=True)[0] == test_input
else:
Reported by Pylint.
Line: 23
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
)
def test_partial_quoted_string(test_input, valid):
if valid:
assert command_lexer.PartialQuotedString.parseString(test_input, parseAll=True)[0] == test_input
else:
with pytest.raises(pyparsing.ParseException):
command_lexer.PartialQuotedString.parseString(test_input, parseAll=True)
Reported by Bandit.
Line: 23
Column: 1
)
def test_partial_quoted_string(test_input, valid):
if valid:
assert command_lexer.PartialQuotedString.parseString(test_input, parseAll=True)[0] == test_input
else:
with pytest.raises(pyparsing.ParseException):
command_lexer.PartialQuotedString.parseString(test_input, parseAll=True)
Reported by Pylint.
Line: 38
Column: 1
('''"foo''', ['"foo']),
('''"foo 'bar' ''', ['''"foo 'bar' ''']),
('"foo\\', ['"foo\\']),
]
)
def test_expr(test_input, expected):
assert list(command_lexer.expr.parseString(test_input, parseAll=True)) == expected
Reported by Pylint.
Line: 41
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
]
)
def test_expr(test_input, expected):
assert list(command_lexer.expr.parseString(test_input, parseAll=True)) == expected
@given(text())
@example(r"foo")
@example(r"'foo\''")
Reported by Bandit.
Line: 56
Column: 1
@example("\"foo\\\\'\"")
@example('\'foo\\"\'')
@example(r"\\\foo")
def test_quote_unquote_cycle(s):
assert command_lexer.unquote(command_lexer.quote(s)).replace(r"\x22", '"') == s
@given(text())
@example("'foo\\'")
Reported by Pylint.
test/mitmproxy/test_log.py
13 issues
Line: 1
Column: 1
from mitmproxy import log
def test_logentry():
e = log.LogEntry("foo", "info")
assert repr(e) == "LogEntry(foo, info)"
f = log.LogEntry("foo", "warning")
assert e == e
Reported by Pylint.
Line: 4
Column: 1
from mitmproxy import log
def test_logentry():
e = log.LogEntry("foo", "info")
assert repr(e) == "LogEntry(foo, info)"
f = log.LogEntry("foo", "warning")
assert e == e
Reported by Pylint.
Line: 5
Column: 5
def test_logentry():
e = log.LogEntry("foo", "info")
assert repr(e) == "LogEntry(foo, info)"
f = log.LogEntry("foo", "warning")
assert e == e
assert e != f
Reported by Pylint.
Line: 6
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
def test_logentry():
e = log.LogEntry("foo", "info")
assert repr(e) == "LogEntry(foo, info)"
f = log.LogEntry("foo", "warning")
assert e == e
assert e != f
assert e != 42
Reported by Bandit.
Line: 8
Column: 5
e = log.LogEntry("foo", "info")
assert repr(e) == "LogEntry(foo, info)"
f = log.LogEntry("foo", "warning")
assert e == e
assert e != f
assert e != 42
Reported by Pylint.
Line: 9
Column: 12
assert repr(e) == "LogEntry(foo, info)"
f = log.LogEntry("foo", "warning")
assert e == e
assert e != f
assert e != 42
def test_dont_pick_up_mutations():
Reported by Pylint.
Line: 9
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
assert repr(e) == "LogEntry(foo, info)"
f = log.LogEntry("foo", "warning")
assert e == e
assert e != f
assert e != 42
def test_dont_pick_up_mutations():
Reported by Bandit.
Line: 10
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
f = log.LogEntry("foo", "warning")
assert e == e
assert e != f
assert e != 42
def test_dont_pick_up_mutations():
x = {"foo": "bar"}
Reported by Bandit.
Line: 11
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
f = log.LogEntry("foo", "warning")
assert e == e
assert e != f
assert e != 42
def test_dont_pick_up_mutations():
x = {"foo": "bar"}
e = log.LogEntry(x, "info")
Reported by Bandit.
Line: 14
Column: 1
assert e != 42
def test_dont_pick_up_mutations():
x = {"foo": "bar"}
e = log.LogEntry(x, "info")
x["foo"] = "baz" # this should not affect the log entry anymore.
assert repr(e) == "LogEntry({'foo': 'bar'}, info)"
Reported by Pylint.
test/mitmproxy/net/http/test_headers.py
13 issues
Line: 1
Column: 1
import collections
from mitmproxy.net.http.headers import parse_content_type, assemble_content_type
def test_parse_content_type():
p = parse_content_type
assert p("text/html") == ("text", "html", {})
assert p("text") is None
Reported by Pylint.
Line: 6
Column: 1
from mitmproxy.net.http.headers import parse_content_type, assemble_content_type
def test_parse_content_type():
p = parse_content_type
assert p("text/html") == ("text", "html", {})
assert p("text") is None
v = p("text/html; charset=UTF-8")
Reported by Pylint.
Line: 7
Column: 5
def test_parse_content_type():
p = parse_content_type
assert p("text/html") == ("text", "html", {})
assert p("text") is None
v = p("text/html; charset=UTF-8")
assert v == ('text', 'html', {'charset': 'UTF-8'})
Reported by Pylint.
Line: 8
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
def test_parse_content_type():
p = parse_content_type
assert p("text/html") == ("text", "html", {})
assert p("text") is None
v = p("text/html; charset=UTF-8")
assert v == ('text', 'html', {'charset': 'UTF-8'})
Reported by Bandit.
Line: 9
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
def test_parse_content_type():
p = parse_content_type
assert p("text/html") == ("text", "html", {})
assert p("text") is None
v = p("text/html; charset=UTF-8")
assert v == ('text', 'html', {'charset': 'UTF-8'})
Reported by Bandit.
Line: 11
Column: 5
assert p("text/html") == ("text", "html", {})
assert p("text") is None
v = p("text/html; charset=UTF-8")
assert v == ('text', 'html', {'charset': 'UTF-8'})
def test_assemble_content_type():
p = assemble_content_type
Reported by Pylint.
Line: 12
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
assert p("text") is None
v = p("text/html; charset=UTF-8")
assert v == ('text', 'html', {'charset': 'UTF-8'})
def test_assemble_content_type():
p = assemble_content_type
assert p("text", "html", {}) == "text/html"
Reported by Bandit.
Line: 15
Column: 1
assert v == ('text', 'html', {'charset': 'UTF-8'})
def test_assemble_content_type():
p = assemble_content_type
assert p("text", "html", {}) == "text/html"
assert p("text", "html", {"charset": "utf8"}) == "text/html; charset=utf8"
assert p("text", "html",
collections.OrderedDict([("charset", "utf8"), ("foo", "bar")])) == "text/html; charset=utf8; foo=bar"
Reported by Pylint.
Line: 16
Column: 5
def test_assemble_content_type():
p = assemble_content_type
assert p("text", "html", {}) == "text/html"
assert p("text", "html", {"charset": "utf8"}) == "text/html; charset=utf8"
assert p("text", "html",
collections.OrderedDict([("charset", "utf8"), ("foo", "bar")])) == "text/html; charset=utf8; foo=bar"
Reported by Pylint.
Line: 17
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
def test_assemble_content_type():
p = assemble_content_type
assert p("text", "html", {}) == "text/html"
assert p("text", "html", {"charset": "utf8"}) == "text/html; charset=utf8"
assert p("text", "html",
collections.OrderedDict([("charset", "utf8"), ("foo", "bar")])) == "text/html; charset=utf8; foo=bar"
Reported by Bandit.
mitmproxy/addons/modifybody.py
13 issues
Line: 1
Column: 1
import re
import typing
from mitmproxy import ctx, exceptions
from mitmproxy.addons.modifyheaders import parse_modify_spec, ModifySpec
class ModifyBody:
def __init__(self):
Reported by Pylint.
Line: 8
Column: 1
from mitmproxy.addons.modifyheaders import parse_modify_spec, ModifySpec
class ModifyBody:
def __init__(self):
self.replacements: typing.List[ModifySpec] = []
def load(self, loader):
loader.add_option(
Reported by Pylint.
Line: 12
Column: 5
def __init__(self):
self.replacements: typing.List[ModifySpec] = []
def load(self, loader):
loader.add_option(
"modify_body", typing.Sequence[str], [],
"""
Replacement pattern of the form "[/flow-filter]/regex/[@]replacement", where
the separator can be any character. The @ allows to provide a file path that
Reported by Pylint.
Line: 12
Column: 5
def __init__(self):
self.replacements: typing.List[ModifySpec] = []
def load(self, loader):
loader.add_option(
"modify_body", typing.Sequence[str], [],
"""
Replacement pattern of the form "[/flow-filter]/regex/[@]replacement", where
the separator can be any character. The @ allows to provide a file path that
Reported by Pylint.
Line: 22
Column: 5
"""
)
def configure(self, updated):
if "modify_body" in updated:
self.replacements = []
for option in ctx.options.modify_body:
try:
spec = parse_modify_spec(option, True)
Reported by Pylint.
Line: 28
Column: 17
for option in ctx.options.modify_body:
try:
spec = parse_modify_spec(option, True)
except ValueError as e:
raise exceptions.OptionsError(f"Cannot parse modify_body option {option}: {e}") from e
self.replacements.append(spec)
def request(self, flow):
Reported by Pylint.
Line: 29
Column: 1
try:
spec = parse_modify_spec(option, True)
except ValueError as e:
raise exceptions.OptionsError(f"Cannot parse modify_body option {option}: {e}") from e
self.replacements.append(spec)
def request(self, flow):
if flow.response or flow.error or flow.reply.state == "taken":
Reported by Pylint.
Line: 33
Column: 5
self.replacements.append(spec)
def request(self, flow):
if flow.response or flow.error or flow.reply.state == "taken":
return
self.run(flow)
def response(self, flow):
Reported by Pylint.
Line: 38
Column: 5
return
self.run(flow)
def response(self, flow):
if flow.error or flow.reply.state == "taken":
return
self.run(flow)
def run(self, flow):
Reported by Pylint.
Line: 43
Column: 5
return
self.run(flow)
def run(self, flow):
for spec in self.replacements:
if spec.matches(flow):
try:
replacement = spec.read_replacement()
except OSError as e:
Reported by Pylint.
mitmproxy/utils/human.py
13 issues
Line: 1
Column: 1
import datetime
import functools
import ipaddress
import time
import typing
SIZE_UNITS = {
"b": 1024 ** 0,
Reported by Pylint.
Line: 22
Column: 5
len(return value) <= 5 always holds true.
"""
s: float = size # type cast for mypy
if s < 1024:
return f"{s}b"
for suffix in ["k", "m", "g", "t"]:
s /= 1024
if s < 99.95:
Reported by Pylint.
Line: 26
Column: 9
if s < 1024:
return f"{s}b"
for suffix in ["k", "m", "g", "t"]:
s /= 1024
if s < 99.95:
return f"{s:.1f}{suffix}"
if s < 1024 or suffix == "t":
return f"{s:.0f}{suffix}"
raise AssertionError
Reported by Pylint.
Line: 35
Column: 1
@functools.lru_cache()
def parse_size(s: typing.Optional[str]) -> typing.Optional[int]:
"""
Parse a size with an optional k/m/... suffix.
Invalid values raise a ValueError. For added convenience, passing `None` returns `None`.
"""
if s is None:
Reported by Pylint.
Line: 46
Column: 14
return int(s)
except ValueError:
pass
for i in SIZE_UNITS.keys():
if s.endswith(i):
try:
return int(s[:-1]) * SIZE_UNITS[i]
except ValueError:
break
Reported by Pylint.
Line: 55
Column: 1
raise ValueError("Invalid size specification.")
def pretty_duration(secs: typing.Optional[float]) -> str:
formatters = [
(100, "{:.0f}s"),
(10, "{:2.1f}s"),
(1, "{:1.2f}s"),
]
Reported by Pylint.
Line: 71
Column: 1
return "{:.0f}ms".format(secs * 1000)
def format_timestamp(s):
s = time.localtime(s)
d = datetime.datetime.fromtimestamp(time.mktime(s))
return d.strftime("%Y-%m-%d %H:%M:%S")
Reported by Pylint.
Line: 71
Column: 1
return "{:.0f}ms".format(secs * 1000)
def format_timestamp(s):
s = time.localtime(s)
d = datetime.datetime.fromtimestamp(time.mktime(s))
return d.strftime("%Y-%m-%d %H:%M:%S")
Reported by Pylint.
Line: 73
Column: 5
def format_timestamp(s):
s = time.localtime(s)
d = datetime.datetime.fromtimestamp(time.mktime(s))
return d.strftime("%Y-%m-%d %H:%M:%S")
def format_timestamp_with_milli(s):
d = datetime.datetime.fromtimestamp(s)
Reported by Pylint.
Line: 77
Column: 1
return d.strftime("%Y-%m-%d %H:%M:%S")
def format_timestamp_with_milli(s):
d = datetime.datetime.fromtimestamp(s)
return d.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
@functools.lru_cache()
Reported by Pylint.