The following issues were found

mitmproxy/websocket.py
12 issues
Unable to import 'wsproto.frame_protocol'
Error

Line: 15 Column: 1

              
from mitmproxy import stateobject
from mitmproxy.coretypes import serializable
from wsproto.frame_protocol import Opcode

WebSocketMessageState = Tuple[int, bool, bytes, float, bool]


class WebSocketMessage(serializable.Serializable):

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 53 Column: 9

              
    def __init__(
        self,
        type: Union[int, Opcode],
        from_client: bool,
        content: bytes,
        timestamp: Optional[float] = None,
        killed: bool = False,
    ) -> None:

            

Reported by Pylint.

Line too long (118/100)
Error

Line: 2 Column: 1

              """
Mitmproxy used to have its own WebSocketFlow type until mitmproxy 6, but now WebSocket connections now are represented
as HTTP flows as well. They can be distinguished from regular HTTP requests by having the
`mitmproxy.http.HTTPFlow.websocket` attribute set.

This module only defines the classes for individual `WebSocketMessage`s and the `WebSocketData` container.
"""
import time
import warnings

            

Reported by Pylint.

Line too long (106/100)
Error

Line: 6 Column: 1

              as HTTP flows as well. They can be distinguished from regular HTTP requests by having the
`mitmproxy.http.HTTPFlow.websocket` attribute set.

This module only defines the classes for individual `WebSocketMessage`s and the `WebSocketData` container.
"""
import time
import warnings
from typing import List, Tuple, Union
from typing import Optional

            

Reported by Pylint.

third party import "from wsproto.frame_protocol import Opcode" should be placed before "from mitmproxy import stateobject"
Error

Line: 15 Column: 1

              
from mitmproxy import stateobject
from mitmproxy.coretypes import serializable
from wsproto.frame_protocol import Opcode

WebSocketMessageState = Tuple[int, bool, bytes, float, bool]


class WebSocketMessage(serializable.Serializable):

            

Reported by Pylint.

Line too long (109/100)
Error

Line: 29 Column: 1

              
    The [WebSocket RFC](https://tools.ietf.org/html/rfc6455) specifies both
    text and binary messages. To avoid a whole class of nasty type confusion bugs,
    mitmproxy stores all message contents as `bytes`. If you need a `str`, you can access the `text` property
    on text messages:

    >>> if message.is_text:
    >>>     text = message.text
    """

            

Reported by Pylint.

Too many arguments (6/5)
Error

Line: 51 Column: 5

                  dropped: bool
    """True if the message has not been forwarded by mitmproxy, False otherwise."""

    def __init__(
        self,
        type: Union[int, Opcode],
        from_client: bool,
        content: bytes,
        timestamp: Optional[float] = None,

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 77 Column: 9

                      self.type = Opcode(typ)

    def __repr__(self):
        if self.type == Opcode.TEXT:
            return repr(self.content.decode(errors="replace"))
        else:
            return repr(self.content)

    @property

            

Reported by Pylint.

Line too long (118/100)
Error

Line: 96 Column: 1

              
    def kill(self):  # pragma: no cover
        """A deprecated alias for `.drop()`."""
        warnings.warn("WebSocketMessage.kill() is deprecated, use .drop() instead.", DeprecationWarning, stacklevel=2)
        self.drop()

    @property
    def text(self) -> str:
        """

            

Reported by Pylint.

Line too long (110/100)
Error

Line: 109 Column: 1

                      *See also:* `WebSocketMessage.content`
        """
        if self.type != Opcode.TEXT:
            raise AttributeError(f"{self.type.name.title()} WebSocket frames do not have a 'text' attribute.")

        return self.content.decode()

    @text.setter
    def text(self, value: str) -> None:

            

Reported by Pylint.

examples/addons/commands-paths.py
12 issues
Unable to import 'mitmproxy'
Error

Line: 4 Column: 1

              """Handle file paths as command arguments."""
import typing

from mitmproxy import command
from mitmproxy import ctx
from mitmproxy import flow
from mitmproxy import http
from mitmproxy import types


            

Reported by Pylint.

Unable to import 'mitmproxy'
Error

Line: 5 Column: 1

              import typing

from mitmproxy import command
from mitmproxy import ctx
from mitmproxy import flow
from mitmproxy import http
from mitmproxy import types



            

Reported by Pylint.

Unable to import 'mitmproxy'
Error

Line: 6 Column: 1

              
from mitmproxy import command
from mitmproxy import ctx
from mitmproxy import flow
from mitmproxy import http
from mitmproxy import types


class MyAddon:

            

Reported by Pylint.

Unable to import 'mitmproxy'
Error

Line: 7 Column: 1

              from mitmproxy import command
from mitmproxy import ctx
from mitmproxy import flow
from mitmproxy import http
from mitmproxy import types


class MyAddon:
    @command.command("myaddon.histogram")

            

Reported by Pylint.

Unable to import 'mitmproxy'
Error

Line: 8 Column: 1

              from mitmproxy import ctx
from mitmproxy import flow
from mitmproxy import http
from mitmproxy import types


class MyAddon:
    @command.command("myaddon.histogram")
    def histogram(

            

Reported by Pylint.

Module name "commands-paths" doesn't conform to snake_case naming style
Error

Line: 1 Column: 1

              """Handle file paths as command arguments."""
import typing

from mitmproxy import command
from mitmproxy import ctx
from mitmproxy import flow
from mitmproxy import http
from mitmproxy import types


            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 11 Column: 1

              from mitmproxy import types


class MyAddon:
    @command.command("myaddon.histogram")
    def histogram(
        self,
        flows: typing.Sequence[flow.Flow],
        path: types.Path,

            

Reported by Pylint.

Missing class docstring
Error

Line: 11 Column: 1

              from mitmproxy import types


class MyAddon:
    @command.command("myaddon.histogram")
    def histogram(
        self,
        flows: typing.Sequence[flow.Flow],
        path: types.Path,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 5

              
class MyAddon:
    @command.command("myaddon.histogram")
    def histogram(
        self,
        flows: typing.Sequence[flow.Flow],
        path: types.Path,
    ) -> None:
        totals: typing.Dict[str, int] = {}

            

Reported by Pylint.

Method could be a function
Error

Line: 13 Column: 5

              
class MyAddon:
    @command.command("myaddon.histogram")
    def histogram(
        self,
        flows: typing.Sequence[flow.Flow],
        path: types.Path,
    ) -> None:
        totals: typing.Dict[str, int] = {}

            

Reported by Pylint.

mitmproxy/contentviews/json.py
12 issues
Module 'json' has no 'loads' member
Error

Line: 15 Column: 16

              @lru_cache(1)
def parse_json(s: bytes) -> typing.Any:
    try:
        return json.loads(s.decode('utf-8'))
    except ValueError:
        return PARSE_ERROR


def format_json(data: typing.Any) -> typing.Iterator[base.TViewLine]:

            

Reported by Pylint.

Module 'json' has no 'JSONEncoder' member
Error

Line: 21 Column: 15

              

def format_json(data: typing.Any) -> typing.Iterator[base.TViewLine]:
    encoder = json.JSONEncoder(indent=4, sort_keys=True, ensure_ascii=False)
    current_line: base.TViewLine = []
    for chunk in encoder.iterencode(data):
        if "\n" in chunk:
            rest_of_last_line, chunk = chunk.split("\n", maxsplit=1)
            # rest_of_last_line is a delimiter such as , or [

            

Reported by Pylint.

Module import itself
Error

Line: 2 Column: 1

              import re
import json
from functools import lru_cache

import typing

from mitmproxy.contentviews import base

PARSE_ERROR = object()

            

Reported by Pylint.

Unused argument 'metadata'
Error

Line: 49 Column: 1

                      if data is not PARSE_ERROR:
            return "JSON", format_json(data)

    def render_priority(self, data: bytes, *, content_type: typing.Optional[str] = None, **metadata) -> float:
        if content_type in (
            "application/json",
            "application/json-rpc",
        ):
            return 1

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import re
import json
from functools import lru_cache

import typing

from mitmproxy.contentviews import base

PARSE_ERROR = object()

            

Reported by Pylint.

Argument name "s" doesn't conform to snake_case naming style
Error

Line: 13 Column: 1

              

@lru_cache(1)
def parse_json(s: bytes) -> typing.Any:
    try:
        return json.loads(s.decode('utf-8'))
    except ValueError:
        return PARSE_ERROR


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 1

              

@lru_cache(1)
def parse_json(s: bytes) -> typing.Any:
    try:
        return json.loads(s.decode('utf-8'))
    except ValueError:
        return PARSE_ERROR


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 20 Column: 1

                      return PARSE_ERROR


def format_json(data: typing.Any) -> typing.Iterator[base.TViewLine]:
    encoder = json.JSONEncoder(indent=4, sort_keys=True, ensure_ascii=False)
    current_line: base.TViewLine = []
    for chunk in encoder.iterencode(data):
        if "\n" in chunk:
            rest_of_last_line, chunk = chunk.split("\n", maxsplit=1)

            

Reported by Pylint.

Missing class docstring
Error

Line: 41 Column: 1

                  yield current_line


class ViewJSON(base.View):
    name = "JSON"

    def __call__(self, data, **metadata):
        data = parse_json(data)
        if data is not PARSE_ERROR:

            

Reported by Pylint.

Either all return statements in a function should return an expression, or none of them should.
Error

Line: 44 Column: 5

              class ViewJSON(base.View):
    name = "JSON"

    def __call__(self, data, **metadata):
        data = parse_json(data)
        if data is not PARSE_ERROR:
            return "JSON", format_json(data)

    def render_priority(self, data: bytes, *, content_type: typing.Optional[str] = None, **metadata) -> float:

            

Reported by Pylint.

test/mitmproxy/test_taddons.py
11 issues
Unable to import 'pytest'
Error

Line: 3 Column: 1

              import io

import pytest

from mitmproxy.test import taddons
from mitmproxy import ctx


@pytest.mark.asyncio

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import io

import pytest

from mitmproxy.test import taddons
from mitmproxy import ctx


@pytest.mark.asyncio

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 10 Column: 1

              

@pytest.mark.asyncio
async def test_recordingmaster():
    with taddons.context() as tctx:
        assert not tctx.master.has_log("nonexistent")
        ctx.log.error("foo")
        assert not tctx.master.has_log("foo", level="debug")
        await tctx.master.await_log("foo", level="error")

            

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

              @pytest.mark.asyncio
async def test_recordingmaster():
    with taddons.context() as tctx:
        assert not tctx.master.has_log("nonexistent")
        ctx.log.error("foo")
        assert not tctx.master.has_log("foo", level="debug")
        await tctx.master.await_log("foo", level="error")



            

Reported by Bandit.

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

                  with taddons.context() as tctx:
        assert not tctx.master.has_log("nonexistent")
        ctx.log.error("foo")
        assert not tctx.master.has_log("foo", level="debug")
        await tctx.master.await_log("foo", level="error")


@pytest.mark.asyncio
async def test_dumplog():

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 19 Column: 1

              

@pytest.mark.asyncio
async def test_dumplog():
    with taddons.context() as tctx:
        ctx.log.info("testing")
        await tctx.master.await_log("testing")
        s = io.StringIO()
        tctx.master.dump_log(s)

            

Reported by Pylint.

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

Line: 23 Column: 9

                  with taddons.context() as tctx:
        ctx.log.info("testing")
        await tctx.master.await_log("testing")
        s = io.StringIO()
        tctx.master.dump_log(s)
        assert s.getvalue()


def test_load_script(tdata):

            

Reported by Pylint.

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

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

                      await tctx.master.await_log("testing")
        s = io.StringIO()
        tctx.master.dump_log(s)
        assert s.getvalue()


def test_load_script(tdata):
    with taddons.context() as tctx:
        s = tctx.script(

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 28 Column: 1

                      assert s.getvalue()


def test_load_script(tdata):
    with taddons.context() as tctx:
        s = tctx.script(
            tdata.path(
                "mitmproxy/data/addonscripts/recorder/recorder.py"
            )

            

Reported by Pylint.

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

Line: 30 Column: 9

              
def test_load_script(tdata):
    with taddons.context() as tctx:
        s = tctx.script(
            tdata.path(
                "mitmproxy/data/addonscripts/recorder/recorder.py"
            )
        )
        assert s

            

Reported by Pylint.

test/helper_tools/memoryleak.py
11 issues
Unable to import 'pympler'
Error

Line: 3 Column: 1

              import gc
import threading
from pympler import muppy, refbrowser
from OpenSSL import SSL
# import os
# os.environ["TK_LIBRARY"] = r"C:\Python27\tcl\tcl8.5"
# os.environ["TCL_LIBRARY"] = r"C:\Python27\tcl\tcl8.5"

# Also noteworthy: guppy, objgraph

            

Reported by Pylint.

Unused argument 'ctx'
Error

Line: 24 Column: 13

                  return str(id(obj)) + ": " + str(obj)[:100].replace("\r\n", "\\r\\n").replace("\n", "\\n")


def request(ctx, flow):
    global step, ssl
    print("==========")
    print(f"GC: {gc.collect()}")
    print(f"Threads: {threading.active_count()}")


            

Reported by Pylint.

Unused argument 'flow'
Error

Line: 24 Column: 18

                  return str(id(obj)) + ": " + str(obj)[:100].replace("\r\n", "\\r\\n").replace("\n", "\\n")


def request(ctx, flow):
    global step, ssl
    print("==========")
    print(f"GC: {gc.collect()}")
    print(f"Threads: {threading.active_count()}")


            

Reported by Pylint.

Global variable 'ssl' undefined at the module level
Error

Line: 25 Column: 5

              

def request(ctx, flow):
    global step, ssl
    print("==========")
    print(f"GC: {gc.collect()}")
    print(f"Threads: {threading.active_count()}")

    step += 1

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import gc
import threading
from pympler import muppy, refbrowser
from OpenSSL import SSL
# import os
# os.environ["TK_LIBRARY"] = r"C:\Python27\tcl\tcl8.5"
# os.environ["TCL_LIBRARY"] = r"C:\Python27\tcl\tcl8.5"

# Also noteworthy: guppy, objgraph

            

Reported by Pylint.

Constant name "step" doesn't conform to UPPER_CASE naming style
Error

Line: 11 Column: 1

              
# Also noteworthy: guppy, objgraph

step = 0
__memory_locals__ = True


def str_fun(obj):
    if isinstance(obj, dict):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 15 Column: 1

              __memory_locals__ = True


def str_fun(obj):
    if isinstance(obj, dict):
        if "__memory_locals__" in obj:
            return "(-locals-)"
        if "self" in obj and isinstance(obj["self"], refbrowser.InteractiveBrowser):
            return "(-browser-)"

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 24 Column: 1

                  return str(id(obj)) + ": " + str(obj)[:100].replace("\r\n", "\\r\\n").replace("\n", "\\n")


def request(ctx, flow):
    global step, ssl
    print("==========")
    print(f"GC: {gc.collect()}")
    print(f"Threads: {threading.active_count()}")


            

Reported by Pylint.

Constant name "ssl" doesn't conform to UPPER_CASE naming style
Error

Line: 25 Column: 5

              

def request(ctx, flow):
    global step, ssl
    print("==========")
    print(f"GC: {gc.collect()}")
    print(f"Threads: {threading.active_count()}")

    step += 1

            

Reported by Pylint.

Constant name "step" doesn't conform to UPPER_CASE naming style
Error

Line: 25 Column: 5

              

def request(ctx, flow):
    global step, ssl
    print("==========")
    print(f"GC: {gc.collect()}")
    print(f"Threads: {threading.active_count()}")

    step += 1

            

Reported by Pylint.

test/mitmproxy/addons/test_anticache.py
11 issues
Missing module docstring
Error

Line: 1 Column: 1

              from mitmproxy.test import tflow

from mitmproxy.addons import anticache
from mitmproxy.test import taddons


class TestAntiCache:
    def test_simple(self):
        sa = anticache.AntiCache()

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 7 Column: 1

              from mitmproxy.test import taddons


class TestAntiCache:
    def test_simple(self):
        sa = anticache.AntiCache()
        with taddons.context(sa) as tctx:
            f = tflow.tflow(resp=True)
            f.request.headers["if-modified-since"] = "test"

            

Reported by Pylint.

Missing class docstring
Error

Line: 7 Column: 1

              from mitmproxy.test import taddons


class TestAntiCache:
    def test_simple(self):
        sa = anticache.AntiCache()
        with taddons.context(sa) as tctx:
            f = tflow.tflow(resp=True)
            f.request.headers["if-modified-since"] = "test"

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 8 Column: 5

              

class TestAntiCache:
    def test_simple(self):
        sa = anticache.AntiCache()
        with taddons.context(sa) as tctx:
            f = tflow.tflow(resp=True)
            f.request.headers["if-modified-since"] = "test"
            f.request.headers["if-none-match"] = "test"

            

Reported by Pylint.

Method could be a function
Error

Line: 8 Column: 5

              

class TestAntiCache:
    def test_simple(self):
        sa = anticache.AntiCache()
        with taddons.context(sa) as tctx:
            f = tflow.tflow(resp=True)
            f.request.headers["if-modified-since"] = "test"
            f.request.headers["if-none-match"] = "test"

            

Reported by Pylint.

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

Line: 9 Column: 9

              
class TestAntiCache:
    def test_simple(self):
        sa = anticache.AntiCache()
        with taddons.context(sa) as tctx:
            f = tflow.tflow(resp=True)
            f.request.headers["if-modified-since"] = "test"
            f.request.headers["if-none-match"] = "test"


            

Reported by Pylint.

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

Line: 11 Column: 13

                  def test_simple(self):
        sa = anticache.AntiCache()
        with taddons.context(sa) as tctx:
            f = tflow.tflow(resp=True)
            f.request.headers["if-modified-since"] = "test"
            f.request.headers["if-none-match"] = "test"

            sa.request(f)
            assert "if-modified-since" in f.request.headers

            

Reported by Pylint.

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

                          f.request.headers["if-none-match"] = "test"

            sa.request(f)
            assert "if-modified-since" in f.request.headers
            assert "if-none-match" in f.request.headers

            tctx.configure(sa, anticache = True)
            sa.request(f)
            assert "if-modified-since" not in f.request.headers

            

Reported by Bandit.

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

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

              
            sa.request(f)
            assert "if-modified-since" in f.request.headers
            assert "if-none-match" in f.request.headers

            tctx.configure(sa, anticache = True)
            sa.request(f)
            assert "if-modified-since" not in f.request.headers
            assert "if-none-match" not in f.request.headers

            

Reported by Bandit.

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

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

              
            tctx.configure(sa, anticache = True)
            sa.request(f)
            assert "if-modified-since" not in f.request.headers
            assert "if-none-match" not in f.request.headers

            

Reported by Bandit.

mitmproxy/addons/keepserving.py
11 issues
Missing module docstring
Error

Line: 1 Column: 1

              import asyncio
from mitmproxy import ctx


class KeepServing:
    def load(self, loader):
        loader.add_option(
            "keepserving", bool, False,
            """

            

Reported by Pylint.

Missing class docstring
Error

Line: 5 Column: 1

              from mitmproxy import ctx


class KeepServing:
    def load(self, loader):
        loader.add_option(
            "keepserving", bool, False,
            """
            Continue serving after client playback, server playback or file

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 6 Column: 5

              

class KeepServing:
    def load(self, loader):
        loader.add_option(
            "keepserving", bool, False,
            """
            Continue serving after client playback, server playback or file
            read. This option is ignored by interactive tools, which always keep

            

Reported by Pylint.

Method could be a function
Error

Line: 6 Column: 5

              

class KeepServing:
    def load(self, loader):
        loader.add_option(
            "keepserving", bool, False,
            """
            Continue serving after client playback, server playback or file
            read. This option is ignored by interactive tools, which always keep

            

Reported by Pylint.

Method could be a function
Error

Line: 16 Column: 5

                          """
        )

    def keepgoing(self) -> bool:
        checks = [
            "readfile.reading",
            "replay.client.count",
            "replay.server.count",
        ]

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 16 Column: 5

                          """
        )

    def keepgoing(self) -> bool:
        checks = [
            "readfile.reading",
            "replay.client.count",
            "replay.server.count",
        ]

            

Reported by Pylint.

Use a generator instead 'any(ctx.master.commands.call(c) for c in checks)'
Error

Line: 22 Column: 16

                          "replay.client.count",
            "replay.server.count",
        ]
        return any([ctx.master.commands.call(c) for c in checks])

    def shutdown(self):  # pragma: no cover
        ctx.master.shutdown()

    async def watch(self):

            

Reported by Pylint.

Method could be a function
Error

Line: 24 Column: 5

                      ]
        return any([ctx.master.commands.call(c) for c in checks])

    def shutdown(self):  # pragma: no cover
        ctx.master.shutdown()

    async def watch(self):
        while True:
            await asyncio.sleep(0.1)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 24 Column: 5

                      ]
        return any([ctx.master.commands.call(c) for c in checks])

    def shutdown(self):  # pragma: no cover
        ctx.master.shutdown()

    async def watch(self):
        while True:
            await asyncio.sleep(0.1)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 27 Column: 5

                  def shutdown(self):  # pragma: no cover
        ctx.master.shutdown()

    async def watch(self):
        while True:
            await asyncio.sleep(0.1)
            if not self.keepgoing():
                self.shutdown()


            

Reported by Pylint.

mitmproxy/proxy/commands.py
11 issues
Too few public methods (1/2)
Error

Line: 18 Column: 1

                  import mitmproxy.proxy.layer


class Command:
    """
    Base class for all commands
    """

    blocking: Union[bool, "mitmproxy.proxy.layer.Layer"] = False

            

Reported by Pylint.

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

Line: 37 Column: 9

                  """

    def __repr__(self):
        x = self.__dict__.copy()
        x.pop("blocking", None)
        return f"{type(self).__name__}({repr(x)})"


class ConnectionCommand(Command):

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 42 Column: 1

                      return f"{type(self).__name__}({repr(x)})"


class ConnectionCommand(Command):
    """
    Commands involving a specific connection
    """
    connection: Connection


            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 52 Column: 1

                      self.connection = connection


class SendData(ConnectionCommand):
    """
    Send data to a remote peer
    """
    data: bytes


            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 67 Column: 1

                      return f"SendData({target}, {self.data})"


class OpenConnection(ConnectionCommand):
    """
    Open a new connection
    """
    connection: Server
    blocking = True

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 75 Column: 1

                  blocking = True


class CloseConnection(ConnectionCommand):
    """
    Close a connection. If the client connection is closed,
    all other connections will ultimately be closed during cleanup.
    """
    half_close: bool

            

Reported by Pylint.

Line too long (110/100)
Error

Line: 83 Column: 1

                  half_close: bool
    """
    If True, only close our half of the connection by sending a FIN packet.
    This is required from some protocols which close their end to signal completion and then continue reading,
    for example HTTP/1.0 without Content-Length header.
    """

    def __init__(self, connection: Connection, half_close: bool = False):
        super().__init__(connection)

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 106 Column: 1

                      return super().__new__(cls, *args, **kwargs)


class GetSocket(ConnectionCommand):
    """
    Get the underlying socket.
    This should really never be used, but is required to implement transparent mode.
    """
    blocking = True

            

Reported by Pylint.

Missing class docstring
Error

Line: 114 Column: 1

                  blocking = True


class Log(Command):
    message: str
    level: str

    def __init__(self, message: str, level: Literal["error", "warn", "info", "alert", "debug"] = "info"):
        self.message = message

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 114 Column: 1

                  blocking = True


class Log(Command):
    message: str
    level: str

    def __init__(self, message: str, level: Literal["error", "warn", "info", "alert", "debug"] = "info"):
        self.message = message

            

Reported by Pylint.

test/mitmproxy/proxy/bench.py
11 issues
Attempted relative import beyond top-level package
Error

Line: 11 Column: 1

              """
import copy

from .layers import test_tcp, test_tls
from .layers.http import test_http, test_http2


def test_bench_http_roundtrip(tctx, benchmark):
    # benchmark something

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 12 Column: 1

              import copy

from .layers import test_tcp, test_tls
from .layers.http import test_http, test_http2


def test_bench_http_roundtrip(tctx, benchmark):
    # benchmark something
    benchmark(test_http.test_http_proxy, tctx)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 15 Column: 1

              from .layers.http import test_http, test_http2


def test_bench_http_roundtrip(tctx, benchmark):
    # benchmark something
    benchmark(test_http.test_http_proxy, tctx)


def test_bench_http2_roundtrip(tctx, benchmark):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 20 Column: 1

                  benchmark(test_http.test_http_proxy, tctx)


def test_bench_http2_roundtrip(tctx, benchmark):
    # benchmark something
    benchmark(test_http2.test_simple, tctx)


def test_bench_tcp_roundtrip(tctx, benchmark):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 25 Column: 1

                  benchmark(test_http2.test_simple, tctx)


def test_bench_tcp_roundtrip(tctx, benchmark):
    # benchmark something
    benchmark(lambda: test_tcp.test_simple(copy.deepcopy(tctx)))


def test_bench_server_tls(tctx, benchmark):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 30 Column: 1

                  benchmark(lambda: test_tcp.test_simple(copy.deepcopy(tctx)))


def test_bench_server_tls(tctx, benchmark):
    t = test_tls.TestServerTLS().test_simple
    benchmark(lambda: t(copy.deepcopy(tctx)))


def test_bench_client_tls(tctx, benchmark):

            

Reported by Pylint.

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

Line: 31 Column: 5

              

def test_bench_server_tls(tctx, benchmark):
    t = test_tls.TestServerTLS().test_simple
    benchmark(lambda: t(copy.deepcopy(tctx)))


def test_bench_client_tls(tctx, benchmark):
    t = test_tls.TestClientTLS().test_client_only

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 35 Column: 1

                  benchmark(lambda: t(copy.deepcopy(tctx)))


def test_bench_client_tls(tctx, benchmark):
    t = test_tls.TestClientTLS().test_client_only
    benchmark(lambda: t(copy.deepcopy(tctx)))


def test_bench_tls_both(tctx, benchmark):

            

Reported by Pylint.

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

Line: 36 Column: 5

              

def test_bench_client_tls(tctx, benchmark):
    t = test_tls.TestClientTLS().test_client_only
    benchmark(lambda: t(copy.deepcopy(tctx)))


def test_bench_tls_both(tctx, benchmark):
    t = test_tls.TestClientTLS().test_server_required

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 40 Column: 1

                  benchmark(lambda: t(copy.deepcopy(tctx)))


def test_bench_tls_both(tctx, benchmark):
    t = test_tls.TestClientTLS().test_server_required
    benchmark(lambda: t(copy.deepcopy(tctx)))

            

Reported by Pylint.

mitmproxy/contentviews/multipart.py
11 issues
Attempted relative import beyond top-level package
Error

Line: 5 Column: 1

              
from mitmproxy.coretypes import multidict
from mitmproxy.net.http import multipart
from . import base


class ViewMultipart(base.View):
    name = "Multipart Form"


            

Reported by Pylint.

Unused argument 'metadata'
Error

Line: 23 Column: 1

                      if v:
            return "Multipart form", self._format(v)

    def render_priority(self, data: bytes, *, content_type: Optional[str] = None, **metadata) -> float:
        return float(content_type == "multipart/form-data")

            

Reported by Pylint.

Unused argument 'data'
Error

Line: 23 Column: 31

                      if v:
            return "Multipart form", self._format(v)

    def render_priority(self, data: bytes, *, content_type: Optional[str] = None, **metadata) -> float:
        return float(content_type == "multipart/form-data")

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from typing import Optional

from mitmproxy.coretypes import multidict
from mitmproxy.net.http import multipart
from . import base


class ViewMultipart(base.View):
    name = "Multipart Form"

            

Reported by Pylint.

Missing class docstring
Error

Line: 8 Column: 1

              from . import base


class ViewMultipart(base.View):
    name = "Multipart Form"

    @staticmethod
    def _format(v):
        yield [("highlight", "Form data:\n")]

            

Reported by Pylint.

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

Line: 12 Column: 5

                  name = "Multipart Form"

    @staticmethod
    def _format(v):
        yield [("highlight", "Form data:\n")]
        yield from base.format_dict(multidict.MultiDict(v))

    def __call__(self, data: bytes, content_type: Optional[str] = None, **metadata):
        if content_type is None:

            

Reported by Pylint.

Either all return statements in a function should return an expression, or none of them should.
Error

Line: 16 Column: 5

                      yield [("highlight", "Form data:\n")]
        yield from base.format_dict(multidict.MultiDict(v))

    def __call__(self, data: bytes, content_type: Optional[str] = None, **metadata):
        if content_type is None:
            return
        v = multipart.decode(content_type, data)
        if v:
            return "Multipart form", self._format(v)

            

Reported by Pylint.

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

Line: 19 Column: 9

                  def __call__(self, data: bytes, content_type: Optional[str] = None, **metadata):
        if content_type is None:
            return
        v = multipart.decode(content_type, data)
        if v:
            return "Multipart form", self._format(v)

    def render_priority(self, data: bytes, *, content_type: Optional[str] = None, **metadata) -> float:
        return float(content_type == "multipart/form-data")

            

Reported by Pylint.

Method could be a function
Error

Line: 23 Column: 5

                      if v:
            return "Multipart form", self._format(v)

    def render_priority(self, data: bytes, *, content_type: Optional[str] = None, **metadata) -> float:
        return float(content_type == "multipart/form-data")

            

Reported by Pylint.

Line too long (103/100)
Error

Line: 23 Column: 1

                      if v:
            return "Multipart form", self._format(v)

    def render_priority(self, data: bytes, *, content_type: Optional[str] = None, **metadata) -> float:
        return float(content_type == "multipart/form-data")

            

Reported by Pylint.