The following issues were found

mitmproxy/proxy/layers/http/_events.py
13 issues
Attempted relative import beyond top-level package
Error

Line: 6 Column: 1

              
from mitmproxy import http
from mitmproxy.http import HTTPFlow
from ._base import HttpEvent


@dataclass
class RequestHeaders(HttpEvent):
    request: http.Request

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from dataclasses import dataclass
from typing import Optional

from mitmproxy import http
from mitmproxy.http import HTTPFlow
from ._base import HttpEvent


@dataclass

            

Reported by Pylint.

Missing class docstring
Error

Line: 10 Column: 1

              

@dataclass
class RequestHeaders(HttpEvent):
    request: http.Request
    end_stream: bool
    """
    If True, we already know at this point that there is no message body. This is useful for HTTP/2, where it allows
    us to set END_STREAM on headers already (and some servers - Akamai - implicitly expect that).

            

Reported by Pylint.

Line too long (116/100)
Error

Line: 14 Column: 1

                  request: http.Request
    end_stream: bool
    """
    If True, we already know at this point that there is no message body. This is useful for HTTP/2, where it allows
    us to set END_STREAM on headers already (and some servers - Akamai - implicitly expect that).
    In either case, this event will nonetheless be followed by RequestEndOfMessage.
    """
    replay_flow: Optional[HTTPFlow] = None
    """If set, the current request headers belong to a replayed flow, which should be reused."""

            

Reported by Pylint.

Missing class docstring
Error

Line: 23 Column: 1

              

@dataclass
class ResponseHeaders(HttpEvent):
    response: http.Response
    end_stream: bool = False


# explicit constructors below to facilitate type checking in _http1/_http2

            

Reported by Pylint.

Missing class docstring
Error

Line: 31 Column: 1

              # explicit constructors below to facilitate type checking in _http1/_http2

@dataclass
class RequestData(HttpEvent):
    data: bytes

    def __init__(self, stream_id: int, data: bytes):
        self.stream_id = stream_id
        self.data = data

            

Reported by Pylint.

Missing class docstring
Error

Line: 40 Column: 1

              

@dataclass
class ResponseData(HttpEvent):
    data: bytes

    def __init__(self, stream_id: int, data: bytes):
        self.stream_id = stream_id
        self.data = data

            

Reported by Pylint.

Missing class docstring
Error

Line: 49 Column: 1

              

@dataclass
class RequestTrailers(HttpEvent):
    trailers: http.Headers

    def __init__(self, stream_id: int, trailers: http.Headers):
        self.stream_id = stream_id
        self.trailers = trailers

            

Reported by Pylint.

Missing class docstring
Error

Line: 58 Column: 1

              

@dataclass
class ResponseTrailers(HttpEvent):
    trailers: http.Headers

    def __init__(self, stream_id: int, trailers: http.Headers):
        self.stream_id = stream_id
        self.trailers = trailers

            

Reported by Pylint.

Missing class docstring
Error

Line: 67 Column: 1

              

@dataclass
class RequestEndOfMessage(HttpEvent):
    def __init__(self, stream_id: int):
        self.stream_id = stream_id


@dataclass

            

Reported by Pylint.

test/mitmproxy/contentviews/test_urlencoded.py
13 issues
Attempted relative import beyond top-level package
Error

Line: 3 Column: 1

              from mitmproxy.contentviews import urlencoded
from mitmproxy.net.http import url
from . import full_eval


def test_view_urlencoded():
    v = full_eval(urlencoded.ViewURLEncoded())

    d = url.encode([("one", "two"), ("three", "four")]).encode()

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from mitmproxy.contentviews import urlencoded
from mitmproxy.net.http import url
from . import full_eval


def test_view_urlencoded():
    v = full_eval(urlencoded.ViewURLEncoded())

    d = url.encode([("one", "two"), ("three", "four")]).encode()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 6 Column: 1

              from . import full_eval


def test_view_urlencoded():
    v = full_eval(urlencoded.ViewURLEncoded())

    d = url.encode([("one", "two"), ("three", "four")]).encode()
    assert v(d)


            

Reported by Pylint.

Variable name "v" doesn't conform to snake_case naming style
Error

Line: 7 Column: 5

              

def test_view_urlencoded():
    v = full_eval(urlencoded.ViewURLEncoded())

    d = url.encode([("one", "two"), ("three", "four")]).encode()
    assert v(d)

    d = url.encode([("adsfa", "")]).encode()

            

Reported by Pylint.

Variable name "d" doesn't conform to snake_case naming style
Error

Line: 9 Column: 5

              def test_view_urlencoded():
    v = full_eval(urlencoded.ViewURLEncoded())

    d = url.encode([("one", "two"), ("three", "four")]).encode()
    assert v(d)

    d = url.encode([("adsfa", "")]).encode()
    assert v(d)


            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 10
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  v = full_eval(urlencoded.ViewURLEncoded())

    d = url.encode([("one", "two"), ("three", "four")]).encode()
    assert v(d)

    d = url.encode([("adsfa", "")]).encode()
    assert v(d)

    assert not v(b"\xFF\x00")

            

Reported by Bandit.

Variable name "d" doesn't conform to snake_case naming style
Error

Line: 12 Column: 5

                  d = url.encode([("one", "two"), ("three", "four")]).encode()
    assert v(d)

    d = url.encode([("adsfa", "")]).encode()
    assert v(d)

    assert not v(b"\xFF\x00")



            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 13
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  assert v(d)

    d = url.encode([("adsfa", "")]).encode()
    assert v(d)

    assert not v(b"\xFF\x00")


def test_render_priority():

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 15
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  d = url.encode([("adsfa", "")]).encode()
    assert v(d)

    assert not v(b"\xFF\x00")


def test_render_priority():
    v = urlencoded.ViewURLEncoded()
    assert v.render_priority(b"", content_type="application/x-www-form-urlencoded")

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 18 Column: 1

                  assert not v(b"\xFF\x00")


def test_render_priority():
    v = urlencoded.ViewURLEncoded()
    assert v.render_priority(b"", content_type="application/x-www-form-urlencoded")
    assert not v.render_priority(b"", content_type="text/plain")

            

Reported by Pylint.

docs/scripts/api-events.py
13 issues
Unable to import 'mitmproxy.addons.next_layer'
Error

Line: 8 Column: 1

              from pathlib import Path
from typing import List, Type

import mitmproxy.addons.next_layer  # noqa
from mitmproxy import hooks, log, addonmanager
from mitmproxy.proxy import server_hooks, layer
from mitmproxy.proxy.layers import http, tcp, tls, websocket

known = set()

            

Reported by Pylint.

Unable to import 'mitmproxy'
Error

Line: 9 Column: 1

              from typing import List, Type

import mitmproxy.addons.next_layer  # noqa
from mitmproxy import hooks, log, addonmanager
from mitmproxy.proxy import server_hooks, layer
from mitmproxy.proxy.layers import http, tcp, tls, websocket

known = set()


            

Reported by Pylint.

Unable to import 'mitmproxy.proxy'
Error

Line: 10 Column: 1

              
import mitmproxy.addons.next_layer  # noqa
from mitmproxy import hooks, log, addonmanager
from mitmproxy.proxy import server_hooks, layer
from mitmproxy.proxy.layers import http, tcp, tls, websocket

known = set()



            

Reported by Pylint.

Unable to import 'mitmproxy.proxy.layers'
Error

Line: 11 Column: 1

              import mitmproxy.addons.next_layer  # noqa
from mitmproxy import hooks, log, addonmanager
from mitmproxy.proxy import server_hooks, layer
from mitmproxy.proxy.layers import http, tcp, tls, websocket

known = set()


def category(name: str, desc: str, hooks: List[Type[hooks.Hook]]) -> None:

            

Reported by Pylint.

Unused import mitmproxy.addons.next_layer
Error

Line: 8 Column: 1

              from pathlib import Path
from typing import List, Type

import mitmproxy.addons.next_layer  # noqa
from mitmproxy import hooks, log, addonmanager
from mitmproxy.proxy import server_hooks, layer
from mitmproxy.proxy.layers import http, tcp, tls, websocket

known = set()

            

Reported by Pylint.

Redefining name 'hooks' from outer scope (line 9)
Error

Line: 16 Column: 36

              known = set()


def category(name: str, desc: str, hooks: List[Type[hooks.Hook]]) -> None:
    all_params = [
        list(inspect.signature(hook.__init__).parameters.values())[1:]
        for hook in hooks
    ]


            

Reported by Pylint.

Access to a protected member _name of a client class
Error

Line: 32 Column: 31

                              if mod == "typing":
                    # this is ugly, but can be removed once we are on Python 3.9+ only
                    imports.add(inspect.getmodule(param.annotation.__args__[0]).__name__)
                    types.add(param.annotation._name)
                else:
                    imports.add(mod)
            except AttributeError:
                raise ValueError(f"Missing type annotation: {params}")
    imports.discard("builtins")

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 36 Column: 17

                              else:
                    imports.add(mod)
            except AttributeError:
                raise ValueError(f"Missing type annotation: {params}")
    imports.discard("builtins")
    if types:
        print(f"from typing import {', '.join(sorted(types))}")
    print("from mitmproxy import ctx")
    for imp in sorted(imports):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3
import contextlib
import inspect
import textwrap
from pathlib import Path
from typing import List, Type

import mitmproxy.addons.next_layer  # noqa
from mitmproxy import hooks, log, addonmanager

            

Reported by Pylint.

Module name "api-events" doesn't conform to snake_case naming style
Error

Line: 1 Column: 1

              #!/usr/bin/env python3
import contextlib
import inspect
import textwrap
from pathlib import Path
from typing import List, Type

import mitmproxy.addons.next_layer  # noqa
from mitmproxy import hooks, log, addonmanager

            

Reported by Pylint.

examples/contrib/link_expander.py
12 issues
Unused variable 'match_num'
Error

Line: 20 Column: 13

                      rel_matcher = re.compile(pattern, flags=re.IGNORECASE)
        rel_matches = rel_matcher.finditer(pageText)
        map_dict = {}
        for match_num, match in enumerate(rel_matches):
            (delimiter, rel_link) = match.group("delimiter", "link")
            abs_link = urljoin(pageUrl, rel_link)
            map_dict["{0}{1}{0}".format(delimiter, rel_link)] = "{0}{1}{0}".format(delimiter, abs_link)
        for map in map_dict.items():
            pageText = pageText.replace(*map)

            

Reported by Pylint.

Redefining built-in 'map'
Error

Line: 24 Column: 13

                          (delimiter, rel_link) = match.group("delimiter", "link")
            abs_link = urljoin(pageUrl, rel_link)
            map_dict["{0}{1}{0}".format(delimiter, rel_link)] = "{0}{1}{0}".format(delimiter, abs_link)
        for map in map_dict.items():
            pageText = pageText.replace(*map)
            # Uncomment the following to print the expansion mapping
            # print("{0} -> {1}".format(*map))
        flow.response.text = pageText
            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # This script determines if request is an HTML webpage and if so seeks out
# relative links (<a href="./about.html">) and expands them to absolute links
# In practice this can be used to front an indexing spider that may not have the capability to expand relative page links.
# Usage: mitmdump -s link_expander.py or mitmproxy -s link_expander.py

import re
from urllib.parse import urljoin



            

Reported by Pylint.

Line too long (122/100)
Error

Line: 3 Column: 1

              # This script determines if request is an HTML webpage and if so seeks out
# relative links (<a href="./about.html">) and expands them to absolute links
# In practice this can be used to front an indexing spider that may not have the capability to expand relative page links.
# Usage: mitmdump -s link_expander.py or mitmproxy -s link_expander.py

import re
from urllib.parse import urljoin



            

Reported by Pylint.

Missing function or method docstring
Error

Line: 10 Column: 1

              from urllib.parse import urljoin


def response(flow):

    if "Content-Type" in flow.response.headers and flow.response.headers["Content-Type"].find("text/html") != -1:
        pageUrl = flow.request.url
        pageText = flow.response.text
        pattern = (r"<a\s+(?:[^>]*?\s+)?href=(?P<delimiter>[\"'])"

            

Reported by Pylint.

Line too long (113/100)
Error

Line: 12 Column: 1

              
def response(flow):

    if "Content-Type" in flow.response.headers and flow.response.headers["Content-Type"].find("text/html") != -1:
        pageUrl = flow.request.url
        pageText = flow.response.text
        pattern = (r"<a\s+(?:[^>]*?\s+)?href=(?P<delimiter>[\"'])"
                   r"(?P<link>(?!https?:\/\/|ftps?:\/\/|\/\/|#|javascript:|mailto:).*?)(?P=delimiter)")
        rel_matcher = re.compile(pattern, flags=re.IGNORECASE)

            

Reported by Pylint.

Variable name "pageUrl" doesn't conform to snake_case naming style
Error

Line: 13 Column: 9

              def response(flow):

    if "Content-Type" in flow.response.headers and flow.response.headers["Content-Type"].find("text/html") != -1:
        pageUrl = flow.request.url
        pageText = flow.response.text
        pattern = (r"<a\s+(?:[^>]*?\s+)?href=(?P<delimiter>[\"'])"
                   r"(?P<link>(?!https?:\/\/|ftps?:\/\/|\/\/|#|javascript:|mailto:).*?)(?P=delimiter)")
        rel_matcher = re.compile(pattern, flags=re.IGNORECASE)
        rel_matches = rel_matcher.finditer(pageText)

            

Reported by Pylint.

Variable name "pageText" doesn't conform to snake_case naming style
Error

Line: 14 Column: 9

              
    if "Content-Type" in flow.response.headers and flow.response.headers["Content-Type"].find("text/html") != -1:
        pageUrl = flow.request.url
        pageText = flow.response.text
        pattern = (r"<a\s+(?:[^>]*?\s+)?href=(?P<delimiter>[\"'])"
                   r"(?P<link>(?!https?:\/\/|ftps?:\/\/|\/\/|#|javascript:|mailto:).*?)(?P=delimiter)")
        rel_matcher = re.compile(pattern, flags=re.IGNORECASE)
        rel_matches = rel_matcher.finditer(pageText)
        map_dict = {}

            

Reported by Pylint.

Line too long (103/100)
Error

Line: 16 Column: 1

                      pageUrl = flow.request.url
        pageText = flow.response.text
        pattern = (r"<a\s+(?:[^>]*?\s+)?href=(?P<delimiter>[\"'])"
                   r"(?P<link>(?!https?:\/\/|ftps?:\/\/|\/\/|#|javascript:|mailto:).*?)(?P=delimiter)")
        rel_matcher = re.compile(pattern, flags=re.IGNORECASE)
        rel_matches = rel_matcher.finditer(pageText)
        map_dict = {}
        for match_num, match in enumerate(rel_matches):
            (delimiter, rel_link) = match.group("delimiter", "link")

            

Reported by Pylint.

Line too long (103/100)
Error

Line: 23 Column: 1

                      for match_num, match in enumerate(rel_matches):
            (delimiter, rel_link) = match.group("delimiter", "link")
            abs_link = urljoin(pageUrl, rel_link)
            map_dict["{0}{1}{0}".format(delimiter, rel_link)] = "{0}{1}{0}".format(delimiter, abs_link)
        for map in map_dict.items():
            pageText = pageText.replace(*map)
            # Uncomment the following to print the expansion mapping
            # print("{0} -> {1}".format(*map))
        flow.response.text = pageText
            

Reported by Pylint.

test/mitmproxy/contentviews/test_multipart.py
12 issues
Attempted relative import beyond top-level package
Error

Line: 2 Column: 1

              from mitmproxy.contentviews import multipart
from . import full_eval


def test_view_multipart():
    view = full_eval(multipart.ViewMultipart())
    v = b"""
--AaB03x
Content-Disposition: form-data; name="submit-name"

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from mitmproxy.contentviews import multipart
from . import full_eval


def test_view_multipart():
    view = full_eval(multipart.ViewMultipart())
    v = b"""
--AaB03x
Content-Disposition: form-data; name="submit-name"

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 5 Column: 1

              from . import full_eval


def test_view_multipart():
    view = full_eval(multipart.ViewMultipart())
    v = b"""
--AaB03x
Content-Disposition: form-data; name="submit-name"


            

Reported by Pylint.

Variable name "v" doesn't conform to snake_case naming style
Error

Line: 7 Column: 5

              
def test_view_multipart():
    view = full_eval(multipart.ViewMultipart())
    v = b"""
--AaB03x
Content-Disposition: form-data; name="submit-name"

Larry
--AaB03x

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 14
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              Larry
--AaB03x
        """.strip()
    assert view(v, content_type="multipart/form-data; boundary=AaB03x")

    assert not view(v)

    assert not view(v, content_type="multipart/form-data")


            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 16
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      """.strip()
    assert view(v, content_type="multipart/form-data; boundary=AaB03x")

    assert not view(v)

    assert not view(v, content_type="multipart/form-data")

    assert not view(v, content_type="unparseable")


            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 18
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
    assert not view(v)

    assert not view(v, content_type="multipart/form-data")

    assert not view(v, content_type="unparseable")


def test_render_priority():

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 20
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
    assert not view(v, content_type="multipart/form-data")

    assert not view(v, content_type="unparseable")


def test_render_priority():
    v = multipart.ViewMultipart()
    assert v.render_priority(b"", content_type="multipart/form-data")

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 23 Column: 1

                  assert not view(v, content_type="unparseable")


def test_render_priority():
    v = multipart.ViewMultipart()
    assert v.render_priority(b"", content_type="multipart/form-data")
    assert not v.render_priority(b"", content_type="text/plain")

            

Reported by Pylint.

Variable name "v" doesn't conform to snake_case naming style
Error

Line: 24 Column: 5

              

def test_render_priority():
    v = multipart.ViewMultipart()
    assert v.render_priority(b"", content_type="multipart/form-data")
    assert not v.render_priority(b"", content_type="text/plain")

            

Reported by Pylint.

mitmproxy/addons/mapremote.py
12 issues
Consider explicitly re-raising using the 'from' keyword
Error

Line: 20 Column: 9

                  try:
        re.compile(spec.subject)
    except re.error as e:
        raise ValueError(f"Invalid regular expression {spec.subject!r} ({e})")

    return spec


class MapRemote:

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import re
import typing

from mitmproxy import ctx, exceptions, flowfilter, http
from mitmproxy.utils.spec import parse_spec


class MapRemoteSpec(typing.NamedTuple):
    matches: flowfilter.TFilter

            

Reported by Pylint.

Missing class docstring
Error

Line: 8 Column: 1

              from mitmproxy.utils.spec import parse_spec


class MapRemoteSpec(typing.NamedTuple):
    matches: flowfilter.TFilter
    subject: str
    replacement: str



            

Reported by Pylint.

Missing function or method docstring
Error

Line: 14 Column: 1

                  replacement: str


def parse_map_remote_spec(option: str) -> MapRemoteSpec:
    spec = MapRemoteSpec(*parse_spec(option))

    try:
        re.compile(spec.subject)
    except re.error as e:

            

Reported by Pylint.

Variable name "e" doesn't conform to snake_case naming style
Error

Line: 19 Column: 5

              
    try:
        re.compile(spec.subject)
    except re.error as e:
        raise ValueError(f"Invalid regular expression {spec.subject!r} ({e})")

    return spec



            

Reported by Pylint.

Missing class docstring
Error

Line: 25 Column: 1

                  return spec


class MapRemote:
    def __init__(self):
        self.replacements: typing.List[MapRemoteSpec] = []

    def load(self, loader):
        loader.add_option(

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 29 Column: 5

                  def __init__(self):
        self.replacements: typing.List[MapRemoteSpec] = []

    def load(self, loader):
        loader.add_option(
            "map_remote", typing.Sequence[str], [],
            """
            Map remote resources to another remote URL using a pattern of the form
            "[/flow-filter]/url-regex/replacement", where the separator can

            

Reported by Pylint.

Method could be a function
Error

Line: 29 Column: 5

                  def __init__(self):
        self.replacements: typing.List[MapRemoteSpec] = []

    def load(self, loader):
        loader.add_option(
            "map_remote", typing.Sequence[str], [],
            """
            Map remote resources to another remote URL using a pattern of the form
            "[/flow-filter]/url-regex/replacement", where the separator can

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 39 Column: 5

                          """
        )

    def configure(self, updated):
        if "map_remote" in updated:
            self.replacements = []
            for option in ctx.options.map_remote:
                try:
                    spec = parse_map_remote_spec(option)

            

Reported by Pylint.

Variable name "e" doesn't conform to snake_case naming style
Error

Line: 45 Column: 17

                          for option in ctx.options.map_remote:
                try:
                    spec = parse_map_remote_spec(option)
                except ValueError as e:
                    raise exceptions.OptionsError(f"Cannot parse map_remote option {option}: {e}") from e

                self.replacements.append(spec)

    def request(self, flow: http.HTTPFlow) -> None:

            

Reported by Pylint.

test/mitmproxy/test_version.py
12 issues
Unused variable 'stderr'
Error

Line: 14 Column: 13

                  here = pathlib.Path(__file__).absolute().parent
    version_file = here / ".." / ".." / "mitmproxy" / "version.py"
    runpy.run_path(str(version_file), run_name='__main__')
    stdout, stderr = capsys.readouterr()
    assert len(stdout) > 0
    assert stdout.strip() == version.VERSION


def test_get_version():

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pathlib
import runpy
import subprocess
import sys
from unittest import mock

from mitmproxy import version



            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

Line: 3
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess

              import pathlib
import runpy
import subprocess
import sys
from unittest import mock

from mitmproxy import version



            

Reported by Bandit.

Missing function or method docstring
Error

Line: 10 Column: 1

              from mitmproxy import version


def test_version(capsys):
    here = pathlib.Path(__file__).absolute().parent
    version_file = here / ".." / ".." / "mitmproxy" / "version.py"
    runpy.run_path(str(version_file), run_name='__main__')
    stdout, stderr = capsys.readouterr()
    assert len(stdout) > 0

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 15
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  version_file = here / ".." / ".." / "mitmproxy" / "version.py"
    runpy.run_path(str(version_file), run_name='__main__')
    stdout, stderr = capsys.readouterr()
    assert len(stdout) > 0
    assert stdout.strip() == version.VERSION


def test_get_version():
    version.VERSION = "3.0.0rc2"

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 16
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  runpy.run_path(str(version_file), run_name='__main__')
    stdout, stderr = capsys.readouterr()
    assert len(stdout) > 0
    assert stdout.strip() == version.VERSION


def test_get_version():
    version.VERSION = "3.0.0rc2"


            

Reported by Bandit.

Missing function or method docstring
Error

Line: 19 Column: 1

                  assert stdout.strip() == version.VERSION


def test_get_version():
    version.VERSION = "3.0.0rc2"

    with mock.patch('subprocess.check_output') as m:
        m.return_value = b"tag-0-cafecafe"
        assert version.get_dev_version() == "3.0.0rc2"

            

Reported by Pylint.

Variable name "m" doesn't conform to snake_case naming style
Error

Line: 22 Column: 51

              def test_get_version():
    version.VERSION = "3.0.0rc2"

    with mock.patch('subprocess.check_output') as m:
        m.return_value = b"tag-0-cafecafe"
        assert version.get_dev_version() == "3.0.0rc2"

        sys.frozen = True
        assert version.get_dev_version() == "3.0.0rc2 binary"

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 24
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
    with mock.patch('subprocess.check_output') as m:
        m.return_value = b"tag-0-cafecafe"
        assert version.get_dev_version() == "3.0.0rc2"

        sys.frozen = True
        assert version.get_dev_version() == "3.0.0rc2 binary"
        sys.frozen = False


            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 27
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      assert version.get_dev_version() == "3.0.0rc2"

        sys.frozen = True
        assert version.get_dev_version() == "3.0.0rc2 binary"
        sys.frozen = False

        m.return_value = b"tag-2-cafecafe"
        assert version.get_dev_version() == "3.0.0rc2 (+2, commit cafecaf)"


            

Reported by Bandit.

mitmproxy/addons/blocklist.py
12 issues
Consider explicitly re-raising using the 'from' keyword
Error

Line: 29 Column: 9

                  try:
        status_code = int(status)
    except ValueError:
        raise ValueError(f"Invalid HTTP status code: {status}")
    flow_filter = flowfilter.parse(flow_patt)
    if not flow_filter:
        raise ValueError(f"Invalid filter pattern: {flow_patt}")
    if not RESPONSES.get(status_code):
        raise ValueError(f"Invalid HTTP status code: {status}")

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import typing

from mitmproxy import ctx, exceptions, flowfilter, http, version
from mitmproxy.net.http.status_codes import NO_RESPONSE
from mitmproxy.net.http.status_codes import RESPONSES


class BlockSpec(typing.NamedTuple):
    matches: flowfilter.TFilter

            

Reported by Pylint.

Missing class docstring
Error

Line: 8 Column: 1

              from mitmproxy.net.http.status_codes import RESPONSES


class BlockSpec(typing.NamedTuple):
    matches: flowfilter.TFilter
    status_code: int


def parse_spec(option: str) -> BlockSpec:

            

Reported by Pylint.

Missing class docstring
Error

Line: 39 Column: 1

                  return BlockSpec(matches=flow_filter, status_code=status_code)


class BlockList:
    def __init__(self):
        self.items: typing.List[BlockSpec] = []

    def load(self, loader):
        loader.add_option(

            

Reported by Pylint.

Method could be a function
Error

Line: 43 Column: 5

                  def __init__(self):
        self.items: typing.List[BlockSpec] = []

    def load(self, loader):
        loader.add_option(
            "block_list", typing.Sequence[str], [],
            """
            Block matching requests and return an empty response with the specified HTTP status.
            Option syntax is "/flow-filter/status-code", where flow-filter describes

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 43 Column: 5

                  def __init__(self):
        self.items: typing.List[BlockSpec] = []

    def load(self, loader):
        loader.add_option(
            "block_list", typing.Sequence[str], [],
            """
            Block matching requests and return an empty response with the specified HTTP status.
            Option syntax is "/flow-filter/status-code", where flow-filter describes

            

Reported by Pylint.

Line too long (111/100)
Error

Line: 49 Column: 1

                          """
            Block matching requests and return an empty response with the specified HTTP status.
            Option syntax is "/flow-filter/status-code", where flow-filter describes
            which requests this rule should be applied to and status-code is the HTTP status code to return for
            blocked requests. The separator ("/" in the example) can be any character.
            Setting a non-standard status code of 444 will close the connection without sending a response.
            """
        )


            

Reported by Pylint.

Line too long (107/100)
Error

Line: 51 Column: 1

                          Option syntax is "/flow-filter/status-code", where flow-filter describes
            which requests this rule should be applied to and status-code is the HTTP status code to return for
            blocked requests. The separator ("/" in the example) can be any character.
            Setting a non-standard status code of 444 will close the connection without sending a response.
            """
        )

    def configure(self, updated):
        if "block_list" in updated:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 55 Column: 5

                          """
        )

    def configure(self, updated):
        if "block_list" in updated:
            self.items = []
            for option in ctx.options.block_list:
                try:
                    spec = parse_spec(option)

            

Reported by Pylint.

Variable name "e" doesn't conform to snake_case naming style
Error

Line: 61 Column: 17

                          for option in ctx.options.block_list:
                try:
                    spec = parse_spec(option)
                except ValueError as e:
                    raise exceptions.OptionsError(f"Cannot parse block_list option {option}: {e}") from e
                self.items.append(spec)

    def request(self, flow: http.HTTPFlow) -> None:
        if flow.response or flow.error or (flow.reply and flow.reply.state == "taken"):

            

Reported by Pylint.

test/mitmproxy/contentviews/test_query.py
12 issues
Attempted relative import beyond top-level package
Error

Line: 3 Column: 1

              from mitmproxy.contentviews import query
from mitmproxy.test import tutils
from . import full_eval


def test_view_query():
    d = ""
    v = full_eval(query.ViewQuery())
    req = tutils.treq()

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from mitmproxy.contentviews import query
from mitmproxy.test import tutils
from . import full_eval


def test_view_query():
    d = ""
    v = full_eval(query.ViewQuery())
    req = tutils.treq()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 6 Column: 1

              from . import full_eval


def test_view_query():
    d = ""
    v = full_eval(query.ViewQuery())
    req = tutils.treq()
    req.query = [("foo", "bar"), ("foo", "baz")]
    f = v(d, http_message=req)

            

Reported by Pylint.

Variable name "d" doesn't conform to snake_case naming style
Error

Line: 7 Column: 5

              

def test_view_query():
    d = ""
    v = full_eval(query.ViewQuery())
    req = tutils.treq()
    req.query = [("foo", "bar"), ("foo", "baz")]
    f = v(d, http_message=req)
    assert f[0] == "Query"

            

Reported by Pylint.

Variable name "v" doesn't conform to snake_case naming style
Error

Line: 8 Column: 5

              
def test_view_query():
    d = ""
    v = full_eval(query.ViewQuery())
    req = tutils.treq()
    req.query = [("foo", "bar"), ("foo", "baz")]
    f = v(d, http_message=req)
    assert f[0] == "Query"
    assert f[1] == [[("header", "foo: "), ("text", "bar")], [("header", "foo: "), ("text", "baz")]]

            

Reported by Pylint.

Variable name "f" doesn't conform to snake_case naming style
Error

Line: 11 Column: 5

                  v = full_eval(query.ViewQuery())
    req = tutils.treq()
    req.query = [("foo", "bar"), ("foo", "baz")]
    f = v(d, http_message=req)
    assert f[0] == "Query"
    assert f[1] == [[("header", "foo: "), ("text", "bar")], [("header", "foo: "), ("text", "baz")]]

    assert v(d) == ("Query", [])


            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 12
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  req = tutils.treq()
    req.query = [("foo", "bar"), ("foo", "baz")]
    f = v(d, http_message=req)
    assert f[0] == "Query"
    assert f[1] == [[("header", "foo: "), ("text", "bar")], [("header", "foo: "), ("text", "baz")]]

    assert v(d) == ("Query", [])



            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 13
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  req.query = [("foo", "bar"), ("foo", "baz")]
    f = v(d, http_message=req)
    assert f[0] == "Query"
    assert f[1] == [[("header", "foo: "), ("text", "bar")], [("header", "foo: "), ("text", "baz")]]

    assert v(d) == ("Query", [])


def test_render_priority():

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 15
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  assert f[0] == "Query"
    assert f[1] == [[("header", "foo: "), ("text", "bar")], [("header", "foo: "), ("text", "baz")]]

    assert v(d) == ("Query", [])


def test_render_priority():
    view = query.ViewQuery()
    req = tutils.treq()

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 18 Column: 1

                  assert v(d) == ("Query", [])


def test_render_priority():
    view = query.ViewQuery()
    req = tutils.treq()
    req.query = [("foo", "bar"), ("foo", "baz")]
    assert view.render_priority(b"", http_message=req)
    assert not view.render_priority(b"")

            

Reported by Pylint.

test/mitmproxy/tools/console/test_master.py
12 issues
Unable to import 'urwid'
Error

Line: 1 Column: 1

              import urwid

import pytest

from mitmproxy import options, hooks
from mitmproxy.tools import console

from ... import tservers


            

Reported by Pylint.

Unable to import 'pytest'
Error

Line: 3 Column: 1

              import urwid

import pytest

from mitmproxy import options, hooks
from mitmproxy.tools import console

from ... import tservers


            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 8 Column: 1

              from mitmproxy import options, hooks
from mitmproxy.tools import console

from ... import tservers


@pytest.mark.asyncio
class TestMaster(tservers.MasterTest):
    def mkmaster(self, **opts):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import urwid

import pytest

from mitmproxy import options, hooks
from mitmproxy.tools import console

from ... import tservers


            

Reported by Pylint.

Missing class docstring
Error

Line: 12 Column: 1

              

@pytest.mark.asyncio
class TestMaster(tservers.MasterTest):
    def mkmaster(self, **opts):
        o = options.Options(**opts)
        m = console.master.ConsoleMaster(o)
        m.addons.trigger(hooks.ConfigureHook(o.keys()))
        return m

            

Reported by Pylint.

Method could be a function
Error

Line: 13 Column: 5

              
@pytest.mark.asyncio
class TestMaster(tservers.MasterTest):
    def mkmaster(self, **opts):
        o = options.Options(**opts)
        m = console.master.ConsoleMaster(o)
        m.addons.trigger(hooks.ConfigureHook(o.keys()))
        return m


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 5

              
@pytest.mark.asyncio
class TestMaster(tservers.MasterTest):
    def mkmaster(self, **opts):
        o = options.Options(**opts)
        m = console.master.ConsoleMaster(o)
        m.addons.trigger(hooks.ConfigureHook(o.keys()))
        return m


            

Reported by Pylint.

Variable name "o" doesn't conform to snake_case naming style
Error

Line: 14 Column: 9

              @pytest.mark.asyncio
class TestMaster(tservers.MasterTest):
    def mkmaster(self, **opts):
        o = options.Options(**opts)
        m = console.master.ConsoleMaster(o)
        m.addons.trigger(hooks.ConfigureHook(o.keys()))
        return m

    async def test_basic(self):

            

Reported by Pylint.

Variable name "m" doesn't conform to snake_case naming style
Error

Line: 15 Column: 9

              class TestMaster(tservers.MasterTest):
    def mkmaster(self, **opts):
        o = options.Options(**opts)
        m = console.master.ConsoleMaster(o)
        m.addons.trigger(hooks.ConfigureHook(o.keys()))
        return m

    async def test_basic(self):
        m = self.mkmaster()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 19 Column: 5

                      m.addons.trigger(hooks.ConfigureHook(o.keys()))
        return m

    async def test_basic(self):
        m = self.mkmaster()
        for i in (1, 2, 3):
            try:
                await self.dummy_cycle(m, 1, b"")
            except urwid.ExitMainLoop:

            

Reported by Pylint.