The following issues were found

test/mitmproxy/test_optmanager.py
176 issues
Unable to import 'pytest'
Error

Line: 3 Column: 1

              import copy
import io
import pytest
import typing
import argparse

from mitmproxy import options
from mitmproxy import optmanager
from mitmproxy import exceptions

            

Reported by Pylint.

Unexpected keyword argument 'nonexistent' in constructor call
Error

Line: 92 Column: 9

                  assert o.one == 1

    with pytest.raises(TypeError):
        TO(nonexistent = "value")
    with pytest.raises(Exception, match="Unknown options"):
        o.nonexistent = "value"
    with pytest.raises(Exception, match="Unknown options"):
        o.update(nonexistent = "value")
    assert o.update_known(nonexistent = "value") == {"nonexistent": "value"}

            

Reported by Pylint.

Access to a protected member _options of a client class
Error

Line: 74 Column: 24

              def test_required_int():
    o = TO()
    with pytest.raises(exceptions.OptionsError):
        o.parse_setval(o._options["required_int"], None, None)


def test_deepcopy():
    o = TD()
    copy.deepcopy(o)

            

Reported by Pylint.

Attribute 'one' defined outside __init__
Error

Line: 88 Column: 5

              
    assert o.one is None
    assert o.two == 2
    o.one = 1
    assert o.one == 1

    with pytest.raises(TypeError):
        TO(nonexistent = "value")
    with pytest.raises(Exception, match="Unknown options"):

            

Reported by Pylint.

Attribute 'nonexistent' defined outside __init__
Error

Line: 94 Column: 9

                  with pytest.raises(TypeError):
        TO(nonexistent = "value")
    with pytest.raises(Exception, match="Unknown options"):
        o.nonexistent = "value"
    with pytest.raises(Exception, match="Unknown options"):
        o.update(nonexistent = "value")
    assert o.update_known(nonexistent = "value") == {"nonexistent": "value"}

    rec = []

            

Reported by Pylint.

Unused argument 'updated'
Error

Line: 101 Column: 19

              
    rec = []

    def sub(opts, updated):
        rec.append(copy.copy(opts))

    o.changed.connect(sub)

    o.one = 90

            

Reported by Pylint.

Attribute 'one' defined outside __init__
Error

Line: 106 Column: 5

              
    o.changed.connect(sub)

    o.one = 90
    assert len(rec) == 1
    assert rec[-1].one == 90

    o.update(one=3)
    assert len(rec) == 2

            

Reported by Pylint.

Attribute 'one' defined outside __init__
Error

Line: 163 Column: 5

                  assert len(o.changed.receivers) == 0

    o.subscribe(r, ["two"])
    o.one = 2
    assert not r.called
    o.two = 3
    assert r.called

    assert len(o.changed.receivers) == 1

            

Reported by Pylint.

Attribute 'two' defined outside __init__
Error

Line: 165 Column: 5

                  o.subscribe(r, ["two"])
    o.one = 2
    assert not r.called
    o.two = 3
    assert r.called

    assert len(o.changed.receivers) == 1
    del r
    o.two = 4

            

Reported by Pylint.

Attribute 'two' defined outside __init__
Error

Line: 170 Column: 5

              
    assert len(o.changed.receivers) == 1
    del r
    o.two = 4
    assert len(o.changed.receivers) == 0

    class binder:
        def __init__(self):
            self.o = TO()

            

Reported by Pylint.

test/mitmproxy/proxy/layers/http/test_http2.py
166 issues
Unable to import 'h2.settings'
Error

Line: 3 Column: 1

              from typing import List, Tuple

import h2.settings
import hpack
import hyperframe.frame
import pytest
from h2.errors import ErrorCodes

from mitmproxy.connection import ConnectionState, Server

            

Reported by Pylint.

Unable to import 'hpack'
Error

Line: 4 Column: 1

              from typing import List, Tuple

import h2.settings
import hpack
import hyperframe.frame
import pytest
from h2.errors import ErrorCodes

from mitmproxy.connection import ConnectionState, Server

            

Reported by Pylint.

Unable to import 'hyperframe.frame'
Error

Line: 5 Column: 1

              
import h2.settings
import hpack
import hyperframe.frame
import pytest
from h2.errors import ErrorCodes

from mitmproxy.connection import ConnectionState, Server
from mitmproxy.flow import Error

            

Reported by Pylint.

Unable to import 'pytest'
Error

Line: 6 Column: 1

              import h2.settings
import hpack
import hyperframe.frame
import pytest
from h2.errors import ErrorCodes

from mitmproxy.connection import ConnectionState, Server
from mitmproxy.flow import Error
from mitmproxy.http import HTTPFlow, Headers, Request

            

Reported by Pylint.

Unable to import 'h2.errors'
Error

Line: 7 Column: 1

              import hpack
import hyperframe.frame
import pytest
from h2.errors import ErrorCodes

from mitmproxy.connection import ConnectionState, Server
from mitmproxy.flow import Error
from mitmproxy.http import HTTPFlow, Headers, Request
from mitmproxy.net.http import status_codes

            

Reported by Pylint.

Unable to import 'mitmproxy.connection'
Error

Line: 9 Column: 1

              import pytest
from h2.errors import ErrorCodes

from mitmproxy.connection import ConnectionState, Server
from mitmproxy.flow import Error
from mitmproxy.http import HTTPFlow, Headers, Request
from mitmproxy.net.http import status_codes
from mitmproxy.proxy.commands import CloseConnection, OpenConnection, SendData
from mitmproxy.proxy.context import Context

            

Reported by Pylint.

Unable to import 'mitmproxy.flow'
Error

Line: 10 Column: 1

              from h2.errors import ErrorCodes

from mitmproxy.connection import ConnectionState, Server
from mitmproxy.flow import Error
from mitmproxy.http import HTTPFlow, Headers, Request
from mitmproxy.net.http import status_codes
from mitmproxy.proxy.commands import CloseConnection, OpenConnection, SendData
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.events import ConnectionClosed, DataReceived

            

Reported by Pylint.

Unable to import 'mitmproxy.http'
Error

Line: 11 Column: 1

              
from mitmproxy.connection import ConnectionState, Server
from mitmproxy.flow import Error
from mitmproxy.http import HTTPFlow, Headers, Request
from mitmproxy.net.http import status_codes
from mitmproxy.proxy.commands import CloseConnection, OpenConnection, SendData
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.events import ConnectionClosed, DataReceived
from mitmproxy.proxy.layers import http

            

Reported by Pylint.

Unable to import 'mitmproxy.net.http'
Error

Line: 12 Column: 1

              from mitmproxy.connection import ConnectionState, Server
from mitmproxy.flow import Error
from mitmproxy.http import HTTPFlow, Headers, Request
from mitmproxy.net.http import status_codes
from mitmproxy.proxy.commands import CloseConnection, OpenConnection, SendData
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.events import ConnectionClosed, DataReceived
from mitmproxy.proxy.layers import http
from mitmproxy.proxy.layers.http import HTTPMode

            

Reported by Pylint.

Unable to import 'mitmproxy.proxy.commands'
Error

Line: 13 Column: 1

              from mitmproxy.flow import Error
from mitmproxy.http import HTTPFlow, Headers, Request
from mitmproxy.net.http import status_codes
from mitmproxy.proxy.commands import CloseConnection, OpenConnection, SendData
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.events import ConnectionClosed, DataReceived
from mitmproxy.proxy.layers import http
from mitmproxy.proxy.layers.http import HTTPMode
from mitmproxy.proxy.layers.http._http2 import Http2Client, split_pseudo_headers

            

Reported by Pylint.

examples/contrib/test_xss_scanner.py
157 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest
import requests
from examples.complex import xss_scanner as xss
from mitmproxy.test import tflow, tutils


class TestXSSScanner():
    def test_get_XSS_info(self):
        # First type of exploit: <script>PAYLOAD</script>

            

Reported by Pylint.

Unable to import 'examples.complex'
Error

Line: 3 Column: 1

              import pytest
import requests
from examples.complex import xss_scanner as xss
from mitmproxy.test import tflow, tutils


class TestXSSScanner():
    def test_get_XSS_info(self):
        # First type of exploit: <script>PAYLOAD</script>

            

Reported by Pylint.

Unable to import 'mitmproxy.test'
Error

Line: 4 Column: 1

              import pytest
import requests
from examples.complex import xss_scanner as xss
from mitmproxy.test import tflow, tutils


class TestXSSScanner():
    def test_get_XSS_info(self):
        # First type of exploit: <script>PAYLOAD</script>

            

Reported by Pylint.

Method has no argument
Error

Line: 243 Column: 5

                      assert text == expected_text
        assert xss.paths_to_text("""<html></html>""", "STRING") == []

    def mocked_requests_vuln(*args, headers=None, cookies=None):
        class MockResponse:
            def __init__(self, html, headers=None, cookies=None):
                self.text = html
        return MockResponse("<html>%s</html>" % xss.FULL_PAYLOAD)


            

Reported by Pylint.

Method has no argument
Error

Line: 249 Column: 5

                              self.text = html
        return MockResponse("<html>%s</html>" % xss.FULL_PAYLOAD)

    def mocked_requests_invuln(*args, headers=None, cookies=None):
        class MockResponse:
            def __init__(self, html, headers=None, cookies=None):
                self.text = html
        return MockResponse("<html></html>")


            

Reported by Pylint.

Unused argument 'headers'
Error

Line: 243 Column: 37

                      assert text == expected_text
        assert xss.paths_to_text("""<html></html>""", "STRING") == []

    def mocked_requests_vuln(*args, headers=None, cookies=None):
        class MockResponse:
            def __init__(self, html, headers=None, cookies=None):
                self.text = html
        return MockResponse("<html>%s</html>" % xss.FULL_PAYLOAD)


            

Reported by Pylint.

Unused argument 'cookies'
Error

Line: 243 Column: 51

                      assert text == expected_text
        assert xss.paths_to_text("""<html></html>""", "STRING") == []

    def mocked_requests_vuln(*args, headers=None, cookies=None):
        class MockResponse:
            def __init__(self, html, headers=None, cookies=None):
                self.text = html
        return MockResponse("<html>%s</html>" % xss.FULL_PAYLOAD)


            

Reported by Pylint.

Unused argument 'cookies'
Error

Line: 245 Column: 52

              
    def mocked_requests_vuln(*args, headers=None, cookies=None):
        class MockResponse:
            def __init__(self, html, headers=None, cookies=None):
                self.text = html
        return MockResponse("<html>%s</html>" % xss.FULL_PAYLOAD)

    def mocked_requests_invuln(*args, headers=None, cookies=None):
        class MockResponse:

            

Reported by Pylint.

Unused argument 'headers'
Error

Line: 245 Column: 38

              
    def mocked_requests_vuln(*args, headers=None, cookies=None):
        class MockResponse:
            def __init__(self, html, headers=None, cookies=None):
                self.text = html
        return MockResponse("<html>%s</html>" % xss.FULL_PAYLOAD)

    def mocked_requests_invuln(*args, headers=None, cookies=None):
        class MockResponse:

            

Reported by Pylint.

Unused argument 'cookies'
Error

Line: 249 Column: 53

                              self.text = html
        return MockResponse("<html>%s</html>" % xss.FULL_PAYLOAD)

    def mocked_requests_invuln(*args, headers=None, cookies=None):
        class MockResponse:
            def __init__(self, html, headers=None, cookies=None):
                self.text = html
        return MockResponse("<html></html>")


            

Reported by Pylint.

test/mitmproxy/test_types.py
157 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest
import os
import typing
import contextlib

import mitmproxy.exceptions
import mitmproxy.types
from mitmproxy.test import taddons
from mitmproxy.test import tflow

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 13 Column: 1

              from mitmproxy import command
from mitmproxy import flow

from . import test_command


@contextlib.contextmanager
def chdir(path: str):
    old_dir = os.getcwd()

            

Reported by Pylint.

Access to a protected member _BoolType of a client class
Error

Line: 26 Column: 13

              
def test_bool():
    with taddons.context() as tctx:
        b = mitmproxy.types._BoolType()
        assert b.completion(tctx.master.commands, bool, "b") == ["false", "true"]
        assert b.parse(tctx.master.commands, bool, "true") is True
        assert b.parse(tctx.master.commands, bool, "false") is False
        assert b.is_valid(tctx.master.commands, bool, True) is True
        assert b.is_valid(tctx.master.commands, bool, "foo") is False

            

Reported by Pylint.

Access to a protected member _StrType of a client class
Error

Line: 38 Column: 13

              
def test_str():
    with taddons.context() as tctx:
        b = mitmproxy.types._StrType()
        assert b.is_valid(tctx.master.commands, str, "foo") is True
        assert b.is_valid(tctx.master.commands, str, 1) is False
        assert b.completion(tctx.master.commands, str, "") == []
        assert b.parse(tctx.master.commands, str, "foo") == "foo"
        assert b.parse(tctx.master.commands, str, r"foo\nbar") == "foo\nbar"

            

Reported by Pylint.

Access to a protected member _BytesType of a client class
Error

Line: 51 Column: 13

              
def test_bytes():
    with taddons.context() as tctx:
        b = mitmproxy.types._BytesType()
        assert b.is_valid(tctx.master.commands, bytes, b"foo") is True
        assert b.is_valid(tctx.master.commands, bytes, 1) is False
        assert b.completion(tctx.master.commands, bytes, "") == []
        assert b.parse(tctx.master.commands, bytes, "foo") == b"foo"
        with pytest.raises(mitmproxy.exceptions.TypeError):

            

Reported by Pylint.

Access to a protected member _UnknownType of a client class
Error

Line: 62 Column: 13

              
def test_unknown():
    with taddons.context() as tctx:
        b = mitmproxy.types._UnknownType()
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Unknown, "foo") is False
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Unknown, 1) is False
        assert b.completion(tctx.master.commands, mitmproxy.types.Unknown, "") == []
        assert b.parse(tctx.master.commands, mitmproxy.types.Unknown, "foo") == "foo"


            

Reported by Pylint.

Access to a protected member _IntType of a client class
Error

Line: 71 Column: 13

              
def test_int():
    with taddons.context() as tctx:
        b = mitmproxy.types._IntType()
        assert b.is_valid(tctx.master.commands, int, "foo") is False
        assert b.is_valid(tctx.master.commands, int, 1) is True
        assert b.completion(tctx.master.commands, int, "b") == []
        assert b.parse(tctx.master.commands, int, "1") == 1
        assert b.parse(tctx.master.commands, int, "999") == 999

            

Reported by Pylint.

Access to a protected member _PathType of a client class
Error

Line: 83 Column: 13

              
def test_path(tdata, monkeypatch):
    with taddons.context() as tctx:
        b = mitmproxy.types._PathType()
        assert b.parse(tctx.master.commands, mitmproxy.types.Path, "/foo") == "/foo"
        assert b.parse(tctx.master.commands, mitmproxy.types.Path, "/bar") == "/bar"
        monkeypatch.setenv("HOME", "/home/test")
        monkeypatch.setenv("USERPROFILE", "/home/test")
        assert b.parse(tctx.master.commands, mitmproxy.types.Path, "~/mitm") == "/home/test/mitm"

            

Reported by Pylint.

Access to a protected member _CmdType of a client class
Error

Line: 115 Column: 13

              def test_cmd():
    with taddons.context() as tctx:
        tctx.master.addons.add(test_command.TAddon())
        b = mitmproxy.types._CmdType()
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Cmd, "foo") is False
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Cmd, "cmd1") is True
        assert b.parse(tctx.master.commands, mitmproxy.types.Cmd, "cmd1") == "cmd1"
        with pytest.raises(mitmproxy.exceptions.TypeError):
            assert b.parse(tctx.master.commands, mitmproxy.types.Cmd, "foo")

            

Reported by Pylint.

Access to a protected member _CutSpecType of a client class
Error

Line: 128 Column: 13

              
def test_cutspec():
    with taddons.context() as tctx:
        b = mitmproxy.types._CutSpecType()
        b.parse(tctx.master.commands, mitmproxy.types.CutSpec, "foo,bar") == ["foo", "bar"]
        assert b.is_valid(tctx.master.commands, mitmproxy.types.CutSpec, 1) is False
        assert b.is_valid(tctx.master.commands, mitmproxy.types.CutSpec, "foo") is False
        assert b.is_valid(tctx.master.commands, mitmproxy.types.CutSpec, "request.path") is True


            

Reported by Pylint.

test/mitmproxy/addons/test_export.py
152 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              import os
import shlex

import pytest
import pyperclip

from mitmproxy import exceptions
from mitmproxy.addons import export  # heh
from mitmproxy.test import tflow

            

Reported by Pylint.

Unable to import 'pyperclip'
Error

Line: 5 Column: 1

              import shlex

import pytest
import pyperclip

from mitmproxy import exceptions
from mitmproxy.addons import export  # heh
from mitmproxy.test import tflow
from mitmproxy.test import tutils

            

Reported by Pylint.

Redefining name 'export_curl' from outer scope (line 57)
Error

Line: 65 Column: 24

              

class TestExportCurlCommand:
    def test_get(self, export_curl, get_request):
        result = """curl -H 'header: qvalue' 'http://address:22/path?a=foo&a=bar&b=baz'"""
        assert export_curl(get_request) == result

    def test_post(self, export_curl, post_request):
        post_request.request.content = b'nobinarysupport'

            

Reported by Pylint.

Redefining name 'get_request' from outer scope (line 16)
Error

Line: 65 Column: 37

              

class TestExportCurlCommand:
    def test_get(self, export_curl, get_request):
        result = """curl -H 'header: qvalue' 'http://address:22/path?a=foo&a=bar&b=baz'"""
        assert export_curl(get_request) == result

    def test_post(self, export_curl, post_request):
        post_request.request.content = b'nobinarysupport'

            

Reported by Pylint.

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

Line: 69 Column: 38

                      result = """curl -H 'header: qvalue' 'http://address:22/path?a=foo&a=bar&b=baz'"""
        assert export_curl(get_request) == result

    def test_post(self, export_curl, post_request):
        post_request.request.content = b'nobinarysupport'
        result = "curl -X POST http://address:22/path -d nobinarysupport"
        assert export_curl(post_request) == result

    def test_fails_with_binary_data(self, export_curl, post_request):

            

Reported by Pylint.

Redefining name 'export_curl' from outer scope (line 57)
Error

Line: 69 Column: 25

                      result = """curl -H 'header: qvalue' 'http://address:22/path?a=foo&a=bar&b=baz'"""
        assert export_curl(get_request) == result

    def test_post(self, export_curl, post_request):
        post_request.request.content = b'nobinarysupport'
        result = "curl -X POST http://address:22/path -d nobinarysupport"
        assert export_curl(post_request) == result

    def test_fails_with_binary_data(self, export_curl, post_request):

            

Reported by Pylint.

Redefining name 'export_curl' from outer scope (line 57)
Error

Line: 74 Column: 43

                      result = "curl -X POST http://address:22/path -d nobinarysupport"
        assert export_curl(post_request) == result

    def test_fails_with_binary_data(self, export_curl, post_request):
        # shlex.quote doesn't support a bytes object
        # see https://github.com/python/cpython/pull/10871
        post_request.request.headers["Content-Type"] = "application/json; charset=utf-8"
        with pytest.raises(exceptions.CommandError):
            export_curl(post_request)

            

Reported by Pylint.

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

Line: 74 Column: 56

                      result = "curl -X POST http://address:22/path -d nobinarysupport"
        assert export_curl(post_request) == result

    def test_fails_with_binary_data(self, export_curl, post_request):
        # shlex.quote doesn't support a bytes object
        # see https://github.com/python/cpython/pull/10871
        post_request.request.headers["Content-Type"] = "application/json; charset=utf-8"
        with pytest.raises(exceptions.CommandError):
            export_curl(post_request)

            

Reported by Pylint.

Redefining name 'patch_request' from outer scope (line 41)
Error

Line: 81 Column: 39

                      with pytest.raises(exceptions.CommandError):
            export_curl(post_request)

    def test_patch(self, export_curl, patch_request):
        result = """curl -H 'header: qvalue' -X PATCH 'http://address:22/path?query=param' -d content"""
        assert export_curl(patch_request) == result

    def test_tcp(self, export_curl, tcp_flow):
        with pytest.raises(exceptions.CommandError):

            

Reported by Pylint.

Redefining name 'export_curl' from outer scope (line 57)
Error

Line: 81 Column: 26

                      with pytest.raises(exceptions.CommandError):
            export_curl(post_request)

    def test_patch(self, export_curl, patch_request):
        result = """curl -H 'header: qvalue' -X PATCH 'http://address:22/path?query=param' -d content"""
        assert export_curl(patch_request) == result

    def test_tcp(self, export_curl, tcp_flow):
        with pytest.raises(exceptions.CommandError):

            

Reported by Pylint.

test/mitmproxy/test_certs.py
150 issues
Unable to import 'pytest'
Error

Line: 6 Column: 1

              from cryptography import x509
from cryptography.x509 import NameOID

import pytest

from mitmproxy import certs
from ..conftest import skip_windows



            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 9 Column: 1

              import pytest

from mitmproxy import certs
from ..conftest import skip_windows


# class TestDNTree:
#     def test_simple(self):
#         d = certs.DNTree()

            

Reported by Pylint.

Redefining name 'tstore' from outer scope (line 43)
Error

Line: 58 Column: 42

              
        assert ca.default_ca.serial == ca2.default_ca.serial

    def test_create_no_common_name(self, tstore):
        assert tstore.get_cert(None, []).cert.cn is None

    def test_chain_file(self, tdata, tmp_path):
        cert = Path(tdata.path("mitmproxy/data/confdir/mitmproxy-ca.pem")).read_bytes()
        (tmp_path / "mitmproxy-ca.pem").write_bytes(cert)

            

Reported by Pylint.

Redefining name 'tstore' from outer scope (line 43)
Error

Line: 71 Column: 25

                      ca = certs.CertStore.from_store(tmp_path, "mitmproxy", 2048)
        assert ca.default_chain_file == (tmp_path / "mitmproxy-ca.pem")

    def test_sans(self, tstore):
        c1 = tstore.get_cert("foo.com", ["*.bar.com"])
        tstore.get_cert("foo.bar.com", [])
        # assert c1 == c2
        c3 = tstore.get_cert("bar.com", [])
        assert not c1 == c3

            

Reported by Pylint.

Redefining name 'tstore' from outer scope (line 43)
Error

Line: 78 Column: 32

                      c3 = tstore.get_cert("bar.com", [])
        assert not c1 == c3

    def test_sans_change(self, tstore):
        tstore.get_cert("foo.com", ["*.bar.com"])
        entry = tstore.get_cert("foo.bar.com", ["*.baz.com"])
        assert "*.baz.com" in entry.cert.altnames

    def test_expire(self, tstore):

            

Reported by Pylint.

Redefining name 'tstore' from outer scope (line 43)
Error

Line: 83 Column: 27

                      entry = tstore.get_cert("foo.bar.com", ["*.baz.com"])
        assert "*.baz.com" in entry.cert.altnames

    def test_expire(self, tstore):
        tstore.STORE_CAP = 3
        tstore.get_cert("one.com", [])
        tstore.get_cert("two.com", [])
        tstore.get_cert("three.com", [])


            

Reported by Pylint.

TODO: How do we actually attempt to read that file as another user?
Error

Line: 129 Column: 3

                      filename = str(tmpdir.join("secret"))
        with certs.CertStore.umask_secret(), open(filename, "wb"):
            pass
        # TODO: How do we actually attempt to read that file as another user?
        assert os.stat(filename).st_mode & 0o77 == 0


class TestDummyCert:


            

Reported by Pylint.

Redefining name 'tstore' from outer scope (line 43)
Error

Line: 135 Column: 28

              
class TestDummyCert:

    def test_with_ca(self, tstore):
        r = certs.dummy_cert(
            tstore.default_privatekey,
            tstore.default_ca._cert,
            "foo.com",
            ["one.com", "two.com", "*.three.com", "127.0.0.1"],

            

Reported by Pylint.

Access to a protected member _cert of a client class
Error

Line: 138 Column: 13

                  def test_with_ca(self, tstore):
        r = certs.dummy_cert(
            tstore.default_privatekey,
            tstore.default_ca._cert,
            "foo.com",
            ["one.com", "two.com", "*.three.com", "127.0.0.1"],
            "Foo Ltd."
        )
        assert r.cn == "foo.com"

            

Reported by Pylint.

Access to a protected member _cert of a client class
Error

Line: 149 Column: 13

              
        r = certs.dummy_cert(
            tstore.default_privatekey,
            tstore.default_ca._cert,
            None,
            [],
            None
        )
        assert r.cn is None

            

Reported by Pylint.

test/mitmproxy/test_command.py
142 issues
Unable to import 'pytest'
Error

Line: 5 Column: 1

              import io
import typing

import pytest

import mitmproxy.types
from mitmproxy import command
from mitmproxy import exceptions
from mitmproxy import flow

            

Reported by Pylint.

Unused argument 'foo'
Error

Line: 22 Column: 20

                      return "ret " + foo

    @command.command("cmd2")
    def cmd2(self, foo: str) -> str:
        return 99

    @command.command("cmd3")
    def cmd3(self, foo: int) -> int:
        return foo

            

Reported by Pylint.

Unused argument 'a'
Error

Line: 30 Column: 20

                      return foo

    @command.command("cmd4")
    def cmd4(self, a: int, b: str, c: mitmproxy.types.Path) -> str:
        return "ok"

    @command.command("subcommand")
    def subcommand(self, cmd: mitmproxy.types.Cmd, *args: mitmproxy.types.CmdArgs) -> str:
        return "ok"

            

Reported by Pylint.

Unused argument 'b'
Error

Line: 30 Column: 28

                      return foo

    @command.command("cmd4")
    def cmd4(self, a: int, b: str, c: mitmproxy.types.Path) -> str:
        return "ok"

    @command.command("subcommand")
    def subcommand(self, cmd: mitmproxy.types.Cmd, *args: mitmproxy.types.CmdArgs) -> str:
        return "ok"

            

Reported by Pylint.

Unused argument 'c'
Error

Line: 30 Column: 36

                      return foo

    @command.command("cmd4")
    def cmd4(self, a: int, b: str, c: mitmproxy.types.Path) -> str:
        return "ok"

    @command.command("subcommand")
    def subcommand(self, cmd: mitmproxy.types.Cmd, *args: mitmproxy.types.CmdArgs) -> str:
        return "ok"

            

Reported by Pylint.

Unused argument 'cmd'
Error

Line: 34 Column: 26

                      return "ok"

    @command.command("subcommand")
    def subcommand(self, cmd: mitmproxy.types.Cmd, *args: mitmproxy.types.CmdArgs) -> str:
        return "ok"

    @command.command("empty")
    def empty(self) -> None:
        pass

            

Reported by Pylint.

Unused argument 'args'
Error

Line: 34 Column: 1

                      return "ok"

    @command.command("subcommand")
    def subcommand(self, cmd: mitmproxy.types.Cmd, *args: mitmproxy.types.CmdArgs) -> str:
        return "ok"

    @command.command("empty")
    def empty(self) -> None:
        pass

            

Reported by Pylint.

Unused argument 'one'
Error

Line: 42 Column: 23

                      pass

    @command.command("varargs")
    def varargs(self, one: str, *var: str) -> typing.Sequence[str]:
        return list(var)

    def choices(self) -> typing.Sequence[str]:
        return ["one", "two", "three"]


            

Reported by Pylint.

Unused argument 'arg'
Error

Line: 49 Column: 22

                      return ["one", "two", "three"]

    @command.argument("arg", type=mitmproxy.types.Choice("choices"))
    def choose(self, arg: str) -> typing.Sequence[str]:
        return ["one", "two", "three"]

    @command.command("path")
    def path(self, arg: mitmproxy.types.Path) -> None:
        pass

            

Reported by Pylint.

Access to a protected member _empty of a client class
Error

Line: 445 Column: 26

                  assert command.typename(mitmproxy.types.Cmd) == "cmd"

    with pytest.raises(exceptions.CommandError, match="missing type annotation"):
        command.typename(inspect._empty)
    with pytest.raises(exceptions.CommandError, match="unsupported type"):
        command.typename(None)


class DummyConsole:

            

Reported by Pylint.

test/mitmproxy/tools/web/test_app.py
136 issues
Unable to import 'pytest'
Error

Line: 7 Column: 1

              import os
from unittest import mock

import pytest

import tornado.testing  # noqa
from tornado import httpclient  # noqa
from tornado import websocket  # noqa


            

Reported by Pylint.

Unable to import 'tornado.testing'
Error

Line: 9 Column: 1

              
import pytest

import tornado.testing  # noqa
from tornado import httpclient  # noqa
from tornado import websocket  # noqa

from mitmproxy import options  # noqa
from mitmproxy.test import tflow  # noqa

            

Reported by Pylint.

Unable to import 'tornado'
Error

Line: 10 Column: 1

              import pytest

import tornado.testing  # noqa
from tornado import httpclient  # noqa
from tornado import websocket  # noqa

from mitmproxy import options  # noqa
from mitmproxy.test import tflow  # noqa
from mitmproxy.tools.web import app  # noqa

            

Reported by Pylint.

Unable to import 'tornado'
Error

Line: 11 Column: 1

              
import tornado.testing  # noqa
from tornado import httpclient  # noqa
from tornado import websocket  # noqa

from mitmproxy import options  # noqa
from mitmproxy.test import tflow  # noqa
from mitmproxy.tools.web import app  # noqa
from mitmproxy.tools.web import master as webmaster  # noqa

            

Reported by Pylint.

Attribute 'master' defined outside __init__
Error

Line: 49 Column: 9

                      m.view.add([f])
        m.view.add([tflow.tflow(err=True)])
        m.log.info("test log")
        self.master = m
        self.view = m.view
        self.events = m.events
        webapp = app.Application(m, None)
        webapp.settings["xsrf_cookies"] = False
        return webapp

            

Reported by Pylint.

Attribute 'view' defined outside __init__
Error

Line: 50 Column: 9

                      m.view.add([tflow.tflow(err=True)])
        m.log.info("test log")
        self.master = m
        self.view = m.view
        self.events = m.events
        webapp = app.Application(m, None)
        webapp.settings["xsrf_cookies"] = False
        return webapp


            

Reported by Pylint.

Attribute 'events' defined outside __init__
Error

Line: 51 Column: 9

                      m.log.info("test log")
        self.master = m
        self.view = m.view
        self.events = m.events
        webapp = app.Application(m, None)
        webapp.settings["xsrf_cookies"] = False
        return webapp

    def fetch(self, *args, **kwargs) -> httpclient.HTTPResponse:

            

Reported by Pylint.

Access to a protected member _backup of a client class
Error

Line: 186 Column: 20

                      f.backup()
        f.request.method = "PATCH"
        self.fetch("/flows/42/revert", method="POST")
        assert not f._backup

    def test_flow_replay(self):
        with mock.patch("mitmproxy.command.CommandManager.call") as replay_call:
            assert self.fetch("/flows/42/replay", method="POST").code == 200
            assert replay_call.called

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import asyncio
import json as _json
import logging
import os
from unittest import mock

import pytest

import tornado.testing  # noqa

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 20 Column: 1

              

@pytest.fixture(scope="module")
def no_tornado_logging():
    logging.getLogger('tornado.access').disabled = True
    logging.getLogger('tornado.application').disabled = True
    logging.getLogger('tornado.general').disabled = True
    yield
    logging.getLogger('tornado.access').disabled = False

            

Reported by Pylint.

mitmproxy/proxy/layers/http/__init__.py
134 issues
Unable to import 'wsproto.handshake'
Error

Line: 7 Column: 1

              from dataclasses import dataclass
from typing import DefaultDict, Dict, List, Optional, Tuple, Union

import wsproto.handshake
from mitmproxy import flow, http
from mitmproxy.connection import Connection, Server
from mitmproxy.net import server_spec
from mitmproxy.net.http import status_codes, url
from mitmproxy.net.http.http1 import expected_http_body_size

            

Reported by Pylint.

Unable to import '__init__._base'
Error

Line: 19 Column: 1

              from mitmproxy.proxy.utils import expect
from mitmproxy.utils import human
from mitmproxy.websocket import WebSocketData
from ._base import HttpCommand, HttpConnection, ReceiveHttp, StreamId
from ._events import HttpEvent, RequestData, RequestEndOfMessage, RequestHeaders, RequestProtocolError, RequestTrailers, \
    ResponseData, ResponseEndOfMessage, ResponseHeaders, ResponseProtocolError, ResponseTrailers
from ._hooks import HttpConnectHook, HttpErrorHook, HttpRequestHeadersHook, HttpRequestHook, HttpResponseHeadersHook, \
    HttpResponseHook, HttpConnectUpstreamHook  # noqa
from ._http1 import Http1Client, Http1Connection, Http1Server

            

Reported by Pylint.

Unable to import '__init__._events'
Error

Line: 20 Column: 1

              from mitmproxy.utils import human
from mitmproxy.websocket import WebSocketData
from ._base import HttpCommand, HttpConnection, ReceiveHttp, StreamId
from ._events import HttpEvent, RequestData, RequestEndOfMessage, RequestHeaders, RequestProtocolError, RequestTrailers, \
    ResponseData, ResponseEndOfMessage, ResponseHeaders, ResponseProtocolError, ResponseTrailers
from ._hooks import HttpConnectHook, HttpErrorHook, HttpRequestHeadersHook, HttpRequestHook, HttpResponseHeadersHook, \
    HttpResponseHook, HttpConnectUpstreamHook  # noqa
from ._http1 import Http1Client, Http1Connection, Http1Server
from ._http2 import Http2Client, Http2Server

            

Reported by Pylint.

Unable to import '__init__._hooks'
Error

Line: 22 Column: 1

              from ._base import HttpCommand, HttpConnection, ReceiveHttp, StreamId
from ._events import HttpEvent, RequestData, RequestEndOfMessage, RequestHeaders, RequestProtocolError, RequestTrailers, \
    ResponseData, ResponseEndOfMessage, ResponseHeaders, ResponseProtocolError, ResponseTrailers
from ._hooks import HttpConnectHook, HttpErrorHook, HttpRequestHeadersHook, HttpRequestHook, HttpResponseHeadersHook, \
    HttpResponseHook, HttpConnectUpstreamHook  # noqa
from ._http1 import Http1Client, Http1Connection, Http1Server
from ._http2 import Http2Client, Http2Server
from ...context import Context


            

Reported by Pylint.

Unable to import '__init__._http1'
Error

Line: 24 Column: 1

                  ResponseData, ResponseEndOfMessage, ResponseHeaders, ResponseProtocolError, ResponseTrailers
from ._hooks import HttpConnectHook, HttpErrorHook, HttpRequestHeadersHook, HttpRequestHook, HttpResponseHeadersHook, \
    HttpResponseHook, HttpConnectUpstreamHook  # noqa
from ._http1 import Http1Client, Http1Connection, Http1Server
from ._http2 import Http2Client, Http2Server
from ...context import Context


class HTTPMode(enum.Enum):

            

Reported by Pylint.

Unable to import '__init__._http2'
Error

Line: 25 Column: 1

              from ._hooks import HttpConnectHook, HttpErrorHook, HttpRequestHeadersHook, HttpRequestHook, HttpResponseHeadersHook, \
    HttpResponseHook, HttpConnectUpstreamHook  # noqa
from ._http1 import Http1Client, Http1Connection, Http1Server
from ._http2 import Http2Client, Http2Server
from ...context import Context


class HTTPMode(enum.Enum):
    regular = 1

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 26 Column: 1

                  HttpResponseHook, HttpConnectUpstreamHook  # noqa
from ._http1 import Http1Client, Http1Connection, Http1Server
from ._http2 import Http2Client, Http2Server
from ...context import Context


class HTTPMode(enum.Enum):
    regular = 1
    transparent = 2

            

Reported by Pylint.

Using an f-string that does not have any interpolated variables
Error

Line: 40 Column: 13

                      return f"Invalid request scheme: {request.scheme}"
    if mode is HTTPMode.transparent and request.method == "CONNECT":
        return (
            f"mitmproxy received an HTTP CONNECT request even though it is not running in regular/upstream mode. "
            f"This usually indicates a misconfiguration, please see the mitmproxy mode documentation for details."
        )
    return None



            

Reported by Pylint.

Comparing against a callable, did you omit the parenthesis?
Error

Line: 118 Column: 12

                      self.stream_id = stream_id

    def __repr__(self):
        if self._handle_event == self.passthrough:
            return f"HttpStream(id={self.stream_id}, passthrough)"
        else:
            return (
                f"HttpStream("
                f"id={self.stream_id}, "

            

Reported by Pylint.

Using an f-string that does not have any interpolated variables
Error

Line: 400 Column: 36

                          elif self.context.options.rawtcp:
                self.child_layer = tcp.TCPLayer(self.context)
            else:
                yield commands.Log(f"Sent HTTP 101 response, but no protocol is enabled to upgrade to.", "warn")
                yield commands.CloseConnection(self.context.client)
                self.client_state = self.server_state = self.state_errored
                return
            if self.debug:
                yield commands.Log(f"{self.debug}[http] upgrading to {self.child_layer}", "debug")

            

Reported by Pylint.

test/mitmproxy/addons/test_command_history.py
132 issues
Unable to import 'pytest'
Error

Line: 5 Column: 1

              from unittest.mock import patch
from pathlib import Path

import pytest

from mitmproxy.addons import command_history
from mitmproxy.test import taddons



            

Reported by Pylint.

Unused argument 'monkeypatch'
Error

Line: 160 Column: 39

                          ch.clear_history()

    @pytest.mark.asyncio
    async def test_clear_failed(self, monkeypatch):
        ch = command_history.CommandHistory()

        with taddons.context(ch) as tctx:
            tctx.options.confdir = '/non/existent/path/foobar1234/'


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os
from unittest.mock import patch
from pathlib import Path

import pytest

from mitmproxy.addons import command_history
from mitmproxy.test import taddons


            

Reported by Pylint.

Missing class docstring
Error

Line: 11 Column: 1

              from mitmproxy.test import taddons


class TestCommandHistory:
    def test_load_and_save(self, tmpdir):
        history_file = tmpdir.join('command_history')
        commands = ["cmd1", "cmd2", "cmd3"]
        with open(history_file, 'w') as f:
            f.write("\n".join(commands))

            

Reported by Pylint.

Method could be a function
Error

Line: 12 Column: 5

              

class TestCommandHistory:
    def test_load_and_save(self, tmpdir):
        history_file = tmpdir.join('command_history')
        commands = ["cmd1", "cmd2", "cmd3"]
        with open(history_file, 'w') as f:
            f.write("\n".join(commands))


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 12 Column: 5

              

class TestCommandHistory:
    def test_load_and_save(self, tmpdir):
        history_file = tmpdir.join('command_history')
        commands = ["cmd1", "cmd2", "cmd3"]
        with open(history_file, 'w') as f:
            f.write("\n".join(commands))


            

Reported by Pylint.

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

Line: 15 Column: 41

                  def test_load_and_save(self, tmpdir):
        history_file = tmpdir.join('command_history')
        commands = ["cmd1", "cmd2", "cmd3"]
        with open(history_file, 'w') as f:
            f.write("\n".join(commands))

        ch = command_history.CommandHistory()
        ch.VACUUM_SIZE = 4
        with taddons.context(ch) as tctx:

            

Reported by Pylint.

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

Line: 18 Column: 9

                      with open(history_file, 'w') as f:
            f.write("\n".join(commands))

        ch = command_history.CommandHistory()
        ch.VACUUM_SIZE = 4
        with taddons.context(ch) as tctx:
            tctx.options.confdir = str(tmpdir)
            assert ch.history == commands
            ch.add_command("cmd4")

            

Reported by Pylint.

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

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

                      ch.VACUUM_SIZE = 4
        with taddons.context(ch) as tctx:
            tctx.options.confdir = str(tmpdir)
            assert ch.history == commands
            ch.add_command("cmd4")
            ch.done()

        with open(history_file) as f:
            assert f.read() == "cmd3\ncmd4\n"

            

Reported by Bandit.

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

Line: 26 Column: 36

                          ch.add_command("cmd4")
            ch.done()

        with open(history_file) as f:
            assert f.read() == "cmd3\ncmd4\n"

    @pytest.mark.asyncio
    async def test_done_writing_failed(self):
        ch = command_history.CommandHistory()

            

Reported by Pylint.