Skip to content

Commit

Permalink
fix mypy annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
mhils committed May 26, 2017
1 parent 9f58b19 commit eb5f37a
Show file tree
Hide file tree
Showing 12 changed files with 47 additions and 50 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ sslkeylogfile.log
.python-version
coverage.xml
web/coverage/
.mypy_cache/
6 changes: 1 addition & 5 deletions examples/simple/custom_contentview.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@
The content view API is explained in the mitmproxy.contentviews module.
"""
from mitmproxy import contentviews
import typing


CVIEWSWAPCASE = typing.Tuple[str, typing.Iterable[typing.List[typing.Tuple[str, typing.AnyStr]]]]


class ViewSwapCase(contentviews.View):
Expand All @@ -17,7 +13,7 @@ class ViewSwapCase(contentviews.View):
prompt = ("swap case text", "z")
content_types = ["text/plain"]

def __call__(self, data: typing.AnyStr, **metadata) -> CVIEWSWAPCASE:
def __call__(self, data, **metadata) -> contentviews.TViewResult:
return "case-swapped text", contentviews.format_text(data.swapcase())


Expand Down
2 changes: 0 additions & 2 deletions examples/simple/io_read_dumpfile.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
#!/usr/bin/env python

# type: ignore
#
# Simple script showing how to read a mitmproxy dump file
#
Expand Down
10 changes: 5 additions & 5 deletions examples/simple/io_write_dumpfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@

class Writer:
def __init__(self, path: str) -> None:
if path == "-":
f = sys.stdout # type: typing.IO[typing.Any]
else:
f = open(path, "wb")
self.w = io.FlowWriter(f)
self.f = open(path, "wb") # type: typing.IO[bytes]
self.w = io.FlowWriter(self.f)

def response(self, flow: http.HTTPFlow) -> None:
if random.choice([True, False]):
self.w.add(flow)

def done(self):
self.f.close()


addons = [Writer(sys.argv[1])]
4 changes: 2 additions & 2 deletions mitmproxy/contentviews/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
auto, raw, hex, json, xml_html, html_outline, wbxml, javascript, css,
urlencoded, multipart, image, query, protobuf
)
from .base import View, VIEW_CUTOFF, KEY_MAX, format_text, format_dict
from .base import View, VIEW_CUTOFF, KEY_MAX, format_text, format_dict, TViewResult

views = [] # type: List[View]
content_types_map = {} # type: Dict[str, List[View]]
Expand Down Expand Up @@ -178,7 +178,7 @@ def get_content_view(viewmode: View, data: bytes, **metadata):
add(protobuf.ViewProtobuf())

__all__ = [
"View", "VIEW_CUTOFF", "KEY_MAX", "format_text", "format_dict",
"View", "VIEW_CUTOFF", "KEY_MAX", "format_text", "format_dict", "TViewResult",
"get", "get_by_shortcut", "add", "remove",
"get_content_view", "get_message_content_view",
]
26 changes: 15 additions & 11 deletions mitmproxy/contentviews/base.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
# Default view cutoff *in lines*

from typing import Iterable, AnyStr, List
from typing import Mapping
from typing import Tuple
import typing

VIEW_CUTOFF = 512

KEY_MAX = 30

TTextType = typing.Union[str, bytes] # FIXME: This should be either bytes or str ultimately.
TViewLine = typing.List[typing.Tuple[str, TTextType]]
TViewResult = typing.Tuple[str, typing.Iterator[TViewLine]]


class View:
name = None # type: str
prompt = None # type: Tuple[str,str]
content_types = [] # type: List[str]
prompt = None # type: typing.Tuple[str,str]
content_types = [] # type: typing.List[str]

def __call__(self, data: bytes, **metadata):
def __call__(self, data: bytes, **metadata) -> TViewResult:
"""
Transform raw data into human-readable output.
Expand All @@ -38,8 +39,8 @@ def __call__(self, data: bytes, **metadata):


def format_dict(
d: Mapping[AnyStr, AnyStr]
) -> Iterable[List[Tuple[str, AnyStr]]]:
d: typing.Mapping[TTextType, TTextType]
) -> typing.Iterator[TViewLine]:
"""
Helper function that transforms the given dictionary into a list of
("key", key )
Expand All @@ -49,15 +50,18 @@ def format_dict(
max_key_len = max(len(k) for k in d.keys())
max_key_len = min(max_key_len, KEY_MAX)
for key, value in d.items():
key += b":" if isinstance(key, bytes) else u":"
if isinstance(key, bytes):
key += b":"
else:
key += ":"
key = key.ljust(max_key_len + 2)
yield [
("header", key),
("text", value)
]


def format_text(text: AnyStr) -> Iterable[List[Tuple[str, AnyStr]]]:
def format_text(text: TTextType) -> typing.Iterator[TViewLine]:
"""
Helper function that transforms bytes into the view output format.
"""
Expand Down
2 changes: 1 addition & 1 deletion pathod/language/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def intermediate(self, settings): # pragma: no cover


class PauseAt(_Action):
unique_name = None # type: ignore
unique_name = None

def __init__(self, offset, seconds):
_Action.__init__(self, offset)
Expand Down
8 changes: 5 additions & 3 deletions pathod/language/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
from mitmproxy.utils import strutils
from mitmproxy.utils import human
import typing # noqa
from . import generators, exceptions
from . import generators
from . import exceptions
from . import message # noqa


class Settings:
Expand Down Expand Up @@ -375,7 +377,7 @@ def freeze(self, settings):


class Integer(_Component):
bounds = (None, None) # type: typing.Tuple[typing.Union[int, None], typing.Union[int , None]]
bounds = (None, None) # type: typing.Tuple[typing.Optional[int], typing.Optional[int]]
preamble = ""

def __init__(self, value):
Expand Down Expand Up @@ -545,7 +547,7 @@ class NestedMessage(Token):
A nested message, as an escaped string with a preamble.
"""
preamble = ""
nest_type = None # type: ignore
nest_type = None # type: typing.Optional[typing.Type[message.Message]]

def __init__(self, value):
Token.__init__(self)
Expand Down
4 changes: 3 additions & 1 deletion pathod/language/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ class Method(base.OptionsOrValue):


class _HeaderMixin:
unique_name = None # type: ignore
@property
def unique_name(self):
return None

def format_header(self, key, value):
return [key, b": ", value, b"\r\n"]
Expand Down
8 changes: 5 additions & 3 deletions pathod/language/http2.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import pyparsing as pp

from mitmproxy.net import http
from mitmproxy.net.http import user_agents, Headers
from . import base, message


"""
Normal HTTP requests:
<method>:<path>:<header>:<body>
Expand Down Expand Up @@ -41,7 +41,9 @@ def get_header(val, headers):


class _HeaderMixin:
unique_name = None # type: ignore
@property
def unique_name(self):
return None

def values(self, settings):
return (
Expand Down Expand Up @@ -146,7 +148,7 @@ class Times(base.Integer):


class Response(_HTTP2Message):
unique_name = None # type: ignore
unique_name = None
comps = (
Header,
Body,
Expand Down
24 changes: 8 additions & 16 deletions pathod/language/websockets.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import random
import string
import typing # noqa

import pyparsing as pp

import mitmproxy.net.websockets
from mitmproxy.utils import strutils
import pyparsing as pp
from . import base, generators, actions, message
import typing # noqa

NESTED_LEADER = b"pathod!"

Expand Down Expand Up @@ -74,7 +76,7 @@ class Times(base.Integer):
preamble = "x"


COMPONENTS = (
COMPONENTS = [
OpCode,
Length,
# Bit flags
Expand All @@ -89,14 +91,13 @@ class Times(base.Integer):
KeyNone,
Key,
Times,

Body,
RawBody,
)
]


class WebsocketFrame(message.Message):
components = COMPONENTS
components = COMPONENTS # type: typing.List[typing.Type[base._Component]]
logattrs = ["body"]
# Used for nested frames
unique_name = "body"
Expand Down Expand Up @@ -240,14 +241,5 @@ class NestedFrame(base.NestedMessage):
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):
components = typing.cast(COMP, COMPONENTS + (
NestedFrame,
))
components = COMPONENTS + [NestedFrame]
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@
'dev': [
"flake8>=3.2.1, <3.4",
"Flask>=0.10.1, <0.13",
"mypy>=0.501, <0.502",
"mypy>=0.501, <0.512",
"pytest-cov>=2.2.1, <3",
"pytest-faulthandler>=1.3.0, <2",
"pytest-timeout>=1.0.0, <2",
Expand Down

0 comments on commit eb5f37a

Please sign in to comment.