Merge pull request #2299 from iharsh234/mypy-pathod

Mypy Checking to pathod
This commit is contained in:
Aldo Cortesi 2017-05-02 12:17:57 +12:00 committed by GitHub
commit 8d29492960
13 changed files with 51 additions and 39 deletions

View File

@ -3,7 +3,10 @@ This example shows how one can add a custom contentview to mitmproxy.
The content view API is explained in the mitmproxy.contentviews module. The content view API is explained in the mitmproxy.contentviews module.
""" """
from mitmproxy import contentviews from mitmproxy import contentviews
from typing import Tuple, Iterable, AnyStr, List import typing
CVIEWSWAPCASE = typing.Tuple[str, typing.Iterable[typing.List[typing.Tuple[str, typing.AnyStr]]]]
class ViewSwapCase(contentviews.View): class ViewSwapCase(contentviews.View):
@ -14,7 +17,7 @@ class ViewSwapCase(contentviews.View):
prompt = ("swap case text", "z") prompt = ("swap case text", "z")
content_types = ["text/plain"] content_types = ["text/plain"]
def __call__(self, data: bytes, **metadata) -> Tuple[str, Iterable[List[Tuple[str, AnyStr]]]]: def __call__(self, data: typing.AnyStr, **metadata) -> CVIEWSWAPCASE:
return "case-swapped text", contentviews.format_text(data.swapcase()) return "case-swapped text", contentviews.format_text(data.swapcase())

View File

@ -1,8 +1,9 @@
#!/usr/bin/env python #!/usr/bin/env python
# type: ignore
# #
# Simple script showing how to read a mitmproxy dump file # Simple script showing how to read a mitmproxy dump file
# #
from mitmproxy import io from mitmproxy import io
from mitmproxy.exceptions import FlowReadException from mitmproxy.exceptions import FlowReadException
import pprint import pprint

View File

@ -8,12 +8,13 @@ to multiple files in parallel.
import random import random
import sys import sys
from mitmproxy import io, http from mitmproxy import io, http
import typing # noqa
class Writer: class Writer:
def __init__(self, path: str) -> None: def __init__(self, path: str) -> None:
if path == "-": if path == "-":
f = sys.stdout # type: io.TextIO f = sys.stdout # type: typing.IO[typing.Any]
else: else:
f = open(path, "wb") f = open(path, "wb")
self.w = io.FlowWriter(f) self.w = io.FlowWriter(f)

View File

@ -2,9 +2,7 @@ import abc
import copy import copy
import random import random
from functools import total_ordering from functools import total_ordering
import pyparsing as pp import pyparsing as pp
from . import base from . import base
@ -52,7 +50,7 @@ class _Action(base.Token):
class PauseAt(_Action): class PauseAt(_Action):
unique_name = None unique_name = None # type: ignore
def __init__(self, offset, seconds): def __init__(self, offset, seconds):
_Action.__init__(self, offset) _Action.__init__(self, offset)
@ -103,7 +101,7 @@ class DisconnectAt(_Action):
class InjectAt(_Action): class InjectAt(_Action):
unique_name = None unique_name = None # type: ignore
def __init__(self, offset, value): def __init__(self, offset, value):
_Action.__init__(self, offset) _Action.__init__(self, offset)

View File

@ -3,10 +3,9 @@ import os
import abc import abc
import functools import functools
import pyparsing as pp import pyparsing as pp
from mitmproxy.utils import strutils from mitmproxy.utils import strutils
from mitmproxy.utils import human from mitmproxy.utils import human
import typing # noqa
from . import generators, exceptions from . import generators, exceptions
@ -84,7 +83,7 @@ class Token:
return None return None
@property @property
def unique_name(self): def unique_name(self) -> typing.Optional[str]:
""" """
Controls uniqueness constraints for tokens. No two tokens with the Controls uniqueness constraints for tokens. No two tokens with the
same name will be allowed. If no uniquness should be applied, this same name will be allowed. If no uniquness should be applied, this
@ -334,7 +333,7 @@ class OptionsOrValue(_Component):
Can be any of a specified set of options, or a value specifier. Can be any of a specified set of options, or a value specifier.
""" """
preamble = "" preamble = ""
options = [] options = [] # type: typing.List[str]
def __init__(self, value): def __init__(self, value):
# If it's a string, we were passed one of the options, so we lower-case # If it's a string, we were passed one of the options, so we lower-case
@ -376,7 +375,7 @@ class OptionsOrValue(_Component):
class Integer(_Component): class Integer(_Component):
bounds = (None, None) bounds = (None, None) # type: typing.Tuple[typing.Union[int, None], typing.Union[int , None]]
preamble = "" preamble = ""
def __init__(self, value): def __init__(self, value):
@ -442,7 +441,7 @@ class FixedLengthValue(Value):
A value component lead by an optional preamble. A value component lead by an optional preamble.
""" """
preamble = "" preamble = ""
length = None length = None # type: typing.Optional[int]
def __init__(self, value): def __init__(self, value):
Value.__init__(self, value) Value.__init__(self, value)
@ -511,7 +510,7 @@ class IntField(_Component):
""" """
An integer field, where values can optionally specified by name. An integer field, where values can optionally specified by name.
""" """
names = {} names = {} # type: typing.Dict[str, int]
max = 16 max = 16
preamble = "" preamble = ""
@ -546,7 +545,7 @@ class NestedMessage(Token):
A nested message, as an escaped string with a preamble. A nested message, as an escaped string with a preamble.
""" """
preamble = "" preamble = ""
nest_type = None nest_type = None # type: ignore
def __init__(self, value): def __init__(self, value):
Token.__init__(self) Token.__init__(self)

View File

@ -54,7 +54,7 @@ class Method(base.OptionsOrValue):
class _HeaderMixin: class _HeaderMixin:
unique_name = None unique_name = None # type: ignore
def format_header(self, key, value): def format_header(self, key, value):
return [key, b": ", value, b"\r\n"] return [key, b": ", value, b"\r\n"]
@ -143,7 +143,7 @@ class _HTTPMessage(message.Message):
class Response(_HTTPMessage): class Response(_HTTPMessage):
unique_name = None unique_name = None # type: ignore
comps = ( comps = (
Header, Header,
ShortcutContentType, ShortcutContentType,

View File

@ -1,9 +1,9 @@
import pyparsing as pp import pyparsing as pp
from mitmproxy.net import http from mitmproxy.net import http
from mitmproxy.net.http import user_agents, Headers from mitmproxy.net.http import user_agents, Headers
from . import base, message from . import base, message
""" """
Normal HTTP requests: Normal HTTP requests:
<method>:<path>:<header>:<body> <method>:<path>:<header>:<body>
@ -41,7 +41,7 @@ def get_header(val, headers):
class _HeaderMixin: class _HeaderMixin:
unique_name = None unique_name = None # type: ignore
def values(self, settings): def values(self, settings):
return ( return (
@ -146,7 +146,7 @@ class Times(base.Integer):
class Response(_HTTP2Message): class Response(_HTTP2Message):
unique_name = None unique_name = None # type: ignore
comps = ( comps = (
Header, Header,
Body, Body,

View File

@ -1,13 +1,14 @@
import abc import abc
from . import actions, exceptions from . import actions, exceptions
from mitmproxy.utils import strutils from mitmproxy.utils import strutils
import typing # noqa
LOG_TRUNCATE = 1024 LOG_TRUNCATE = 1024
class Message: class Message:
__metaclass__ = abc.ABCMeta __metaclass__ = abc.ABCMeta
logattrs = [] logattrs = [] # type: typing.List[str]
def __init__(self, tokens): def __init__(self, tokens):
track = set([]) track = set([])

View File

@ -4,6 +4,7 @@ import mitmproxy.net.websockets
from mitmproxy.utils import strutils from mitmproxy.utils import strutils
import pyparsing as pp import pyparsing as pp
from . import base, generators, actions, message from . import base, generators, actions, message
import typing # noqa
NESTED_LEADER = b"pathod!" NESTED_LEADER = b"pathod!"
@ -20,7 +21,7 @@ class OpCode(base.IntField):
"close": mitmproxy.net.websockets.OPCODE.CLOSE, "close": mitmproxy.net.websockets.OPCODE.CLOSE,
"ping": mitmproxy.net.websockets.OPCODE.PING, "ping": mitmproxy.net.websockets.OPCODE.PING,
"pong": mitmproxy.net.websockets.OPCODE.PONG, "pong": mitmproxy.net.websockets.OPCODE.PONG,
} } # type: typing.Dict[str, int]
max = 15 max = 15
preamble = "c" preamble = "c"
@ -239,7 +240,14 @@ class NestedFrame(base.NestedMessage):
nest_type = WebsocketFrame nest_type = WebsocketFrame
COMP = typing.Tuple[
typing.Type[OpCode], typing.Type[Length], typing.Type[Fin], typing.Type[RSV1], typing.Type[RSV2], typing.Type[RSV3], typing.Type[Mask],
typing.Type[actions.PauseAt], typing.Type[actions.DisconnectAt], typing.Type[actions.InjectAt], typing.Type[KeyNone], typing.Type[Key],
typing.Type[Times], typing.Type[Body], typing.Type[RawBody]
]
class WebsocketClientFrame(WebsocketFrame): class WebsocketClientFrame(WebsocketFrame):
components = COMPONENTS + ( components = typing.cast(COMP, COMPONENTS + (
NestedFrame, NestedFrame,
) ))

View File

@ -3,19 +3,17 @@ import logging
import os import os
import sys import sys
import threading import threading
from mitmproxy.net import tcp from mitmproxy.net import tcp
from mitmproxy import certs as mcerts from mitmproxy import certs as mcerts
from mitmproxy.net import websockets from mitmproxy.net import websockets
from mitmproxy import version from mitmproxy import version
import urllib import urllib
from mitmproxy import exceptions from mitmproxy import exceptions
from pathod import language from pathod import language
from pathod import utils from pathod import utils
from pathod import log from pathod import log
from pathod import protocols from pathod import protocols
import typing # noqa
DEFAULT_CERT_DOMAIN = b"pathod.net" DEFAULT_CERT_DOMAIN = b"pathod.net"
@ -71,7 +69,7 @@ class SSLOptions:
class PathodHandler(tcp.BaseHandler): class PathodHandler(tcp.BaseHandler):
wbufsize = 0 wbufsize = 0
sni = None sni = None # type: typing.Union[str, None, bool]
def __init__( def __init__(
self, self,

View File

@ -1,16 +1,16 @@
import io import io
import time import time
import queue import queue
from . import pathod from . import pathod
from mitmproxy.types import basethread from mitmproxy.types import basethread
import typing # noqa
class Daemon: class Daemon:
IFACE = "127.0.0.1" IFACE = "127.0.0.1"
def __init__(self, ssl=None, **daemonargs): def __init__(self, ssl=None, **daemonargs) -> None:
self.q = queue.Queue() self.q = queue.Queue() # type: queue.Queue
self.logfp = io.StringIO() self.logfp = io.StringIO()
daemonargs["logfp"] = self.logfp daemonargs["logfp"] = self.logfp
self.thread = _PaThread(self.IFACE, self.q, ssl, daemonargs) self.thread = _PaThread(self.IFACE, self.q, ssl, daemonargs)
@ -25,18 +25,18 @@ class Daemon:
def __enter__(self): def __enter__(self):
return self return self
def __exit__(self, type, value, traceback): def __exit__(self, type, value, traceback) -> bool:
self.logfp.truncate(0) self.logfp.truncate(0)
self.shutdown() self.shutdown()
return False return False
def p(self, spec): def p(self, spec: str) -> str:
""" """
Return a URL that will render the response in spec. Return a URL that will render the response in spec.
""" """
return "%s/p/%s" % (self.urlbase, spec) return "%s/p/%s" % (self.urlbase, spec)
def text_log(self): def text_log(self) -> str:
return self.logfp.getvalue() return self.logfp.getvalue()
def wait_for_silence(self, timeout=5): def wait_for_silence(self, timeout=5):
@ -62,7 +62,7 @@ class Daemon:
return None return None
return l[-1] return l[-1]
def log(self): def log(self) -> typing.List[typing.Dict]:
""" """
Return the log buffer as a list of dictionaries. Return the log buffer as a list of dictionaries.
""" """

View File

@ -1,6 +1,7 @@
import os import os
import sys import sys
from mitmproxy.utils import data as mdata from mitmproxy.utils import data as mdata
import typing # noqa
class MemBool: class MemBool:
@ -9,10 +10,10 @@ class MemBool:
Truth-checking with a memory, for use in chained if statements. Truth-checking with a memory, for use in chained if statements.
""" """
def __init__(self): def __init__(self) -> None:
self.v = None self.v = None # type: typing.Optional[bool]
def __call__(self, v): def __call__(self, v: bool) -> bool:
self.v = v self.v = v
return bool(v) return bool(v)

View File

@ -28,6 +28,8 @@ commands =
python3 test/filename_matching.py python3 test/filename_matching.py
rstcheck README.rst rstcheck README.rst
mypy --ignore-missing-imports ./mitmproxy mypy --ignore-missing-imports ./mitmproxy
mypy --ignore-missing-imports ./pathod
mypy --ignore-missing-imports --follow-imports=skip ./examples/simple/
[testenv:individual_coverage] [testenv:individual_coverage]
deps = deps =