The following issues were found

test/mitmproxy/tools/console/test_commander.py
131 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest

from mitmproxy import options
from mitmproxy.addons import command_history
from mitmproxy.test import taddons
from mitmproxy.tools.console.commander import commander


@pytest.fixture(autouse=True)

            

Reported by Pylint.

Redefining name 'commander_tctx' from outer scope (line 10)
Error

Line: 17 Column: 5

              
    opts = options.Options()
    opts.set(*[f"confdir={confdir}"])
    commander_tctx = taddons.context(options=opts)
    ch = command_history.CommandHistory()
    commander_tctx.master.addons.add(ch)
    ch.configure('command_history')

    yield commander_tctx

            

Reported by Pylint.

Redefining name 'commander_tctx' from outer scope (line 10)
Error

Line: 67 Column: 37

              
class TestCommandEdit:

    def test_open_command_bar(self, commander_tctx):
        edit = commander.CommandEdit(commander_tctx.master, '')

        try:
            edit.update()
        except IndexError:

            

Reported by Pylint.

Redefining name 'commander_tctx' from outer scope (line 10)
Error

Line: 75 Column: 27

                      except IndexError:
            pytest.faied("Unexpected IndexError")

    def test_insert(self, commander_tctx):
        edit = commander.CommandEdit(commander_tctx.master, '')
        edit.keypress(1, 'a')
        assert edit.get_edit_text() == 'a'

        # Don't let users type a space before starting a command

            

Reported by Pylint.

Redefining name 'commander_tctx' from outer scope (line 10)
Error

Line: 86 Column: 30

                      edit.keypress(1, ' ')
        assert edit.get_edit_text() == ''

    def test_backspace(self, commander_tctx):
        edit = commander.CommandEdit(commander_tctx.master, '')

        edit.keypress(1, 'a')
        edit.keypress(1, 'b')
        assert edit.get_edit_text() == 'ab'

            

Reported by Pylint.

Redefining name 'commander_tctx' from outer scope (line 10)
Error

Line: 96 Column: 25

                      edit.keypress(1, 'backspace')
        assert edit.get_edit_text() == 'a'

    def test_left(self, commander_tctx):
        edit = commander.CommandEdit(commander_tctx.master, '')

        edit.keypress(1, 'a')
        assert edit.cbuf.cursor == 1


            

Reported by Pylint.

Redefining name 'commander_tctx' from outer scope (line 10)
Error

Line: 109 Column: 26

                      edit.keypress(1, 'left')
        assert edit.cbuf.cursor == 0

    def test_right(self, commander_tctx):
        edit = commander.CommandEdit(commander_tctx.master, '')

        edit.keypress(1, 'a')
        assert edit.cbuf.cursor == 1


            

Reported by Pylint.

Redefining name 'commander_tctx' from outer scope (line 10)
Error

Line: 126 Column: 32

                      edit.keypress(1, 'right')
        assert edit.cbuf.cursor == 1

    def test_up_and_down(self, commander_tctx):
        edit = commander.CommandEdit(commander_tctx.master, '')

        commander_tctx.master.commands.execute('commands.history.clear')
        commander_tctx.master.commands.execute('commands.history.add "cmd1"')


            

Reported by Pylint.

Redefining name 'commander_tctx' from outer scope (line 10)
Error

Line: 303 Column: 35

                          [("123", 2), ("13", 1)],
            [("123", 0), ("123", 0)],
        ]
        with taddons.context() as commander_tctx:
            for start, output in tests:
                cb = commander.CommandBuffer(commander_tctx.master)
                cb.text, cb.cursor = start[0], start[1]
                cb.backspace()
                assert cb.text == output[0]

            

Reported by Pylint.

Redefining name 'commander_tctx' from outer scope (line 10)
Error

Line: 313 Column: 35

              
    def test_left(self):
        cursors = [3, 2, 1, 0, 0]
        with taddons.context() as commander_tctx:
            cb = commander.CommandBuffer(commander_tctx.master)
            cb.text, cb.cursor = "abcd", 4
            for c in cursors:
                cb.left()
                assert cb.cursor == c

            

Reported by Pylint.

test/mitmproxy/proxy/layers/test_tls.py
130 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              import ssl
import typing

import pytest

from OpenSSL import SSL
from mitmproxy import connection
from mitmproxy.connection import ConnectionState, Server
from mitmproxy.proxy import commands, context, events, layer

            

Reported by Pylint.

No value for argument 'callback' in method call
Error

Line: 193 Column: 9

                      )
        if alpn is not None:
            ssl_context.set_alpn_protos([alpn])
        ssl_context.set_verify(SSL.VERIFY_PEER)

        tls_start.ssl_conn = SSL.Connection(ssl_context)
        tls_start.ssl_conn.set_connect_state()
        # Set SNI
        tls_start.ssl_conn.set_tlsext_host_name(tls_start.conn.sni.encode())

            

Reported by Pylint.

Redefining name 'data' from outer scope (line 11)
Error

Line: 29 Column: 5

              

def test_record_contents():
    data = bytes.fromhex(
        "1603010002beef"
        "1603010001ff"
    )
    assert list(tls.handshake_record_contents(data)) == [
        b"\xbe\xef", b"\xff"

            

Reported by Pylint.

Redefining name 'data' from outer scope (line 11)
Error

Line: 127 Column: 5

              
def _test_echo(playbook: tutils.Playbook, tssl: SSLTest, conn: connection.Connection) -> None:
    tssl.obj.write(b"Hello World")
    data = tutils.Placeholder(bytes)
    assert (
            playbook
            >> events.DataReceived(conn, tssl.bio_read())
            << commands.SendData(conn, data)
    )

            

Reported by Pylint.

Redefining name 'data' from outer scope (line 11)
Error

Line: 150 Column: 5

              

def interact(playbook: tutils.Playbook, conn: connection.Connection, tssl: SSLTest):
    data = tutils.Placeholder(bytes)
    assert (
            playbook
            >> events.DataReceived(conn, tssl.bio_read())
            << commands.SendData(conn, data)
    )

            

Reported by Pylint.

Keyword argument before variable positional arguments list in the definition of reply_tls_start_client function
Error

Line: 159 Column: 1

                  tssl.bio_write(data())


def reply_tls_start_client(alpn: typing.Optional[bytes] = None, *args, **kwargs) -> tutils.reply:
    """
    Helper function to simplify the syntax for tls_start_client hooks.
    """

    def make_client_conn(tls_start: tls.TlsStartData) -> None:

            

Reported by Pylint.

Keyword argument before variable positional arguments list in the definition of reply_tls_start_server function
Error

Line: 181 Column: 1

                  return tutils.reply(*args, side_effect=make_client_conn, **kwargs)


def reply_tls_start_server(alpn: typing.Optional[bytes] = None, *args, **kwargs) -> tutils.reply:
    """
    Helper function to simplify the syntax for tls_start_server hooks.
    """

    def make_server_conn(tls_start: tls.TlsStartData) -> None:

            

Reported by Pylint.

Access to a protected member _ssl of a client class
Error

Line: 204 Column: 41

                      # Recent OpenSSL versions provide slightly nicer ways to do this, but they are not exposed in
        # cryptography and likely a PITA to add.
        # https://wiki.openssl.org/index.php/Hostname_validation
        param = SSL._lib.SSL_get0_param(tls_start.ssl_conn._ssl)
        # Common Name matching is disabled in both Chrome and Firefox, so we should disable it, too.
        # https://www.chromestatus.com/feature/4981025180483584
        SSL._lib.X509_VERIFY_PARAM_set_hostflags(
            param,
            SSL._lib.X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS | SSL._lib.X509_CHECK_FLAG_NEVER_CHECK_SUBJECT

            

Reported by Pylint.

Access to a protected member _lib of a client class
Error

Line: 204 Column: 17

                      # Recent OpenSSL versions provide slightly nicer ways to do this, but they are not exposed in
        # cryptography and likely a PITA to add.
        # https://wiki.openssl.org/index.php/Hostname_validation
        param = SSL._lib.SSL_get0_param(tls_start.ssl_conn._ssl)
        # Common Name matching is disabled in both Chrome and Firefox, so we should disable it, too.
        # https://www.chromestatus.com/feature/4981025180483584
        SSL._lib.X509_VERIFY_PARAM_set_hostflags(
            param,
            SSL._lib.X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS | SSL._lib.X509_CHECK_FLAG_NEVER_CHECK_SUBJECT

            

Reported by Pylint.

Access to a protected member _lib of a client class
Error

Line: 207 Column: 9

                      param = SSL._lib.SSL_get0_param(tls_start.ssl_conn._ssl)
        # Common Name matching is disabled in both Chrome and Firefox, so we should disable it, too.
        # https://www.chromestatus.com/feature/4981025180483584
        SSL._lib.X509_VERIFY_PARAM_set_hostflags(
            param,
            SSL._lib.X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS | SSL._lib.X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
        )
        SSL._openssl_assert(
            SSL._lib.X509_VERIFY_PARAM_set1_host(param, tls_start.conn.sni.encode(), 0) == 1

            

Reported by Pylint.

examples/contrib/webscanner_helper/test_urlindex.py
113 issues
Unable to import 'mitmproxy.test'
Error

Line: 8 Column: 1

              from typing import List
from unittest.mock import patch

from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlindex import UrlIndexWriter, SetEncoder, JSONUrlIndexWriter, \
    TextUrlIndexWriter, WRITER, \
    filter_404, \

            

Reported by Pylint.

Unable to import 'mitmproxy.test'
Error

Line: 9 Column: 1

              from unittest.mock import patch

from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlindex import UrlIndexWriter, SetEncoder, JSONUrlIndexWriter, \
    TextUrlIndexWriter, WRITER, \
    filter_404, \
    UrlIndexAddon

            

Reported by Pylint.

Unable to import 'examples.contrib.webscanner_helper.urlindex'
Error

Line: 11 Column: 1

              from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlindex import UrlIndexWriter, SetEncoder, JSONUrlIndexWriter, \
    TextUrlIndexWriter, WRITER, \
    filter_404, \
    UrlIndexAddon



            

Reported by Pylint.

Second argument of isinstance is not a type
Error

Line: 33 Column: 16

                  def test_set_encoder_set(self):
        test_set = {"foo", "bar", "42"}
        result = SetEncoder.default(SetEncoder(), test_set)
        assert isinstance(result, List)
        assert 'foo' in result
        assert 'bar' in result
        assert '42' in result

    def test_set_encoder_str(self):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import json
from json import JSONDecodeError
from pathlib import Path
from unittest import mock
from typing import List
from unittest.mock import patch

from mitmproxy.test import tflow
from mitmproxy.test import tutils

            

Reported by Pylint.

Imports from package unittest are not grouped
Error

Line: 6 Column: 1

              from pathlib import Path
from unittest import mock
from typing import List
from unittest.mock import patch

from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlindex import UrlIndexWriter, SetEncoder, JSONUrlIndexWriter, \

            

Reported by Pylint.

Line too long (105/100)
Error

Line: 11 Column: 1

              from mitmproxy.test import tflow
from mitmproxy.test import tutils

from examples.contrib.webscanner_helper.urlindex import UrlIndexWriter, SetEncoder, JSONUrlIndexWriter, \
    TextUrlIndexWriter, WRITER, \
    filter_404, \
    UrlIndexAddon



            

Reported by Pylint.

Missing class docstring
Error

Line: 17 Column: 1

                  UrlIndexAddon


class TestBaseClass:

    @patch.multiple(UrlIndexWriter, __abstractmethods__=set())
    def test_base_class(self, tmpdir):
        tmpfile = tmpdir.join("tmpfile")
        index_writer = UrlIndexWriter(tmpfile)

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 17 Column: 1

                  UrlIndexAddon


class TestBaseClass:

    @patch.multiple(UrlIndexWriter, __abstractmethods__=set())
    def test_base_class(self, tmpdir):
        tmpfile = tmpdir.join("tmpfile")
        index_writer = UrlIndexWriter(tmpfile)

            

Reported by Pylint.

Method could be a function
Error

Line: 20 Column: 5

              class TestBaseClass:

    @patch.multiple(UrlIndexWriter, __abstractmethods__=set())
    def test_base_class(self, tmpdir):
        tmpfile = tmpdir.join("tmpfile")
        index_writer = UrlIndexWriter(tmpfile)
        index_writer.load()
        index_writer.add_url(tflow.tflow())
        index_writer.save()

            

Reported by Pylint.

mitmproxy/tools/web/app.py
111 issues
Unable to import 'tornado.escape'
Error

Line: 10 Column: 1

              from io import BytesIO
from typing import ClassVar, Optional

import tornado.escape
import tornado.web
import tornado.websocket

import mitmproxy.flow
import mitmproxy.tools.web.master  # noqa

            

Reported by Pylint.

Unable to import 'tornado.web'
Error

Line: 11 Column: 1

              from typing import ClassVar, Optional

import tornado.escape
import tornado.web
import tornado.websocket

import mitmproxy.flow
import mitmproxy.tools.web.master  # noqa
from mitmproxy import contentviews

            

Reported by Pylint.

Unable to import 'tornado.websocket'
Error

Line: 12 Column: 1

              
import tornado.escape
import tornado.web
import tornado.websocket

import mitmproxy.flow
import mitmproxy.tools.web.master  # noqa
from mitmproxy import contentviews
from mitmproxy import flowfilter

            

Reported by Pylint.

TODO: remove, use flow.is_replay instead.
Error

Line: 96 Column: 3

                              "contentHash": content_hash,
                "timestamp_start": flow.request.timestamp_start,
                "timestamp_end": flow.request.timestamp_end,
                "is_replay": flow.is_replay == "request",  # TODO: remove, use flow.is_replay instead.
                "pretty_host": flow.request.pretty_host,
            }
        if flow.response:
            if flow.response.raw_content:
                content_length = len(flow.response.raw_content)

            

Reported by Pylint.

TODO: remove, use flow.is_replay instead.
Error

Line: 115 Column: 3

                              "contentHash": content_hash,
                "timestamp_start": flow.response.timestamp_start,
                "timestamp_end": flow.response.timestamp_end,
                "is_replay": flow.is_replay == "response",  # TODO: remove, use flow.is_replay instead.
            }
            if flow.response.data.trailers:
                f["response"]["trailers"] = tuple(flow.response.data.trailers.items(True))

    return f

            

Reported by Pylint.

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

Line: 166 Column: 13

                      try:
            return json.loads(self.request.body.decode())
        except Exception as e:
            raise APIError(400, "Malformed JSON: {}".format(str(e)))

    @property
    def filecontents(self):
        """
        Accept either a multipart/form file upload or just take the plain request body.

            

Reported by Pylint.

FIXME: Add a facility to addon.view to safely access the store
Error

Line: 190 Column: 3

                  @property
    def flow(self) -> mitmproxy.flow.Flow:
        flow_id = str(self.path_kwargs["flow_id"])
        # FIXME: Add a facility to addon.view to safely access the store
        flow = self.view.get_by_id(flow_id)
        if flow:
            return flow
        else:
            raise APIError(404, "Flow not found.")

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 235 Column: 20

                      for conn in cls.connections:
            try:
                conn.write_message(message)
            except Exception:  # pragma: no cover
                logging.error("Error sending message", exc_info=True)


class ClientConnection(WebSocketEventBroadcaster):
    connections: ClassVar[set] = set()

            

Reported by Pylint.

Unused argument 'flow_id'
Error

Line: 293 Column: 20

              

class ResumeFlow(RequestHandler):
    def post(self, flow_id):
        self.flow.resume()
        self.view.update([self.flow])


class KillFlow(RequestHandler):

            

Reported by Pylint.

Unused argument 'flow_id'
Error

Line: 299 Column: 20

              

class KillFlow(RequestHandler):
    def post(self, flow_id):
        if self.flow.killable:
            self.flow.kill()
            self.view.update([self.flow])



            

Reported by Pylint.

test/mitmproxy/coretypes/test_multidict.py
109 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest

from mitmproxy.coretypes import multidict


class _TMulti:
    @staticmethod
    def _kconv(key):
        return key.lower()

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest

from mitmproxy.coretypes import multidict


class _TMulti:
    @staticmethod
    def _kconv(key):
        return key.lower()

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 6 Column: 1

              from mitmproxy.coretypes import multidict


class _TMulti:
    @staticmethod
    def _kconv(key):
        return key.lower()



            

Reported by Pylint.

Missing class docstring
Error

Line: 12 Column: 1

                      return key.lower()


class TMultiDict(_TMulti, multidict.MultiDict):
    pass


class TestMultiDict:
    @staticmethod

            

Reported by Pylint.

Missing class docstring
Error

Line: 16 Column: 1

                  pass


class TestMultiDict:
    @staticmethod
    def _multi():
        return TMultiDict((
            ("foo", "bar"),
            ("bar", "baz"),

            

Reported by Pylint.

Method could be a function
Error

Line: 25 Column: 5

                          ("Bar", "bam")
        ))

    def test_init(self):
        md = TMultiDict()
        assert len(md) == 0

        md = TMultiDict([("foo", "bar")])
        assert len(md) == 1

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 25 Column: 5

                          ("Bar", "bam")
        ))

    def test_init(self):
        md = TMultiDict()
        assert len(md) == 0

        md = TMultiDict([("foo", "bar")])
        assert len(md) == 1

            

Reported by Pylint.

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

Line: 26 Column: 9

                      ))

    def test_init(self):
        md = TMultiDict()
        assert len(md) == 0

        md = TMultiDict([("foo", "bar")])
        assert len(md) == 1
        assert md.fields == (("foo", "bar"),)

            

Reported by Pylint.

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

              
    def test_init(self):
        md = TMultiDict()
        assert len(md) == 0

        md = TMultiDict([("foo", "bar")])
        assert len(md) == 1
        assert md.fields == (("foo", "bar"),)


            

Reported by Bandit.

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

Line: 29 Column: 9

                      md = TMultiDict()
        assert len(md) == 0

        md = TMultiDict([("foo", "bar")])
        assert len(md) == 1
        assert md.fields == (("foo", "bar"),)

    def test_repr(self):
        assert repr(self._multi()) == (

            

Reported by Pylint.

test/mitmproxy/proxy/layers/test_websocket.py
102 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              import secrets
from dataclasses import dataclass

import pytest

import wsproto
import wsproto.events
from mitmproxy.http import HTTPFlow, Request, Response
from mitmproxy.proxy.layers.http import HTTPMode

            

Reported by Pylint.

Unable to import 'wsproto'
Error

Line: 6 Column: 1

              
import pytest

import wsproto
import wsproto.events
from mitmproxy.http import HTTPFlow, Request, Response
from mitmproxy.proxy.layers.http import HTTPMode
from mitmproxy.proxy.commands import SendData, CloseConnection, Log
from mitmproxy.connection import ConnectionState

            

Reported by Pylint.

Unable to import 'wsproto.events'
Error

Line: 7 Column: 1

              import pytest

import wsproto
import wsproto.events
from mitmproxy.http import HTTPFlow, Request, Response
from mitmproxy.proxy.layers.http import HTTPMode
from mitmproxy.proxy.commands import SendData, CloseConnection, Log
from mitmproxy.connection import ConnectionState
from mitmproxy.proxy.events import DataReceived, ConnectionClosed

            

Reported by Pylint.

Unable to import 'wsproto.frame_protocol'
Error

Line: 17 Column: 1

              from mitmproxy.proxy.layers.websocket import WebSocketMessageInjected
from mitmproxy.websocket import WebSocketData, WebSocketMessage
from test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply
from wsproto.frame_protocol import Opcode


@dataclass
class _Masked:
    unmasked: bytes

            

Reported by Pylint.

Redefining name 'masked' from outer scope (line 35)
Error

Line: 44 Column: 5

                  assert header[1] < 126  # assert that this is neither masked nor extended payload
    header[1] |= 0b1000_0000
    mask = secrets.token_bytes(4)
    masked = bytes([x ^ mask[i % 4] for i, x in enumerate(unmasked[2:])])
    return bytes(header + mask + masked)


def test_masking():
    m = masked(b"\x02\x03foo")

            

Reported by Pylint.

Redefining name 'ws_testdata' from outer scope (line 113)
Error

Line: 133 Column: 25

                  return tctx, Playbook(websocket.WebsocketLayer(tctx, flow)), flow


def test_modify_message(ws_testdata):
    tctx, playbook, flow = ws_testdata
    assert (
            playbook
            << websocket.WebsocketStartHook(flow)
            >> reply()

            

Reported by Pylint.

Redefining name 'ws_testdata' from outer scope (line 113)
Error

Line: 150 Column: 24

                  )


def test_empty_message(ws_testdata):
    tctx, playbook, flow = ws_testdata
    assert (
            playbook
            << websocket.WebsocketStartHook(flow)
            >> reply()

            

Reported by Pylint.

Redefining name 'ws_testdata' from outer scope (line 113)
Error

Line: 167 Column: 23

                  )


def test_drop_message(ws_testdata):
    tctx, playbook, flow = ws_testdata
    assert (
            playbook
            << websocket.WebsocketStartHook(flow)
            >> reply()

            

Reported by Pylint.

Redefining name 'ws_testdata' from outer scope (line 113)
Error

Line: 184 Column: 21

                  )


def test_fragmented(ws_testdata):
    tctx, playbook, flow = ws_testdata
    assert (
            playbook
            << websocket.WebsocketStartHook(flow)
            >> reply()

            

Reported by Pylint.

Redefining name 'ws_testdata' from outer scope (line 113)
Error

Line: 200 Column: 23

                  assert flow.websocket.messages[-1].content == b"foobar"


def test_unfragmented(ws_testdata):
    tctx, playbook, flow = ws_testdata
    assert (
            playbook
            << websocket.WebsocketStartHook(flow)
            >> reply()

            

Reported by Pylint.

mitmproxy/tools/console/grideditor/base.py
100 issues
Unable to import 'urwid'
Error

Line: 5 Column: 1

              import copy
import os
import typing
import urwid

from mitmproxy.utils import strutils
from mitmproxy import exceptions
from mitmproxy.tools.console import signals
from mitmproxy.tools.console import layoutwidget

            

Reported by Pylint.

Unused import mitmproxy.tools.console.master
Error

Line: 11 Column: 1

              from mitmproxy import exceptions
from mitmproxy.tools.console import signals
from mitmproxy.tools.console import layoutwidget
import mitmproxy.tools.console.master # noqa


def read_file(filename: str, escaped: bool) -> typing.AnyStr:
    filename = os.path.expanduser(filename)
    try:

            

Reported by Pylint.

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

Line: 25 Column: 13

                      try:
            d = strutils.escaped_str_to_bytes(d)
        except ValueError:
            raise exceptions.CommandError("Invalid Python-style string encoding.")
    return d


class Cell(urwid.WidgetWrap):
    def get_data(self):

            

Reported by Pylint.

Unused argument 'editor'
Error

Line: 59 Column: 34

                  def blank(self) -> typing.Any:
        pass

    def keypress(self, key: str, editor: "GridEditor") -> typing.Optional[str]:
        return key


class GridRow(urwid.WidgetWrap):


            

Reported by Pylint.

Useless super delegation in method '__init__'
Error

Line: 249 Column: 5

              

class GridListBox(urwid.ListBox):
    def __init__(self, lw):
        super().__init__(lw)


FIRST_WIDTH_MAX = 40


            

Reported by Pylint.

Unused argument 'col'
Error

Line: 372 Column: 24

                      """
        return data

    def is_error(self, col: int, val: typing.Any) -> typing.Optional[str]:
        """
            Return None, or a string error message.
        """
        return None


            

Reported by Pylint.

Unused argument 'val'
Error

Line: 372 Column: 34

                      """
        return data

    def is_error(self, col: int, val: typing.Any) -> typing.Optional[str]:
        """
            Return None, or a string error message.
        """
        return None


            

Reported by Pylint.

Unused argument 'key'
Error

Line: 378 Column: 26

                      """
        return None

    def handle_key(self, key):
        return False

    def cmd_add(self):
        self.walker.add()


            

Reported by Pylint.

Attribute '_w' defined outside __init__
Error

Line: 466 Column: 13

              
    def layout_pushed(self, prev):
        if self.master.view.focus.flow:
            self._w = BaseGridEditor(
                self.master,
                self.title,
                self.columns,
                self.get_data(self.master.view.focus.flow),
                self.set_data_update,

            

Reported by Pylint.

Attribute '_w' defined outside __init__
Error

Line: 475 Column: 13

                              self.master.view.focus.flow,
            )
        else:
            self._w = urwid.Pile([])

            

Reported by Pylint.

test/release/test_cibuild.py
96 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              import io
from pathlib import Path

import pytest

from release import cibuild

root = Path(__file__).parent.parent.parent


            

Reported by Pylint.

Unable to import 'release'
Error

Line: 6 Column: 1

              
import pytest

from release import cibuild

root = Path(__file__).parent.parent.parent


def test_buildenviron_live():

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 36 Column: 9

                      root_dir=root,
    )
    with pytest.raises(cibuild.BuildError):
        be.version
    with pytest.raises(cibuild.BuildError):
        be.platform_tag


def test_buildenviron_pr(monkeypatch):

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 38 Column: 9

                  with pytest.raises(cibuild.BuildError):
        be.version
    with pytest.raises(cibuild.BuildError):
        be.platform_tag


def test_buildenviron_pr(monkeypatch):
    # Simulates a PR. We build everything, but don't have access to secret
    # credential env variables.

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import io
from pathlib import Path

import pytest

from release import cibuild

root = Path(__file__).parent.parent.parent


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 11 Column: 1

              root = Path(__file__).parent.parent.parent


def test_buildenviron_live():
    be = cibuild.BuildEnviron.from_env()
    assert be.release_dir


def test_buildenviron_common():

            

Reported by Pylint.

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

Line: 12 Column: 5

              

def test_buildenviron_live():
    be = cibuild.BuildEnviron.from_env()
    assert be.release_dir


def test_buildenviron_common():
    be = cibuild.BuildEnviron(

            

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

              
def test_buildenviron_live():
    be = cibuild.BuildEnviron.from_env()
    assert be.release_dir


def test_buildenviron_common():
    be = cibuild.BuildEnviron(
        system="Linux",

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 16 Column: 1

                  assert be.release_dir


def test_buildenviron_common():
    be = cibuild.BuildEnviron(
        system="Linux",
        root_dir=root,
        branch="main",
    )

            

Reported by Pylint.

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

Line: 17 Column: 5

              

def test_buildenviron_common():
    be = cibuild.BuildEnviron(
        system="Linux",
        root_dir=root,
        branch="main",
    )
    assert be.release_dir == be.root_dir / "release"

            

Reported by Pylint.

test/mitmproxy/addons/test_proxyauth.py
95 issues
Unable to import 'ldap3'
Error

Line: 4 Column: 1

              import binascii
from unittest import mock

import ldap3
import pytest

from mitmproxy import exceptions
from mitmproxy.addons import proxyauth
from mitmproxy.test import taddons

            

Reported by Pylint.

Unable to import 'pytest'
Error

Line: 5 Column: 1

              from unittest import mock

import ldap3
import pytest

from mitmproxy import exceptions
from mitmproxy.addons import proxyauth
from mitmproxy.test import taddons
from mitmproxy.test import tflow

            

Reported by Pylint.

Redefining built-in 'input'
Error

Line: 33 Column: 48

                      'basic abc',
        'basic ' + binascii.b2a_base64(b"foo").decode("ascii"),
    ])
    def test_parse_http_basic_auth_error(self, input):
        with pytest.raises(ValueError):
            proxyauth.parse_http_basic_auth(input)

    def test_parse_http_basic_auth(self):
        input = proxyauth.mkauth("test", "test")

            

Reported by Pylint.

Redefining built-in 'input'
Error

Line: 38 Column: 9

                          proxyauth.parse_http_basic_auth(input)

    def test_parse_http_basic_auth(self):
        input = proxyauth.mkauth("test", "test")
        assert proxyauth.parse_http_basic_auth(input) == ("basic", "test", "test")


class TestProxyAuth:
    @pytest.mark.parametrize('mode, expected', [

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import binascii
from unittest import mock

import ldap3
import pytest

from mitmproxy import exceptions
from mitmproxy.addons import proxyauth
from mitmproxy.test import taddons

            

Reported by Pylint.

Missing class docstring
Error

Line: 13 Column: 1

              from mitmproxy.test import tflow


class TestMkauth:
    def test_mkauth_scheme(self):
        assert proxyauth.mkauth('username', 'password') == 'basic dXNlcm5hbWU6cGFzc3dvcmQ=\n'

    @pytest.mark.parametrize('scheme, expected', [
        ('', ' dXNlcm5hbWU6cGFzc3dvcmQ=\n'),

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 14 Column: 5

              

class TestMkauth:
    def test_mkauth_scheme(self):
        assert proxyauth.mkauth('username', 'password') == 'basic dXNlcm5hbWU6cGFzc3dvcmQ=\n'

    @pytest.mark.parametrize('scheme, expected', [
        ('', ' dXNlcm5hbWU6cGFzc3dvcmQ=\n'),
        ('basic', 'basic dXNlcm5hbWU6cGFzc3dvcmQ=\n'),

            

Reported by Pylint.

Method could be a function
Error

Line: 14 Column: 5

              

class TestMkauth:
    def test_mkauth_scheme(self):
        assert proxyauth.mkauth('username', 'password') == 'basic dXNlcm5hbWU6cGFzc3dvcmQ=\n'

    @pytest.mark.parametrize('scheme, expected', [
        ('', ' dXNlcm5hbWU6cGFzc3dvcmQ=\n'),
        ('basic', 'basic dXNlcm5hbWU6cGFzc3dvcmQ=\n'),

            

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

              
class TestMkauth:
    def test_mkauth_scheme(self):
        assert proxyauth.mkauth('username', 'password') == 'basic dXNlcm5hbWU6cGFzc3dvcmQ=\n'

    @pytest.mark.parametrize('scheme, expected', [
        ('', ' dXNlcm5hbWU6cGFzc3dvcmQ=\n'),
        ('basic', 'basic dXNlcm5hbWU6cGFzc3dvcmQ=\n'),
        ('foobar', 'foobar dXNlcm5hbWU6cGFzc3dvcmQ=\n'),

            

Reported by Bandit.

Method could be a function
Error

Line: 21 Column: 5

                      ('', ' dXNlcm5hbWU6cGFzc3dvcmQ=\n'),
        ('basic', 'basic dXNlcm5hbWU6cGFzc3dvcmQ=\n'),
        ('foobar', 'foobar dXNlcm5hbWU6cGFzc3dvcmQ=\n'),
    ])
    def test_mkauth(self, scheme, expected):
        assert proxyauth.mkauth('username', 'password', scheme) == expected


class TestParseHttpBasicAuth:

            

Reported by Pylint.

release/cibuild.py
95 issues
Unable to import 'parver'
Error

Line: 20 Column: 1

              
import click
import cryptography.fernet
import parver


@contextlib.contextmanager
def chdir(path: Path):  # pragma: no cover
    old_dir = os.getcwd()

            

Reported by Pylint.

Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
Security blacklist

Line: 418
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b310-urllib-urlopen

                                  click.secho(f"Downloading... {round(100 * done / total)}%")

            tmp = IB_SETUP.with_suffix(".tmp")
            urllib.request.urlretrieve(
                f"https://clients.bitrock.com/installbuilder/installbuilder-enterprise-{IB_VERSION}-windows-x64-installer.exe",
                tmp,
                reporthook=report
            )
            tmp.rename(IB_SETUP)

            

Reported by Bandit.

Unnecessary pass statement
Error

Line: 465 Column: 5

                  """
    mitmproxy build tool
    """
    pass


@cli.command("build")
def build():  # pragma: no cover
    """

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3

import contextlib
import hashlib
import os
import platform
import re
import shutil
import subprocess

            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

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

              import platform
import re
import shutil
import subprocess
import sys
import tarfile
import urllib.request
import zipfile
from dataclasses import dataclass

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 24 Column: 1

              

@contextlib.contextmanager
def chdir(path: Path):  # pragma: no cover
    old_dir = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(old_dir)


            

Reported by Pylint.

Missing class docstring
Error

Line: 31 Column: 1

                  os.chdir(old_dir)


class BuildError(Exception):
    pass


def bool_from_env(envvar: str) -> bool:
    val = os.environ.get(envvar, "")

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 35 Column: 1

                  pass


def bool_from_env(envvar: str) -> bool:
    val = os.environ.get(envvar, "")
    if not val or val.lower() in ("0", "false"):
        return False
    else:
        return True

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 37 Column: 5

              
def bool_from_env(envvar: str) -> bool:
    val = os.environ.get(envvar, "")
    if not val or val.lower() in ("0", "false"):
        return False
    else:
        return True



            

Reported by Pylint.

Missing class docstring
Error

Line: 43 Column: 1

                      return True


class ZipFile2(zipfile.ZipFile):
    # ZipFile and tarfile have slightly different APIs. Let's fix that.
    def add(self, name: str, arcname: str) -> None:
        return self.write(name, arcname)

    def __enter__(self) -> "ZipFile2":

            

Reported by Pylint.