Not Found
\r\n
HTTP Error 404. The requested resource is not found.
\r\n\r\n'
- ),
- b"",
-])
+@pytest.mark.parametrize(
+ "data",
+ [
+ # HEADERS
+ b"\x01\x1d\x00\x00\xd1\xc1\xd7P\x8a\x08\x9d\\\x0b\x81p\xdcx\x0f\x03_P\x88%\xb6P\xc3\xab\xbc\xda\xe0\xdd",
+ # broken HEADERS
+ b"\x01\x1d\x00\x00\xd1\xc1\xd7P\x8a\x08\x9d\\\x0b\x81p\xdcx\x0f\x03_P\x88%\xb6P\xc3\xab\xff\xff\xff\xff",
+ # headers + data
+ (
+ b"\x01@I\x00\x00\xdb_'\x93I|\xa5\x89\xd3M\x1fj\x12q\xd8\x82\xa6\x0bP\xb0\xd0C\x1b_M\x90\xd0bXt\x1eT\xad\x8f~\xfdp"
+ b"\xeb\xc8\xc0\x97\x07V\x96\xd0z\xbe\x94\x08\x94\xdcZ\xd4\x10\x04%\x02\xe5\xc6\xde\xb8\x17\x14\xc5\xa3\x7fT\x03315"
+ b'\x00A;\r\n<'
+ b'TITLE>Not Found\r\n\r\nNot Found
\r\n
HTTP Error 404. The requested resource is not found.
\r\n\r\n"
+ ),
+ b"",
+ ],
+)
def test_view_http3(data):
v = full_eval(http3.ViewHttp3())
- t = tflow.ttcpflow(messages=[
- TCPMessage(from_client=len(data) > 16, content=data)
- ])
+ t = tflow.ttcpflow(messages=[TCPMessage(from_client=len(data) > 16, content=data)])
t.metadata["quic_is_unidirectional"] = False
- assert (v(b"", flow=t, tcp_message=t.messages[0]))
+ assert v(b"", flow=t, tcp_message=t.messages[0])
-@pytest.mark.parametrize("data", [
- # SETTINGS
- b"\x00\x04\r\x06\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00\x07\x00",
- # unknown setting
- b"\x00\x04\r\x3f\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00\x07\x00",
- # out of bounds
- b"\x00\x04\r\x06\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00\x42\x00",
- # incomplete
- b"\x00\x04\r\x06\xff\xff\xff",
- # QPACK encoder stream
- b"\x02",
-])
+@pytest.mark.parametrize(
+ "data",
+ [
+ # SETTINGS
+ b"\x00\x04\r\x06\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00\x07\x00",
+ # unknown setting
+ b"\x00\x04\r\x3f\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00\x07\x00",
+ # out of bounds
+ b"\x00\x04\r\x06\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00\x42\x00",
+ # incomplete
+ b"\x00\x04\r\x06\xff\xff\xff",
+ # QPACK encoder stream
+ b"\x02",
+ ],
+)
def test_view_http3_unidirectional(data):
v = full_eval(http3.ViewHttp3())
- t = tflow.ttcpflow(messages=[
- TCPMessage(from_client=len(data) > 16, content=data)
- ])
+ t = tflow.ttcpflow(messages=[TCPMessage(from_client=len(data) > 16, content=data)])
t.metadata["quic_is_unidirectional"] = True
- assert (v(b"", flow=t, tcp_message=t.messages[0]))
+ assert v(b"", flow=t, tcp_message=t.messages[0])
def test_render_priority():
diff --git a/test/mitmproxy/contentviews/test_javascript.py b/test/mitmproxy/contentviews/test_javascript.py
index c050adee4..64647446d 100644
--- a/test/mitmproxy/contentviews/test_javascript.py
+++ b/test/mitmproxy/contentviews/test_javascript.py
@@ -1,7 +1,7 @@
import pytest
-from mitmproxy.contentviews import javascript
from . import full_eval
+from mitmproxy.contentviews import javascript
def test_view_javascript():
diff --git a/test/mitmproxy/contentviews/test_json.py b/test/mitmproxy/contentviews/test_json.py
index 5b3883060..9711a6465 100644
--- a/test/mitmproxy/contentviews/test_json.py
+++ b/test/mitmproxy/contentviews/test_json.py
@@ -1,8 +1,8 @@
from hypothesis import given
from hypothesis.strategies import binary
-from mitmproxy.contentviews import json
from . import full_eval
+from mitmproxy.contentviews import json
def test_parse_json():
@@ -18,31 +18,66 @@ def test_parse_json():
def test_format_json():
assert list(json.format_json({"data": ["str", 42, True, False, None, {}, []]}))
assert list(json.format_json({"string": "test"})) == [
- [('text', '{'), ('text', '')],
- [('text', ' '), ('Token_Name_Tag', '"string"'), ('text', ': '), ('Token_Literal_String', '"test"'), ('text', '')],
- [('text', ''), ('text', '}')]]
+ [("text", "{"), ("text", "")],
+ [
+ ("text", " "),
+ ("Token_Name_Tag", '"string"'),
+ ("text", ": "),
+ ("Token_Literal_String", '"test"'),
+ ("text", ""),
+ ],
+ [("text", ""), ("text", "}")],
+ ]
assert list(json.format_json({"num": 4})) == [
- [('text', '{'), ('text', '')],
- [('text', ' '), ('Token_Name_Tag', '"num"'), ('text', ': '), ('Token_Literal_Number', '4'), ('text', '')],
- [('text', ''), ('text', '}')]]
+ [("text", "{"), ("text", "")],
+ [
+ ("text", " "),
+ ("Token_Name_Tag", '"num"'),
+ ("text", ": "),
+ ("Token_Literal_Number", "4"),
+ ("text", ""),
+ ],
+ [("text", ""), ("text", "}")],
+ ]
assert list(json.format_json({"bool": True})) == [
- [('text', '{'), ('text', '')],
- [('text', ' '), ('Token_Name_Tag', '"bool"'), ('text', ': '), ('Token_Keyword_Constant', 'true'), ('text', '')],
- [('text', ''), ('text', '}')]]
+ [("text", "{"), ("text", "")],
+ [
+ ("text", " "),
+ ("Token_Name_Tag", '"bool"'),
+ ("text", ": "),
+ ("Token_Keyword_Constant", "true"),
+ ("text", ""),
+ ],
+ [("text", ""), ("text", "}")],
+ ]
assert list(json.format_json({"object": {"int": 1}})) == [
- [('text', '{'), ('text', '')],
- [('text', ' '), ('Token_Name_Tag', '"object"'), ('text', ': '), ('text', '{'), ('text', '')],
- [('text', ' '), ('Token_Name_Tag', '"int"'), ('text', ': '), ('Token_Literal_Number', '1'), ('text', '')],
- [('text', ' '), ('text', '}'), ('text', '')],
- [('text', ''), ('text', '}')]]
+ [("text", "{"), ("text", "")],
+ [
+ ("text", " "),
+ ("Token_Name_Tag", '"object"'),
+ ("text", ": "),
+ ("text", "{"),
+ ("text", ""),
+ ],
+ [
+ ("text", " "),
+ ("Token_Name_Tag", '"int"'),
+ ("text", ": "),
+ ("Token_Literal_Number", "1"),
+ ("text", ""),
+ ],
+ [("text", " "), ("text", "}"), ("text", "")],
+ [("text", ""), ("text", "}")],
+ ]
assert list(json.format_json({"list": ["string", 1, True]})) == [
- [('text', '{'), ('text', '')],
- [('text', ' '), ('Token_Name_Tag', '"list"'), ('text', ': '), ('text', '[')],
- [('Token_Literal_String', ' "string"'), ('text', ',')],
- [('Token_Literal_Number', ' 1'), ('text', ',')],
- [('Token_Keyword_Constant', ' true'), ('text', '')],
- [('text', ' '), ('text', ']'), ('text', '')],
- [('text', ''), ('text', '}')]]
+ [("text", "{"), ("text", "")],
+ [("text", " "), ("Token_Name_Tag", '"list"'), ("text", ": "), ("text", "[")],
+ [("Token_Literal_String", ' "string"'), ("text", ",")],
+ [("Token_Literal_Number", " 1"), ("text", ",")],
+ [("Token_Keyword_Constant", " true"), ("text", "")],
+ [("text", " "), ("text", "]"), ("text", "")],
+ [("text", ""), ("text", "}")],
+ ]
def test_view_json():
diff --git a/test/mitmproxy/contentviews/test_mqtt.py b/test/mitmproxy/contentviews/test_mqtt.py
index 7acc33541..87cc09d40 100644
--- a/test/mitmproxy/contentviews/test_mqtt.py
+++ b/test/mitmproxy/contentviews/test_mqtt.py
@@ -1,7 +1,7 @@
import pytest
-from mitmproxy.contentviews import mqtt
from . import full_eval
+from mitmproxy.contentviews import mqtt
@pytest.mark.parametrize(
@@ -9,8 +9,14 @@ from . import full_eval
[
pytest.param(b"\xC0\x00", "[PINGREQ]", id="PINGREQ"),
pytest.param(b"\xD0\x00", "[PINGRESP]", id="PINGRESP"),
- pytest.param(b"\x90\x00", "Packet type SUBACK is not supported yet!", id="SUBACK"),
- pytest.param(b"\xA0\x00", "Packet type UNSUBSCRIBE is not supported yet!", id="UNSUBSCRIBE"),
+ pytest.param(
+ b"\x90\x00", "Packet type SUBACK is not supported yet!", id="SUBACK"
+ ),
+ pytest.param(
+ b"\xA0\x00",
+ "Packet type UNSUBSCRIBE is not supported yet!",
+ id="UNSUBSCRIBE",
+ ),
pytest.param(
b"\x82\x31\x00\x03\x00\x2cxxxx/yy/zzzzzz/56:6F:5E:6A:01:05/messages/in\x01",
"[SUBSCRIBE] sent topic filters: 'xxxx/yy/zzzzzz/56:6F:5E:6A:01:05/messages/in'",
@@ -52,10 +58,7 @@ def test_view_mqtt(data, expected_text):
assert output == [[("text", expected_text)]]
-@pytest.mark.parametrize(
- "data",
- [b"\xC0\xFF\xFF\xFF\xFF"]
-)
+@pytest.mark.parametrize("data", [b"\xC0\xFF\xFF\xFF\xFF"])
def test_mqtt_malformed(data):
v = full_eval(mqtt.ViewMQTT())
with pytest.raises(Exception):
diff --git a/test/mitmproxy/contentviews/test_msgpack.py b/test/mitmproxy/contentviews/test_msgpack.py
index eeba8b2d1..65c8487f0 100644
--- a/test/mitmproxy/contentviews/test_msgpack.py
+++ b/test/mitmproxy/contentviews/test_msgpack.py
@@ -1,10 +1,9 @@
from hypothesis import given
from hypothesis.strategies import binary
-
from msgpack import packb
-from mitmproxy.contentviews import msgpack
from . import full_eval
+from mitmproxy.contentviews import msgpack
def msgpack_encode(content):
@@ -18,32 +17,86 @@ def test_parse_msgpack():
def test_format_msgpack():
- assert list(msgpack.format_msgpack({"string": "test", "int": 1, "float": 1.44, "bool": True})) == [
- [('text', '{')],
- [('text', ''), ('text', ' '), ('Token_Name_Tag', '"string"'), ('text', ': '), ('Token_Literal_String', '"test"'), ('text', ',')],
- [('text', ''), ('text', ' '), ('Token_Name_Tag', '"int"'), ('text', ': '), ('Token_Literal_Number', '1'), ('text', ',')],
- [('text', ''), ('text', ' '), ('Token_Name_Tag', '"float"'), ('text', ': '), ('Token_Literal_Number', '1.44'), ('text', ',')],
- [('text', ''), ('text', ' '), ('Token_Name_Tag', '"bool"'), ('text', ': '), ('Token_Keyword_Constant', 'True')],
- [('text', ''), ('text', '}')]
+ assert list(
+ msgpack.format_msgpack(
+ {"string": "test", "int": 1, "float": 1.44, "bool": True}
+ )
+ ) == [
+ [("text", "{")],
+ [
+ ("text", ""),
+ ("text", " "),
+ ("Token_Name_Tag", '"string"'),
+ ("text", ": "),
+ ("Token_Literal_String", '"test"'),
+ ("text", ","),
+ ],
+ [
+ ("text", ""),
+ ("text", " "),
+ ("Token_Name_Tag", '"int"'),
+ ("text", ": "),
+ ("Token_Literal_Number", "1"),
+ ("text", ","),
+ ],
+ [
+ ("text", ""),
+ ("text", " "),
+ ("Token_Name_Tag", '"float"'),
+ ("text", ": "),
+ ("Token_Literal_Number", "1.44"),
+ ("text", ","),
+ ],
+ [
+ ("text", ""),
+ ("text", " "),
+ ("Token_Name_Tag", '"bool"'),
+ ("text", ": "),
+ ("Token_Keyword_Constant", "True"),
+ ],
+ [("text", ""), ("text", "}")],
]
assert list(msgpack.format_msgpack({"object": {"key": "value"}, "list": [1]})) == [
- [('text', '{')],
- [('text', ''), ('text', ' '), ('Token_Name_Tag', '"object"'), ('text', ': '), ('text', '{')],
- [('text', ' '), ('text', ' '), ('Token_Name_Tag', '"key"'), ('text', ': '), ('Token_Literal_String', '"value"')],
- [('text', ' '), ('text', '}'), ('text', ',')],
- [('text', ''), ('text', ' '), ('Token_Name_Tag', '"list"'), ('text', ': '), ('text', '[')],
- [('text', ' '), ('text', ' '), ('Token_Literal_Number', '1')],
- [('text', ' '), ('text', ']')],
- [('text', ''), ('text', '}')]]
+ [("text", "{")],
+ [
+ ("text", ""),
+ ("text", " "),
+ ("Token_Name_Tag", '"object"'),
+ ("text", ": "),
+ ("text", "{"),
+ ],
+ [
+ ("text", " "),
+ ("text", " "),
+ ("Token_Name_Tag", '"key"'),
+ ("text", ": "),
+ ("Token_Literal_String", '"value"'),
+ ],
+ [("text", " "), ("text", "}"), ("text", ",")],
+ [
+ ("text", ""),
+ ("text", " "),
+ ("Token_Name_Tag", '"list"'),
+ ("text", ": "),
+ ("text", "["),
+ ],
+ [("text", " "), ("text", " "), ("Token_Literal_Number", "1")],
+ [("text", " "), ("text", "]")],
+ [("text", ""), ("text", "}")],
+ ]
- assert list(msgpack.format_msgpack('string')) == [[('Token_Literal_String', '"string"')]]
+ assert list(msgpack.format_msgpack("string")) == [
+ [("Token_Literal_String", '"string"')]
+ ]
- assert list(msgpack.format_msgpack(1.2)) == [[('Token_Literal_Number', '1.2')]]
+ assert list(msgpack.format_msgpack(1.2)) == [[("Token_Literal_Number", "1.2")]]
- assert list(msgpack.format_msgpack(True)) == [[('Token_Keyword_Constant', 'True')]]
+ assert list(msgpack.format_msgpack(True)) == [[("Token_Keyword_Constant", "True")]]
- assert list(msgpack.format_msgpack(b'\x01\x02\x03')) == [[('text', "b'\\x01\\x02\\x03'")]]
+ assert list(msgpack.format_msgpack(b"\x01\x02\x03")) == [
+ [("text", "b'\\x01\\x02\\x03'")]
+ ]
def test_view_msgpack():
diff --git a/test/mitmproxy/contentviews/test_multipart.py b/test/mitmproxy/contentviews/test_multipart.py
index da1f723e0..a748231d6 100644
--- a/test/mitmproxy/contentviews/test_multipart.py
+++ b/test/mitmproxy/contentviews/test_multipart.py
@@ -1,5 +1,5 @@
-from mitmproxy.contentviews import multipart
from . import full_eval
+from mitmproxy.contentviews import multipart
def test_view_multipart():
diff --git a/test/mitmproxy/contentviews/test_protobuf.py b/test/mitmproxy/contentviews/test_protobuf.py
index 5f8d84d2e..99d6768ed 100644
--- a/test/mitmproxy/contentviews/test_protobuf.py
+++ b/test/mitmproxy/contentviews/test_protobuf.py
@@ -1,7 +1,7 @@
import pytest
-from mitmproxy.contentviews import protobuf
from . import full_eval
+from mitmproxy.contentviews import protobuf
datadir = "mitmproxy/contentviews/test_protobuf_data/"
diff --git a/test/mitmproxy/contentviews/test_query.py b/test/mitmproxy/contentviews/test_query.py
index af47a02f8..b4b1408ef 100644
--- a/test/mitmproxy/contentviews/test_query.py
+++ b/test/mitmproxy/contentviews/test_query.py
@@ -1,6 +1,6 @@
+from . import full_eval
from mitmproxy.contentviews import query
from mitmproxy.test import tutils
-from . import full_eval
def test_view_query():
diff --git a/test/mitmproxy/contentviews/test_raw.py b/test/mitmproxy/contentviews/test_raw.py
index d9fa44f89..0cffcf869 100644
--- a/test/mitmproxy/contentviews/test_raw.py
+++ b/test/mitmproxy/contentviews/test_raw.py
@@ -1,5 +1,5 @@
-from mitmproxy.contentviews import raw
from . import full_eval
+from mitmproxy.contentviews import raw
def test_view_raw():
diff --git a/test/mitmproxy/contentviews/test_urlencoded.py b/test/mitmproxy/contentviews/test_urlencoded.py
index 84c33dfce..e6005c0c8 100644
--- a/test/mitmproxy/contentviews/test_urlencoded.py
+++ b/test/mitmproxy/contentviews/test_urlencoded.py
@@ -1,6 +1,6 @@
+from . import full_eval
from mitmproxy.contentviews import urlencoded
from mitmproxy.net.http import url
-from . import full_eval
def test_view_urlencoded():
diff --git a/test/mitmproxy/contentviews/test_wbxml.py b/test/mitmproxy/contentviews/test_wbxml.py
index e37f0da21..11f2886bf 100644
--- a/test/mitmproxy/contentviews/test_wbxml.py
+++ b/test/mitmproxy/contentviews/test_wbxml.py
@@ -1,5 +1,5 @@
-from mitmproxy.contentviews import wbxml
from . import full_eval
+from mitmproxy.contentviews import wbxml
datadir = "mitmproxy/contentviews/test_wbxml_data/"
diff --git a/test/mitmproxy/contentviews/test_xml_html.py b/test/mitmproxy/contentviews/test_xml_html.py
index 4bb007972..de2b8d59f 100644
--- a/test/mitmproxy/contentviews/test_xml_html.py
+++ b/test/mitmproxy/contentviews/test_xml_html.py
@@ -1,7 +1,7 @@
import pytest
-from mitmproxy.contentviews import xml_html
from . import full_eval
+from mitmproxy.contentviews import xml_html
datadir = "mitmproxy/contentviews/test_xml_html_data/"
diff --git a/test/mitmproxy/coretypes/test_bidi.py b/test/mitmproxy/coretypes/test_bidi.py
index 3bdad3c2c..b4cff33cb 100644
--- a/test/mitmproxy/coretypes/test_bidi.py
+++ b/test/mitmproxy/coretypes/test_bidi.py
@@ -1,4 +1,5 @@
import pytest
+
from mitmproxy.coretypes import bidi
diff --git a/test/mitmproxy/coretypes/test_serializable.py b/test/mitmproxy/coretypes/test_serializable.py
index 70980a625..06e10fc54 100644
--- a/test/mitmproxy/coretypes/test_serializable.py
+++ b/test/mitmproxy/coretypes/test_serializable.py
@@ -5,7 +5,8 @@ import dataclasses
import enum
from collections.abc import Mapping
from dataclasses import dataclass
-from typing import Literal, Optional
+from typing import Literal
+from typing import Optional
import pytest
@@ -108,16 +109,31 @@ class FrozenWrapper(SerializableDataclass):
class TestSerializableDataclass:
- @pytest.mark.parametrize("cls, state", [
- (Simple, {"x": 42, "y": 'foo'}),
- (Simple, {"x": 42, "y": None}),
- (SerializableChild, {"foo": {"x": 42, "y": "foo"}, "maybe_foo": None}),
- (SerializableChild, {"foo": {"x": 42, "y": "foo"}, "maybe_foo": {"x": 42, "y": "foo"}}),
- (Inheritance, {"x": 42, "y": "foo", "z": True}),
- (BuiltinChildren, {"a": [1, 2, 3], "b": {"foo": 42}, "c": (1, 2), "d": [{"x": 42, "y": "foo"}], "e": 1}),
- (BuiltinChildren, {"a": None, "b": None, "c": None, "d": [], "e": None}),
- (TLiteral, {"l": "foo"}),
- ])
+ @pytest.mark.parametrize(
+ "cls, state",
+ [
+ (Simple, {"x": 42, "y": "foo"}),
+ (Simple, {"x": 42, "y": None}),
+ (SerializableChild, {"foo": {"x": 42, "y": "foo"}, "maybe_foo": None}),
+ (
+ SerializableChild,
+ {"foo": {"x": 42, "y": "foo"}, "maybe_foo": {"x": 42, "y": "foo"}},
+ ),
+ (Inheritance, {"x": 42, "y": "foo", "z": True}),
+ (
+ BuiltinChildren,
+ {
+ "a": [1, 2, 3],
+ "b": {"foo": 42},
+ "c": (1, 2),
+ "d": [{"x": 42, "y": "foo"}],
+ "e": 1,
+ },
+ ),
+ (BuiltinChildren, {"a": None, "b": None, "c": None, "d": [], "e": None}),
+ (TLiteral, {"l": "foo"}),
+ ],
+ )
def test_roundtrip(self, cls, state):
a = cls.from_state(copy.deepcopy(state))
assert a.get_state() == state
@@ -142,7 +158,9 @@ class TestSerializableDataclass:
with pytest.raises(ValueError):
Simple.from_state({"x": 42, "y": 42})
with pytest.raises(ValueError):
- BuiltinChildren.from_state({"a": None, "b": None, "c": ("foo",), "d": [], "e": None})
+ BuiltinChildren.from_state(
+ {"a": None, "b": None, "c": ("foo",), "d": [], "e": None}
+ )
def test_invalid_key(self):
with pytest.raises(ValueError):
@@ -150,7 +168,15 @@ class TestSerializableDataclass:
def test_invalid_type_in_list(self):
with pytest.raises(ValueError, match="Invalid value for x"):
- BuiltinChildren.from_state({"a": None, "b": None, "c": None, "d": [{"x": "foo", "y": "foo"}], "e": None})
+ BuiltinChildren.from_state(
+ {
+ "a": None,
+ "b": None,
+ "c": None,
+ "d": [{"x": "foo", "y": "foo"}],
+ "e": None,
+ }
+ )
def test_unsupported_type(self):
with pytest.raises(TypeError):
@@ -162,8 +188,12 @@ class TestSerializableDataclass:
TLiteral.from_state({"l": "unknown"})
def test_peername(self):
- assert Addr.from_state({"peername": ("addr", 42)}).get_state() == {"peername": ("addr", 42)}
- assert Addr.from_state({"peername": ("addr", 42, 0, 0)}).get_state() == {"peername": ("addr", 42, 0, 0)}
+ assert Addr.from_state({"peername": ("addr", 42)}).get_state() == {
+ "peername": ("addr", 42)
+ }
+ assert Addr.from_state({"peername": ("addr", 42, 0, 0)}).get_state() == {
+ "peername": ("addr", 42, 0, 0)
+ }
def test_set_immutable(self):
w = FrozenWrapper(Frozen(42))
diff --git a/test/mitmproxy/data/addonscripts/concurrent_decorator.py b/test/mitmproxy/data/addonscripts/concurrent_decorator.py
index bf2628958..0af96c486 100644
--- a/test/mitmproxy/data/addonscripts/concurrent_decorator.py
+++ b/test/mitmproxy/data/addonscripts/concurrent_decorator.py
@@ -1,4 +1,5 @@
import time
+
from mitmproxy.script import concurrent
diff --git a/test/mitmproxy/data/addonscripts/concurrent_decorator_class.py b/test/mitmproxy/data/addonscripts/concurrent_decorator_class.py
index b4ef75292..e08ca0cb1 100644
--- a/test/mitmproxy/data/addonscripts/concurrent_decorator_class.py
+++ b/test/mitmproxy/data/addonscripts/concurrent_decorator_class.py
@@ -1,4 +1,5 @@
import time
+
from mitmproxy.script import concurrent
diff --git a/test/mitmproxy/io/test_compat.py b/test/mitmproxy/io/test_compat.py
index 85ba5a0ee..35b11d619 100644
--- a/test/mitmproxy/io/test_compat.py
+++ b/test/mitmproxy/io/test_compat.py
@@ -1,7 +1,7 @@
import pytest
-from mitmproxy import io
from mitmproxy import exceptions
+from mitmproxy import io
@pytest.mark.parametrize(
diff --git a/test/mitmproxy/io/test_io.py b/test/mitmproxy/io/test_io.py
index 9d7ad8080..73d067d95 100644
--- a/test/mitmproxy/io/test_io.py
+++ b/test/mitmproxy/io/test_io.py
@@ -1,11 +1,14 @@
import io
import pytest
-from hypothesis import example, given
+from hypothesis import example
+from hypothesis import given
from hypothesis.strategies import binary
-from mitmproxy import exceptions, version
-from mitmproxy.io import FlowReader, tnetstring
+from mitmproxy import exceptions
+from mitmproxy import version
+from mitmproxy.io import FlowReader
+from mitmproxy.io import tnetstring
class TestFlowReader:
diff --git a/test/mitmproxy/io/test_tnetstring.py b/test/mitmproxy/io/test_tnetstring.py
index ccda4cfb8..6ae50bc82 100644
--- a/test/mitmproxy/io/test_tnetstring.py
+++ b/test/mitmproxy/io/test_tnetstring.py
@@ -1,8 +1,8 @@
-import unittest
-import random
-import math
import io
+import math
+import random
import struct
+import unittest
from mitmproxy.io import tnetstring
diff --git a/test/mitmproxy/net/dns/test_domain_names.py b/test/mitmproxy/net/dns/test_domain_names.py
index 72e6e5391..5f1847b55 100644
--- a/test/mitmproxy/net/dns/test_domain_names.py
+++ b/test/mitmproxy/net/dns/test_domain_names.py
@@ -1,5 +1,6 @@
import re
import struct
+
import pytest
from mitmproxy.net.dns import domain_names
@@ -15,14 +16,11 @@ def test_unpack_from_with_compression():
domain_names.unpack_from_with_compression(
b"\x03www\xc0\x00", 0, domain_names.cache()
)
- assert (
- domain_names.unpack_from_with_compression(
- b"\xFF\xFF\xFF\x07example\x03org\x00\xFF\xFF\xFF\x03www\xc0\x03",
- 19,
- domain_names.cache(),
- )
- == ("www.example.org", 6)
- )
+ assert domain_names.unpack_from_with_compression(
+ b"\xFF\xFF\xFF\x07example\x03org\x00\xFF\xFF\xFF\x03www\xc0\x03",
+ 19,
+ domain_names.cache(),
+ ) == ("www.example.org", 6)
def test_unpack():
diff --git a/test/mitmproxy/net/http/http1/test_assemble.py b/test/mitmproxy/net/http/http1/test_assemble.py
index 5d17e1bfb..eb246cf19 100644
--- a/test/mitmproxy/net/http/http1/test_assemble.py
+++ b/test/mitmproxy/net/http/http1/test_assemble.py
@@ -1,17 +1,16 @@
import pytest
from mitmproxy.http import Headers
-from mitmproxy.net.http.http1.assemble import (
- assemble_request,
- assemble_request_head,
- assemble_response,
- assemble_response_head,
- _assemble_request_line,
- _assemble_request_headers,
- _assemble_response_headers,
- assemble_body,
-)
-from mitmproxy.test.tutils import treq, tresp
+from mitmproxy.net.http.http1.assemble import _assemble_request_headers
+from mitmproxy.net.http.http1.assemble import _assemble_request_line
+from mitmproxy.net.http.http1.assemble import _assemble_response_headers
+from mitmproxy.net.http.http1.assemble import assemble_body
+from mitmproxy.net.http.http1.assemble import assemble_request
+from mitmproxy.net.http.http1.assemble import assemble_request_head
+from mitmproxy.net.http.http1.assemble import assemble_response
+from mitmproxy.net.http.http1.assemble import assemble_response_head
+from mitmproxy.test.tutils import treq
+from mitmproxy.test.tutils import tresp
def test_assemble_request():
diff --git a/test/mitmproxy/net/http/http1/test_read.py b/test/mitmproxy/net/http/http1/test_read.py
index 3f48a672e..a9148e7ab 100644
--- a/test/mitmproxy/net/http/http1/test_read.py
+++ b/test/mitmproxy/net/http/http1/test_read.py
@@ -1,18 +1,17 @@
import pytest
from mitmproxy.http import Headers
-from mitmproxy.net.http.http1.read import (
- read_request_head,
- read_response_head,
- connection_close,
- expected_http_body_size,
- _read_request_line,
- _read_response_line,
- _read_headers,
- get_header_tokens,
- validate_headers,
-)
-from mitmproxy.test.tutils import treq, tresp
+from mitmproxy.net.http.http1.read import _read_headers
+from mitmproxy.net.http.http1.read import _read_request_line
+from mitmproxy.net.http.http1.read import _read_response_line
+from mitmproxy.net.http.http1.read import connection_close
+from mitmproxy.net.http.http1.read import expected_http_body_size
+from mitmproxy.net.http.http1.read import get_header_tokens
+from mitmproxy.net.http.http1.read import read_request_head
+from mitmproxy.net.http.http1.read import read_response_head
+from mitmproxy.net.http.http1.read import validate_headers
+from mitmproxy.test.tutils import treq
+from mitmproxy.test.tutils import tresp
def test_get_header_tokens():
diff --git a/test/mitmproxy/net/http/test_cookies.py b/test/mitmproxy/net/http/test_cookies.py
index 4b7f3dd65..be5a57c76 100644
--- a/test/mitmproxy/net/http/test_cookies.py
+++ b/test/mitmproxy/net/http/test_cookies.py
@@ -1,7 +1,8 @@
import time
-import pytest
from unittest import mock
+import pytest
+
from mitmproxy.net.http import cookies
diff --git a/test/mitmproxy/net/http/test_headers.py b/test/mitmproxy/net/http/test_headers.py
index b7dff51d9..473b930f8 100644
--- a/test/mitmproxy/net/http/test_headers.py
+++ b/test/mitmproxy/net/http/test_headers.py
@@ -1,6 +1,7 @@
import collections
-from mitmproxy.net.http.headers import parse_content_type, assemble_content_type
+from mitmproxy.net.http.headers import assemble_content_type
+from mitmproxy.net.http.headers import parse_content_type
def test_parse_content_type():
diff --git a/test/mitmproxy/net/test_encoding.py b/test/mitmproxy/net/test_encoding.py
index 9d155961b..640d318ae 100644
--- a/test/mitmproxy/net/test_encoding.py
+++ b/test/mitmproxy/net/test_encoding.py
@@ -1,4 +1,5 @@
from unittest import mock
+
import pytest
from mitmproxy.net import encoding
diff --git a/test/mitmproxy/net/test_tls.py b/test/mitmproxy/net/test_tls.py
index c4fb16062..9e2600348 100644
--- a/test/mitmproxy/net/test_tls.py
+++ b/test/mitmproxy/net/test_tls.py
@@ -1,6 +1,8 @@
from pathlib import Path
-from OpenSSL import SSL, crypto
+from OpenSSL import crypto
+from OpenSSL import SSL
+
from mitmproxy import certs
from mitmproxy.net import tls
@@ -58,7 +60,7 @@ def test_sslkeylogfile(tdata, monkeypatch):
try:
read.do_handshake()
except SSL.WantReadError:
- write.bio_write(read.bio_read(2 ** 16))
+ write.bio_write(read.bio_read(2**16))
else:
break
read, write = write, read
diff --git a/test/mitmproxy/net/test_udp.py b/test/mitmproxy/net/test_udp.py
index 29a848cd1..d52636529 100644
--- a/test/mitmproxy/net/test_udp.py
+++ b/test/mitmproxy/net/test_udp.py
@@ -1,8 +1,14 @@
import asyncio
from typing import Optional
+
import pytest
+
from mitmproxy.connection import Address
-from mitmproxy.net.udp import MAX_DATAGRAM_SIZE, DatagramReader, DatagramWriter, open_connection, start_server
+from mitmproxy.net.udp import DatagramReader
+from mitmproxy.net.udp import DatagramWriter
+from mitmproxy.net.udp import MAX_DATAGRAM_SIZE
+from mitmproxy.net.udp import open_connection
+from mitmproxy.net.udp import start_server
async def test_client_server():
@@ -13,7 +19,7 @@ async def test_client_server():
transport: asyncio.DatagramTransport,
data: bytes,
remote_addr: Address,
- local_addr: Address
+ local_addr: Address,
):
nonlocal server_reader, server_writer
if server_writer is None:
@@ -23,9 +29,14 @@ async def test_client_server():
server = await start_server(handle_datagram, "127.0.0.1", 0)
assert repr(server).startswith(" context.Context:
opts = options.Options()
Proxyserver().load(opts)
return context.Context(
- connection.Client(peername=("client", 1234), sockname=("127.0.0.1", 8080),
- timestamp_start=1605699329, state=connection.ConnectionState.OPEN),
- opts
+ connection.Client(
+ peername=("client", 1234),
+ sockname=("127.0.0.1", 8080),
+ timestamp_start=1605699329,
+ state=connection.ConnectionState.OPEN,
+ ),
+ opts,
)
diff --git a/test/mitmproxy/proxy/layers/http/hyper_h2_test_helpers.py b/test/mitmproxy/proxy/layers/http/hyper_h2_test_helpers.py
index d5f8e0182..9b1e2676d 100644
--- a/test/mitmproxy/proxy/layers/http/hyper_h2_test_helpers.py
+++ b/test/mitmproxy/proxy/layers/http/hyper_h2_test_helpers.py
@@ -1,6 +1,5 @@
# This file has been copied from https://github.com/python-hyper/hyper-h2/blob/master/test/helpers.py,
# MIT License
-
# -*- coding: utf-8 -*-
"""
helpers
@@ -9,19 +8,17 @@ helpers
This module contains helpers for the h2 tests.
"""
from hpack.hpack import Encoder
-from hyperframe.frame import (
- HeadersFrame,
- DataFrame,
- SettingsFrame,
- WindowUpdateFrame,
- PingFrame,
- GoAwayFrame,
- RstStreamFrame,
- PushPromiseFrame,
- PriorityFrame,
- ContinuationFrame,
- AltSvcFrame,
-)
+from hyperframe.frame import AltSvcFrame
+from hyperframe.frame import ContinuationFrame
+from hyperframe.frame import DataFrame
+from hyperframe.frame import GoAwayFrame
+from hyperframe.frame import HeadersFrame
+from hyperframe.frame import PingFrame
+from hyperframe.frame import PriorityFrame
+from hyperframe.frame import PushPromiseFrame
+from hyperframe.frame import RstStreamFrame
+from hyperframe.frame import SettingsFrame
+from hyperframe.frame import WindowUpdateFrame
SAMPLE_SETTINGS = {
SettingsFrame.HEADER_TABLE_SIZE: 4096,
diff --git a/test/mitmproxy/proxy/layers/http/test_http.py b/test/mitmproxy/proxy/layers/http/test_http.py
index 86ff6fc3a..0d8e638df 100644
--- a/test/mitmproxy/proxy/layers/http/test_http.py
+++ b/test/mitmproxy/proxy/layers/http/test_http.py
@@ -1,27 +1,34 @@
-from logging import WARNING
-
import gc
+from logging import WARNING
import pytest
-from mitmproxy.connection import ConnectionState, Server
-from mitmproxy.http import HTTPFlow, Response
+from mitmproxy.connection import ConnectionState
+from mitmproxy.connection import Server
+from mitmproxy.http import HTTPFlow
+from mitmproxy.http import Response
from mitmproxy.proxy import layer
-from mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData
-from mitmproxy.proxy.events import ConnectionClosed, DataReceived
-from mitmproxy.proxy.layers import TCPLayer, http, tls
+from mitmproxy.proxy.commands import CloseConnection
+from mitmproxy.proxy.commands import Log
+from mitmproxy.proxy.commands import OpenConnection
+from mitmproxy.proxy.commands import SendData
+from mitmproxy.proxy.events import ConnectionClosed
+from mitmproxy.proxy.events import DataReceived
+from mitmproxy.proxy.layers import http
+from mitmproxy.proxy.layers import TCPLayer
+from mitmproxy.proxy.layers import tls
from mitmproxy.proxy.layers.http import HTTPMode
-from mitmproxy.proxy.layers.tcp import TcpMessageInjected, TcpStartHook
+from mitmproxy.proxy.layers.tcp import TcpMessageInjected
+from mitmproxy.proxy.layers.tcp import TcpStartHook
from mitmproxy.proxy.layers.websocket import WebsocketStartHook
from mitmproxy.proxy.mode_specs import ProxyMode
-from mitmproxy.tcp import TCPFlow, TCPMessage
-from test.mitmproxy.proxy.tutils import (
- BytesMatching,
- Placeholder,
- Playbook,
- reply,
- reply_next_layer,
-)
+from mitmproxy.tcp import TCPFlow
+from mitmproxy.tcp import TCPMessage
+from test.mitmproxy.proxy.tutils import BytesMatching
+from test.mitmproxy.proxy.tutils import Placeholder
+from test.mitmproxy.proxy.tutils import Playbook
+from test.mitmproxy.proxy.tutils import reply
+from test.mitmproxy.proxy.tutils import reply_next_layer
def test_http_proxy(tctx):
@@ -744,7 +751,8 @@ def test_upstream_proxy(tctx, redirect, domain, scheme):
<< OpenConnection(server)
>> reply(None)
<< SendData(
- server, b"GET http://%s/ HTTP/1.1\r\nHost: %s\r\n\r\n" % (domain, domain),
+ server,
+ b"GET http://%s/ HTTP/1.1\r\nHost: %s\r\n\r\n" % (domain, domain),
)
)
@@ -799,7 +807,8 @@ def test_upstream_proxy(tctx, redirect, domain, scheme):
if redirect == "change-destination":
playbook << SendData(
server2,
- b"GET http://%s.test/two HTTP/1.1\r\nHost: %s\r\n\r\n" % (domain, domain),
+ b"GET http://%s.test/two HTTP/1.1\r\nHost: %s\r\n\r\n"
+ % (domain, domain),
)
else:
playbook << SendData(
@@ -808,7 +817,9 @@ def test_upstream_proxy(tctx, redirect, domain, scheme):
)
else:
if redirect == "change-destination":
- playbook << SendData(server2, b"CONNECT %s.test:443 HTTP/1.1\r\n\r\n" % domain)
+ playbook << SendData(
+ server2, b"CONNECT %s.test:443 HTTP/1.1\r\n\r\n" % domain
+ )
playbook >> DataReceived(
server2, b"HTTP/1.1 200 Connection established\r\n\r\n"
)
@@ -830,9 +841,7 @@ def test_upstream_proxy(tctx, redirect, domain, scheme):
assert flow().server_conn.address[0] == domain.decode("idna")
if redirect == "change-proxy":
- assert (
- server2().address == flow().server_conn.via[1] == ("other-proxy", 1234)
- )
+ assert server2().address == flow().server_conn.via[1] == ("other-proxy", 1234)
else:
assert server2().address == flow().server_conn.via[1] == ("proxy", 8080)
@@ -958,8 +967,12 @@ def test_http_proxy_without_empty_chunk_in_head_request(tctx):
<< OpenConnection(server)
>> reply(None)
<< SendData(server, b"HEAD / HTTP/1.1\r\n\r\n")
- >> DataReceived(server, b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
- << SendData(tctx.client, b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
+ >> DataReceived(
+ server, b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"
+ )
+ << SendData(
+ tctx.client, b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"
+ )
)
@@ -1658,7 +1671,7 @@ def test_drop_stream_with_paused_events(tctx):
<< http.HttpRequestHeadersHook(flow)
>> reply()
<< OpenConnection(server)
- >> reply('Connection killed: error')
+ >> reply("Connection killed: error")
<< http.HttpErrorHook(flow)
>> reply()
<< SendData(tctx.client, BytesMatching(b"502 Bad Gateway.+Connection killed"))
diff --git a/test/mitmproxy/proxy/layers/http/test_http1.py b/test/mitmproxy/proxy/layers/http/test_http1.py
index 05e84e1fc..160493ad1 100644
--- a/test/mitmproxy/proxy/layers/http/test_http1.py
+++ b/test/mitmproxy/proxy/layers/http/test_http1.py
@@ -3,18 +3,17 @@ import pytest
from mitmproxy import http
from mitmproxy.proxy.commands import SendData
from mitmproxy.proxy.events import DataReceived
-from mitmproxy.proxy.layers.http import (
- Http1Server,
- ReceiveHttp,
- RequestHeaders,
- RequestEndOfMessage,
- ResponseHeaders,
- ResponseEndOfMessage,
- RequestData,
- Http1Client,
- ResponseData,
-)
-from test.mitmproxy.proxy.tutils import Placeholder, Playbook
+from mitmproxy.proxy.layers.http import Http1Client
+from mitmproxy.proxy.layers.http import Http1Server
+from mitmproxy.proxy.layers.http import ReceiveHttp
+from mitmproxy.proxy.layers.http import RequestData
+from mitmproxy.proxy.layers.http import RequestEndOfMessage
+from mitmproxy.proxy.layers.http import RequestHeaders
+from mitmproxy.proxy.layers.http import ResponseData
+from mitmproxy.proxy.layers.http import ResponseEndOfMessage
+from mitmproxy.proxy.layers.http import ResponseHeaders
+from test.mitmproxy.proxy.tutils import Placeholder
+from test.mitmproxy.proxy.tutils import Playbook
class TestServer:
diff --git a/test/mitmproxy/proxy/layers/http/test_http2.py b/test/mitmproxy/proxy/layers/http/test_http2.py
index e28bf72f3..a6a5412d8 100644
--- a/test/mitmproxy/proxy/layers/http/test_http2.py
+++ b/test/mitmproxy/proxy/layers/http/test_http2.py
@@ -1,28 +1,34 @@
+import time
+
import h2.settings
import hpack
import hyperframe.frame
import pytest
-import time
from h2.errors import ErrorCodes
-from mitmproxy.connection import ConnectionState, Server
+from mitmproxy.connection import ConnectionState
+from mitmproxy.connection import Server
from mitmproxy.flow import Error
-from mitmproxy.http import HTTPFlow, Headers, Request
+from mitmproxy.http import Headers
+from mitmproxy.http import HTTPFlow
+from mitmproxy.http import Request
from mitmproxy.net.http import status_codes
-from mitmproxy.proxy.commands import (
- CloseConnection,
- Log,
- OpenConnection,
- SendData,
- RequestWakeup,
-)
+from mitmproxy.proxy.commands import CloseConnection
+from mitmproxy.proxy.commands import Log
+from mitmproxy.proxy.commands import OpenConnection
+from mitmproxy.proxy.commands import RequestWakeup
+from mitmproxy.proxy.commands import SendData
from mitmproxy.proxy.context import Context
-from mitmproxy.proxy.events import ConnectionClosed, DataReceived
+from mitmproxy.proxy.events import ConnectionClosed
+from mitmproxy.proxy.events import 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
+from mitmproxy.proxy.layers.http._http2 import Http2Client
+from mitmproxy.proxy.layers.http._http2 import split_pseudo_headers
from test.mitmproxy.proxy.layers.http.hyper_h2_test_helpers import FrameFactory
-from test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply
+from test.mitmproxy.proxy.tutils import Placeholder
+from test.mitmproxy.proxy.tutils import Playbook
+from test.mitmproxy.proxy.tutils import reply
example_request_headers = (
(b":method", b"GET"),
@@ -325,8 +331,7 @@ def test_long_response(tctx: Context, trailers):
<< http.HttpResponseHeadersHook(flow)
>> reply()
>> DataReceived(
- server,
- sff.build_data_frame(b"a" * 10000, flags=[]).serialize()
+ server, sff.build_data_frame(b"a" * 10000, flags=[]).serialize()
)
>> DataReceived(
server,
@@ -373,9 +378,7 @@ def test_long_response(tctx: Context, trailers):
playbook
>> DataReceived(
server,
- sff.build_data_frame(
- b'', flags=["END_STREAM"]
- ).serialize(),
+ sff.build_data_frame(b"", flags=["END_STREAM"]).serialize(),
)
)
(
@@ -412,10 +415,7 @@ def test_long_response(tctx: Context, trailers):
tctx.client,
cff.build_data_frame(b"a" * 1).serialize(),
)
- << SendData(
- tctx.client,
- cff.build_data_frame(b"a" * 4464).serialize()
- )
+ << SendData(tctx.client, cff.build_data_frame(b"a" * 4464).serialize())
<< SendData(
tctx.client,
cff.build_headers_frame(
@@ -430,15 +430,10 @@ def test_long_response(tctx: Context, trailers):
tctx.client,
cff.build_data_frame(b"a" * 1).serialize(),
)
+ << SendData(tctx.client, cff.build_data_frame(b"a" * 4464).serialize())
<< SendData(
tctx.client,
- cff.build_data_frame(b"a" * 4464).serialize()
- )
- << SendData(
- tctx.client,
- cff.build_data_frame(
- b"", flags=["END_STREAM"]
- ).serialize(),
+ cff.build_data_frame(b"", flags=["END_STREAM"]).serialize(),
)
)
assert flow().request.url == "http://example.com/"
diff --git a/test/mitmproxy/proxy/layers/http/test_http3.py b/test/mitmproxy/proxy/layers/http/test_http3.py
index eccdd7bf4..59ffb670a 100644
--- a/test/mitmproxy/proxy/layers/http/test_http3.py
+++ b/test/mitmproxy/proxy/layers/http/test_http3.py
@@ -1,26 +1,33 @@
import collections.abc
-from typing import Callable, Iterable, Optional
-import pytest
+from collections.abc import Iterable
+from typing import Callable
+from typing import Optional
+
import pylsqpack
-
+import pytest
from aioquic._buffer import Buffer
-from aioquic.h3.connection import (
- ErrorCode,
- FrameType,
- Headers as H3Headers,
- Setting,
- StreamType,
- encode_frame,
- encode_uint_var,
- encode_settings,
- parse_settings,
-)
+from aioquic.h3.connection import encode_frame
+from aioquic.h3.connection import encode_settings
+from aioquic.h3.connection import encode_uint_var
+from aioquic.h3.connection import ErrorCode
+from aioquic.h3.connection import FrameType
+from aioquic.h3.connection import Headers as H3Headers
+from aioquic.h3.connection import parse_settings
+from aioquic.h3.connection import Setting
+from aioquic.h3.connection import StreamType
-from mitmproxy import connection, version
+from mitmproxy import connection
+from mitmproxy import version
from mitmproxy.flow import Error
-from mitmproxy.http import Headers, HTTPFlow, Request
-from mitmproxy.proxy import commands, context, events, layers
-from mitmproxy.proxy.layers import http, quic
+from mitmproxy.http import Headers
+from mitmproxy.http import HTTPFlow
+from mitmproxy.http import Request
+from mitmproxy.proxy import commands
+from mitmproxy.proxy import context
+from mitmproxy.proxy import events
+from mitmproxy.proxy import layers
+from mitmproxy.proxy.layers import http
+from mitmproxy.proxy.layers import quic
from mitmproxy.proxy.layers.http._http3 import Http3Client
from test.mitmproxy.proxy import tutils
@@ -47,6 +54,7 @@ def decode_frame(frame_type: int, frame_data: bytes) -> bytes:
class CallbackPlaceholder(tutils._Placeholder[bytes]):
"""Data placeholder that invokes a callback once its bytes get set."""
+
def __init__(self, cb: Callable[[bytes], None]):
super().__init__(bytes)
self._cb = cb
@@ -59,6 +67,7 @@ class CallbackPlaceholder(tutils._Placeholder[bytes]):
class DelayedPlaceholder(tutils._Placeholder[bytes]):
"""Data placeholder that resolves its bytes when needed."""
+
def __init__(self, resolve: Callable[[], bytes]):
super().__init__(bytes)
self._resolve = resolve
@@ -71,6 +80,7 @@ class DelayedPlaceholder(tutils._Placeholder[bytes]):
class MultiPlaybook(tutils.Playbook):
"""Playbook that allows multiple events and commands to be registered at once."""
+
def __lshift__(self, c):
if isinstance(c, collections.abc.Iterable):
for c_i in c:
@@ -90,11 +100,8 @@ class MultiPlaybook(tutils.Playbook):
class FrameFactory:
"""Helper class for generating QUIC stream events and commands."""
- def __init__(
- self,
- conn: connection.Connection,
- is_client: bool
- ) -> None:
+
+ def __init__(self, conn: connection.Connection, is_client: bool) -> None:
self.conn = conn
self.is_client = is_client
self.decoder = pylsqpack.Decoder(
@@ -108,11 +115,7 @@ class FrameFactory:
self.local_stream_id: dict[StreamType, int] = {}
self.max_push_id: Optional[int] = None
- def get_default_stream_id(
- self,
- stream_type: StreamType,
- for_local: bool
- ) -> int:
+ def get_default_stream_id(self, stream_type: StreamType, for_local: bool) -> int:
if stream_type == StreamType.CONTROL:
stream_id = 2
elif stream_type == StreamType.QPACK_ENCODER:
@@ -132,9 +135,7 @@ class FrameFactory:
) -> quic.SendQuicStreamData:
assert stream_type not in self.peer_stream_id
if stream_id is None:
- stream_id = self.get_default_stream_id(
- stream_type, for_local=False
- )
+ stream_id = self.get_default_stream_id(stream_type, for_local=False)
self.peer_stream_id[stream_type] = stream_id
return quic.SendQuicStreamData(
connection=self.conn,
@@ -150,9 +151,7 @@ class FrameFactory:
) -> quic.QuicStreamDataReceived:
assert stream_type not in self.local_stream_id
if stream_id is None:
- stream_id = self.get_default_stream_id(
- stream_type, for_local=True
- )
+ stream_id = self.get_default_stream_id(stream_type, for_local=True)
self.local_stream_id[stream_type] = stream_id
return quic.QuicStreamDataReceived(
connection=self.conn,
@@ -185,10 +184,12 @@ class FrameFactory:
buf = Buffer(data=data)
assert buf.pull_uint_var() == FrameType.SETTINGS
settings = parse_settings(buf.pull_bytes(buf.pull_uint_var()))
- placeholder.setdefault(self.encoder.apply_settings(
- max_table_capacity=settings[Setting.QPACK_MAX_TABLE_CAPACITY],
- blocked_streams=settings[Setting.QPACK_BLOCKED_STREAMS],
- ))
+ placeholder.setdefault(
+ self.encoder.apply_settings(
+ max_table_capacity=settings[Setting.QPACK_MAX_TABLE_CAPACITY],
+ blocked_streams=settings[Setting.QPACK_BLOCKED_STREAMS],
+ )
+ )
return quic.SendQuicStreamData(
connection=self.conn,
@@ -368,10 +369,7 @@ class FrameFactory:
@property
def is_done(self) -> bool:
- return (
- self.encoder_placeholder is None
- and not self.decoder_placeholders
- )
+ return self.encoder_placeholder is None and not self.decoder_placeholders
@pytest.fixture
@@ -428,11 +426,14 @@ def test_invalid_header(tctx: context.Context):
playbook, cff = start_h3_client(tctx)
assert (
playbook
- >> cff.receive_headers([
- (b":method", b"CONNECT"),
- (b":path", b"/"),
- (b":authority", b"example.com"),
- ], end_stream=True)
+ >> cff.receive_headers(
+ [
+ (b":method", b"CONNECT"),
+ (b":path", b"/"),
+ (b":authority", b"example.com"),
+ ],
+ end_stream=True,
+ )
<< cff.send_decoder() # for receive_headers
<< quic.CloseQuicConnection(
tctx.client,
@@ -441,11 +442,14 @@ def test_invalid_header(tctx: context.Context):
reason_phrase="Invalid HTTP/3 request headers: Required pseudo header is missing: b':scheme'",
)
# ensure that once we close, we don't process messages anymore
- >> cff.receive_headers([
- (b":method", b"CONNECT"),
- (b":path", b"/"),
- (b":authority", b"example.com"),
- ], end_stream=True)
+ >> cff.receive_headers(
+ [
+ (b":method", b"CONNECT"),
+ (b":path", b"/"),
+ (b":authority", b"example.com"),
+ ],
+ end_stream=True,
+ )
)
@@ -621,10 +625,7 @@ def test_request_trailers(
>> tutils.reply(to=request)
<< sff.send_headers(example_request_trailers, end_stream=True)
)
- assert (
- playbook
- >> sff.receive_decoder() # for send_headers
- )
+ assert playbook >> sff.receive_decoder() # for send_headers
assert cff.is_done and sff.is_done
@@ -648,11 +649,13 @@ def test_upstream_error(tctx: context.Context):
>> tutils.reply("oops server <> error")
<< http.HttpErrorHook(flow)
>> tutils.reply()
- << cff.send_headers([
- (b":status", b"502"),
- (b'server', version.MITMPROXY.encode()),
- (b'content-type', b'text/html'),
- ])
+ << cff.send_headers(
+ [
+ (b":status", b"502"),
+ (b"server", version.MITMPROXY.encode()),
+ (b"content-type", b"text/html"),
+ ]
+ )
<< quic.SendQuicStreamData(
tctx.client,
stream_id=0,
@@ -670,9 +673,7 @@ def test_upstream_error(tctx: context.Context):
@pytest.mark.parametrize("stream", ["stream", ""])
@pytest.mark.parametrize("when", ["request", "response"])
@pytest.mark.parametrize("how", ["RST", "disconnect", "RST+disconnect"])
-def test_http3_client_aborts(
- tctx: context.Context, stream: str, when: str, how: str
-):
+def test_http3_client_aborts(tctx: context.Context, stream: str, when: str, how: str):
"""
Test handling of the case where a client aborts during request or response transmission.
@@ -698,12 +699,12 @@ def test_http3_client_aborts(
if stream and when == "request":
assert (
playbook
- >> tutils.reply(
- side_effect=enable_request_streaming, to=request_headers
- )
+ >> tutils.reply(side_effect=enable_request_streaming, to=request_headers)
<< commands.OpenConnection(server)
>> tutils.reply(None)
- << commands.SendData(server, b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n\r\n")
+ << commands.SendData(
+ server, b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n\r\n"
+ )
)
else:
assert playbook >> tutils.reply(to=request_headers)
@@ -716,7 +717,7 @@ def test_http3_client_aborts(
tctx.client,
error_code=ErrorCode.H3_REQUEST_CANCELLED,
frame_type=None,
- reason_phrase="peer closed connection"
+ reason_phrase="peer closed connection",
)
if stream:
@@ -729,7 +730,7 @@ def test_http3_client_aborts(
tctx.client,
error_code=ErrorCode.H3_NO_ERROR,
frame_type=None,
- reason_phrase="peer closed connection"
+ reason_phrase="peer closed connection",
)
assert playbook
assert (
@@ -746,17 +747,21 @@ def test_http3_client_aborts(
<< commands.OpenConnection(server)
>> tutils.reply(None)
<< commands.SendData(server, b"GET / HTTP/1.1\r\n" b"Host: example.com\r\n\r\n")
- >> events.DataReceived(server, b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\n123")
+ >> events.DataReceived(
+ server, b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\n123"
+ )
<< http.HttpResponseHeadersHook(flow)
)
if stream:
assert (
playbook
>> tutils.reply(side_effect=enable_response_streaming)
- << cff.send_headers([
- (b":status", b"200"),
- (b"content-length", b"6"),
- ])
+ << cff.send_headers(
+ [
+ (b":status", b"200"),
+ (b"content-length", b"6"),
+ ]
+ )
<< cff.send_data(b"123")
)
else:
@@ -769,7 +774,7 @@ def test_http3_client_aborts(
tctx.client,
error_code=ErrorCode.H3_REQUEST_CANCELLED,
frame_type=None,
- reason_phrase="peer closed connection"
+ reason_phrase="peer closed connection",
)
playbook << commands.CloseConnection(server)
@@ -782,7 +787,7 @@ def test_http3_client_aborts(
tctx.client,
error_code=ErrorCode.H3_REQUEST_CANCELLED,
frame_type=None,
- reason_phrase="peer closed connection"
+ reason_phrase="peer closed connection",
)
assert playbook
@@ -920,14 +925,10 @@ def test_stream_concurrency(tctx: context.Context):
assert (
playbook
# request client
- >> cff.receive_headers(
- headers1, stream_id=0, end_stream=True
- )
+ >> cff.receive_headers(headers1, stream_id=0, end_stream=True)
<< (request_header1 := http.HttpRequestHeadersHook(flow1))
<< cff.send_decoder() # for receive_headers
- >> cff.receive_headers(
- headers2, stream_id=4, end_stream=True
- )
+ >> cff.receive_headers(headers2, stream_id=4, end_stream=True)
<< (request_header2 := http.HttpRequestHeadersHook(flow2))
<< cff.send_decoder() # for receive_headers
>> tutils.reply(to=request_header1)
@@ -940,17 +941,13 @@ def test_stream_concurrency(tctx: context.Context):
<< commands.OpenConnection(server)
>> tutils.reply(None, side_effect=make_h3)
<< sff.send_init()
- << sff.send_headers(
- headers2, stream_id=0, end_stream=True
- )
+ << sff.send_headers(headers2, stream_id=0, end_stream=True)
>> sff.receive_init()
<< sff.send_encoder()
>> sff.receive_encoder()
>> sff.receive_decoder() # for send_headers
>> tutils.reply(to=request1)
- << sff.send_headers(
- headers1, stream_id=4, end_stream=True
- )
+ << sff.send_headers(headers1, stream_id=4, end_stream=True)
>> sff.receive_decoder() # for send_headers
)
assert cff.is_done and sff.is_done
@@ -964,23 +961,15 @@ def test_stream_concurrent_get_connection(tctx: context.Context):
sff = FrameFactory(server, is_client=False)
assert (
playbook
- >> cff.receive_headers(
- example_request_headers, stream_id=0, end_stream=True
- )
+ >> cff.receive_headers(example_request_headers, stream_id=0, end_stream=True)
<< cff.send_decoder() # for receive_headers
<< (o := commands.OpenConnection(server))
- >> cff.receive_headers(
- example_request_headers, stream_id=4, end_stream=True
- )
+ >> cff.receive_headers(example_request_headers, stream_id=4, end_stream=True)
<< cff.send_decoder() # for receive_headers
>> tutils.reply(None, to=o, side_effect=make_h3)
<< sff.send_init()
- << sff.send_headers(
- example_request_headers, stream_id=0, end_stream=True
- )
- << sff.send_headers(
- example_request_headers, stream_id=4, end_stream=True
- )
+ << sff.send_headers(example_request_headers, stream_id=0, end_stream=True)
+ << sff.send_headers(example_request_headers, stream_id=4, end_stream=True)
>> sff.receive_init()
<< sff.send_encoder()
>> sff.receive_encoder()
@@ -1007,14 +996,10 @@ def test_kill_stream(tctx: context.Context):
assert (
playbook
# request client
- >> cff.receive_headers(
- headers1, stream_id=0, end_stream=True
- )
+ >> cff.receive_headers(headers1, stream_id=0, end_stream=True)
<< (request_header1 := http.HttpRequestHeadersHook(flow1))
<< cff.send_decoder() # for receive_headers
- >> cff.receive_headers(
- headers2, stream_id=4, end_stream=True
- )
+ >> cff.receive_headers(headers2, stream_id=4, end_stream=True)
<< (request_header2 := http.HttpRequestHeadersHook(flow2))
<< cff.send_decoder() # for receive_headers
>> tutils.reply(to=request_header2, side_effect=kill)
@@ -1028,9 +1013,7 @@ def test_kill_stream(tctx: context.Context):
<< commands.OpenConnection(server)
>> tutils.reply(None, side_effect=make_h3)
<< sff.send_init()
- << sff.send_headers(
- headers1, stream_id=0, end_stream=True
- )
+ << sff.send_headers(headers1, stream_id=0, end_stream=True)
>> sff.receive_init()
<< sff.send_encoder()
>> sff.receive_encoder()
@@ -1052,12 +1035,15 @@ class TestClient:
<< frame_factory.send_encoder()
>> frame_factory.receive_encoder()
>> http.RequestHeaders(1, req, end_stream=True)
- << frame_factory.send_headers([
- (b":method", b"GET"),
- (b':scheme', b'http'),
- (b':path', b'/'),
- (b'content-length', b'0'),
- ], end_stream=True)
+ << frame_factory.send_headers(
+ [
+ (b":method", b"GET"),
+ (b":scheme", b"http"),
+ (b":path", b"/"),
+ (b"content-length", b"0"),
+ ],
+ end_stream=True,
+ )
>> frame_factory.receive_decoder() # for send_headers
>> http.RequestEndOfMessage(1)
>> frame_factory.receive_headers(resp)
@@ -1099,12 +1085,15 @@ class TestClient:
"DATA frame is not allowed in this state"
)
>> http.RequestHeaders(1, req, end_stream=False)
- << frame_factory.send_headers([
- (b":method", b"GET"),
- (b':scheme', b'http'),
- (b':path', b'/'),
- (b'content-length', b'0'),
- ], end_stream=False)
+ << frame_factory.send_headers(
+ [
+ (b":method", b"GET"),
+ (b":scheme", b"http"),
+ (b":path", b"/"),
+ (b"content-length", b"0"),
+ ],
+ end_stream=False,
+ )
>> frame_factory.receive_decoder() # for send_headers
>> http.RequestHeaders(1, req, end_stream=False)
<< commands.Log(
diff --git a/test/mitmproxy/proxy/layers/http/test_http_fuzz.py b/test/mitmproxy/proxy/layers/http/test_http_fuzz.py
index 67478a02f..8e139e0c2 100644
--- a/test/mitmproxy/proxy/layers/http/test_http_fuzz.py
+++ b/test/mitmproxy/proxy/layers/http/test_http_fuzz.py
@@ -2,44 +2,44 @@ from typing import Any
import pytest
from h2.settings import SettingCodes
-from hypothesis import example, given
-from hypothesis.strategies import (
- binary,
- booleans,
- composite,
- dictionaries,
- integers,
- lists,
- sampled_from,
- sets,
- text,
- data,
-)
+from hypothesis import example
+from hypothesis import given
+from hypothesis.strategies import binary
+from hypothesis.strategies import booleans
+from hypothesis.strategies import composite
+from hypothesis.strategies import data
+from hypothesis.strategies import dictionaries
+from hypothesis.strategies import integers
+from hypothesis.strategies import lists
+from hypothesis.strategies import sampled_from
+from hypothesis.strategies import sets
+from hypothesis.strategies import text
-from mitmproxy import options, connection
+from mitmproxy import connection
+from mitmproxy import options
from mitmproxy.addons.proxyserver import Proxyserver
from mitmproxy.connection import Server
from mitmproxy.http import HTTPFlow
-from mitmproxy.proxy.layers.http import HTTPMode
-from mitmproxy.proxy import context, events
-from mitmproxy.proxy.commands import OpenConnection, SendData
-from mitmproxy.proxy.events import DataReceived, Start, ConnectionClosed
+from mitmproxy.proxy import context
+from mitmproxy.proxy import events
+from mitmproxy.proxy.commands import OpenConnection
+from mitmproxy.proxy.commands import SendData
+from mitmproxy.proxy.events import ConnectionClosed
+from mitmproxy.proxy.events import DataReceived
+from mitmproxy.proxy.events import Start
from mitmproxy.proxy.layers import http
-from test.mitmproxy.proxy.layers.http.hyper_h2_test_helpers import FrameFactory
-from test.mitmproxy.proxy.layers.http.test_http2 import (
- make_h2,
- example_response_headers,
- example_request_headers,
- start_h2_client,
-)
-from test.mitmproxy.proxy.tutils import (
- Placeholder,
- Playbook,
- reply,
- _TracebackInPlaybook,
- _eq,
-)
from mitmproxy.proxy.layers.http import _http2
+from mitmproxy.proxy.layers.http import HTTPMode
+from test.mitmproxy.proxy.layers.http.hyper_h2_test_helpers import FrameFactory
+from test.mitmproxy.proxy.layers.http.test_http2 import example_request_headers
+from test.mitmproxy.proxy.layers.http.test_http2 import example_response_headers
+from test.mitmproxy.proxy.layers.http.test_http2 import make_h2
+from test.mitmproxy.proxy.layers.http.test_http2 import start_h2_client
+from test.mitmproxy.proxy.tutils import _eq
+from test.mitmproxy.proxy.tutils import _TracebackInPlaybook
+from test.mitmproxy.proxy.tutils import Placeholder
+from test.mitmproxy.proxy.tutils import Playbook
+from test.mitmproxy.proxy.tutils import reply
opts = options.Options()
Proxyserver().load(opts)
@@ -217,7 +217,7 @@ def h2_frames(draw):
settings=draw(
dictionaries(
keys=sampled_from(SettingCodes),
- values=integers(0, 2 ** 32 - 1),
+ values=integers(0, 2**32 - 1),
max_size=5,
)
),
@@ -244,7 +244,7 @@ def h2_frames(draw):
draw(binary()), draw(h2_flags), stream_id=draw(h2_stream_ids_nonzero)
)
window_update = ff.build_window_update_frame(
- draw(h2_stream_ids), draw(integers(0, 2 ** 32 - 1))
+ draw(h2_stream_ids), draw(integers(0, 2**32 - 1))
)
frames = draw(
@@ -318,8 +318,12 @@ def test_fuzz_h2_request_mutations(chunks):
def _tctx() -> context.Context:
return context.Context(
- connection.Client(peername=("client", 1234), sockname=("127.0.0.1", 8080), timestamp_start=1605699329),
- opts
+ connection.Client(
+ peername=("client", 1234),
+ sockname=("127.0.0.1", 8080),
+ timestamp_start=1605699329,
+ ),
+ opts,
)
diff --git a/test/mitmproxy/proxy/layers/http/test_http_version_interop.py b/test/mitmproxy/proxy/layers/http/test_http_version_interop.py
index d0ae84248..599793e32 100644
--- a/test/mitmproxy/proxy/layers/http/test_http_version_interop.py
+++ b/test/mitmproxy/proxy/layers/http/test_http_version_interop.py
@@ -2,19 +2,21 @@ import h2.config
import h2.connection
import h2.events
-from mitmproxy.http import HTTPFlow
-from mitmproxy.proxy.context import Context
-from mitmproxy.proxy.layers.http import HTTPMode
-from mitmproxy.proxy.commands import CloseConnection, OpenConnection, SendData
from mitmproxy.connection import Server
+from mitmproxy.http import HTTPFlow
+from mitmproxy.proxy.commands import CloseConnection
+from mitmproxy.proxy.commands import OpenConnection
+from mitmproxy.proxy.commands import SendData
+from mitmproxy.proxy.context import Context
from mitmproxy.proxy.events import DataReceived
from mitmproxy.proxy.layers import http
+from mitmproxy.proxy.layers.http import HTTPMode
from test.mitmproxy.proxy.layers.http.hyper_h2_test_helpers import FrameFactory
-from test.mitmproxy.proxy.layers.http.test_http2 import (
- example_response_headers,
- make_h2,
-)
-from test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply
+from test.mitmproxy.proxy.layers.http.test_http2 import example_response_headers
+from test.mitmproxy.proxy.layers.http.test_http2 import make_h2
+from test.mitmproxy.proxy.tutils import Placeholder
+from test.mitmproxy.proxy.tutils import Playbook
+from test.mitmproxy.proxy.tutils import reply
example_request_headers = (
(b":method", b"GET"),
@@ -77,7 +79,9 @@ def test_h2_to_h1(tctx):
>> reply()
<< OpenConnection(server)
>> reply(None)
- << SendData(server, b"GET / HTTP/1.1\r\nHost: example.com\r\ncookie: a=1; b=2\r\n\r\n")
+ << SendData(
+ server, b"GET / HTTP/1.1\r\nHost: example.com\r\ncookie: a=1; b=2\r\n\r\n"
+ )
>> DataReceived(server, b"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\n")
<< http.HttpResponseHeadersHook(flow)
>> reply()
diff --git a/test/mitmproxy/proxy/layers/test_dns.py b/test/mitmproxy/proxy/layers/test_dns.py
index ab520bb62..133ae20b3 100644
--- a/test/mitmproxy/proxy/layers/test_dns.py
+++ b/test/mitmproxy/proxy/layers/test_dns.py
@@ -1,11 +1,18 @@
import time
-from mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData
-from mitmproxy.proxy.events import ConnectionClosed, DataReceived
-from mitmproxy.proxy.layers import dns
+from ..tutils import Placeholder
+from ..tutils import Playbook
+from ..tutils import reply
from mitmproxy.dns import DNSFlow
-from mitmproxy.test.tutils import tdnsreq, tdnsresp
-from ..tutils import Placeholder, Playbook, reply
+from mitmproxy.proxy.commands import CloseConnection
+from mitmproxy.proxy.commands import Log
+from mitmproxy.proxy.commands import OpenConnection
+from mitmproxy.proxy.commands import SendData
+from mitmproxy.proxy.events import ConnectionClosed
+from mitmproxy.proxy.events import DataReceived
+from mitmproxy.proxy.layers import dns
+from mitmproxy.test.tutils import tdnsreq
+from mitmproxy.test.tutils import tdnsresp
def test_invalid_and_dummy_end(tctx):
diff --git a/test/mitmproxy/proxy/layers/test_modes.py b/test/mitmproxy/proxy/layers/test_modes.py
index 96ca863f5..6d8040e3b 100644
--- a/test/mitmproxy/proxy/layers/test_modes.py
+++ b/test/mitmproxy/proxy/layers/test_modes.py
@@ -1,38 +1,46 @@
import copy
import pytest
-from mitmproxy import dns
+from mitmproxy import dns
from mitmproxy.addons.proxyauth import ProxyAuth
-from mitmproxy.connection import Client, ConnectionState, Server
+from mitmproxy.connection import Client
+from mitmproxy.connection import ConnectionState
+from mitmproxy.connection import Server
from mitmproxy.proxy import layers
-from mitmproxy.proxy.commands import (
- CloseConnection,
- Log,
- OpenConnection,
- RequestWakeup,
- SendData,
-)
+from mitmproxy.proxy.commands import CloseConnection
+from mitmproxy.proxy.commands import Log
+from mitmproxy.proxy.commands import OpenConnection
+from mitmproxy.proxy.commands import RequestWakeup
+from mitmproxy.proxy.commands import SendData
from mitmproxy.proxy.context import Context
-from mitmproxy.proxy.events import ConnectionClosed, DataReceived
-from mitmproxy.proxy.layer import NextLayer, NextLayerHook
-from mitmproxy.proxy.layers import http, modes, quic, tcp, tls, udp
+from mitmproxy.proxy.events import ConnectionClosed
+from mitmproxy.proxy.events import DataReceived
+from mitmproxy.proxy.layer import NextLayer
+from mitmproxy.proxy.layer import NextLayerHook
+from mitmproxy.proxy.layers import http
+from mitmproxy.proxy.layers import modes
+from mitmproxy.proxy.layers import quic
+from mitmproxy.proxy.layers import tcp
+from mitmproxy.proxy.layers import tls
+from mitmproxy.proxy.layers import udp
from mitmproxy.proxy.layers.http import HTTPMode
-from mitmproxy.proxy.layers.tcp import TcpMessageHook, TcpStartHook
-from mitmproxy.proxy.layers.tls import (
- ClientTLSLayer,
- TlsStartClientHook,
- TlsStartServerHook,
-)
+from mitmproxy.proxy.layers.tcp import TcpMessageHook
+from mitmproxy.proxy.layers.tcp import TcpStartHook
+from mitmproxy.proxy.layers.tls import ClientTLSLayer
+from mitmproxy.proxy.layers.tls import TlsStartClientHook
+from mitmproxy.proxy.layers.tls import TlsStartServerHook
from mitmproxy.proxy.mode_specs import ProxyMode
from mitmproxy.tcp import TCPFlow
-from mitmproxy.test import taddons, tflow
+from mitmproxy.test import taddons
+from mitmproxy.test import tflow
from mitmproxy.udp import UDPFlow
-from test.mitmproxy.proxy.layers.test_tls import (
- reply_tls_start_client,
- reply_tls_start_server,
-)
-from test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply, reply_next_layer
+from test.mitmproxy.proxy.layers.test_tls import reply_tls_start_client
+from test.mitmproxy.proxy.layers.test_tls import reply_tls_start_server
+from test.mitmproxy.proxy.tutils import Placeholder
+from test.mitmproxy.proxy.tutils import Playbook
+from test.mitmproxy.proxy.tutils import reply
+from test.mitmproxy.proxy.tutils import reply_next_layer
def test_upstream_https(tctx):
@@ -45,12 +53,24 @@ def test_upstream_https(tctx):
curl -x localhost:8080 -k http://example.com
"""
tctx1 = Context(
- Client(peername=("client", 1234), sockname=("127.0.0.1", 8080), timestamp_start=1605699329, state=ConnectionState.OPEN),
+ Client(
+ peername=("client", 1234),
+ sockname=("127.0.0.1", 8080),
+ timestamp_start=1605699329,
+ state=ConnectionState.OPEN,
+ ),
copy.deepcopy(tctx.options),
)
- tctx1.client.proxy_mode = ProxyMode.parse("upstream:https://example.mitmproxy.org:8081")
+ tctx1.client.proxy_mode = ProxyMode.parse(
+ "upstream:https://example.mitmproxy.org:8081"
+ )
tctx2 = Context(
- Client(peername=("client", 4321), sockname=("127.0.0.1", 8080), timestamp_start=1605699329, state=ConnectionState.OPEN),
+ Client(
+ peername=("client", 4321),
+ sockname=("127.0.0.1", 8080),
+ timestamp_start=1605699329,
+ state=ConnectionState.OPEN,
+ ),
copy.deepcopy(tctx.options),
)
assert tctx2.client.proxy_mode == ProxyMode.parse("regular")
diff --git a/test/mitmproxy/proxy/layers/test_quic.py b/test/mitmproxy/proxy/layers/test_quic.py
index 06da7725c..d635a3385 100644
--- a/test/mitmproxy/proxy/layers/test_quic.py
+++ b/test/mitmproxy/proxy/layers/test_quic.py
@@ -1,28 +1,42 @@
-from logging import DEBUG, ERROR, WARNING
import ssl
import time
+from logging import DEBUG
+from logging import ERROR
+from logging import WARNING
+from typing import Literal
+from typing import Optional
+from typing import TypeVar
+from unittest.mock import MagicMock
+
+import pytest
from aioquic.buffer import Buffer as QuicBuffer
from aioquic.quic import events as quic_events
from aioquic.quic.configuration import QuicConfiguration
-from aioquic.quic.connection import QuicConnection, pull_quic_header
-from typing import Literal, Optional, TypeVar
-from unittest.mock import MagicMock
-import pytest
+from aioquic.quic.connection import pull_quic_header
+from aioquic.quic.connection import QuicConnection
+
from mitmproxy import connection
-from mitmproxy.proxy import commands, context, events, layer, tunnel
+from mitmproxy.proxy import commands
+from mitmproxy.proxy import context
+from mitmproxy.proxy import events
+from mitmproxy.proxy import layer
from mitmproxy.proxy import layers
-from mitmproxy.proxy.layers import quic, tcp, tls, udp
-from mitmproxy.udp import UDPFlow, UDPMessage
+from mitmproxy.proxy import tunnel
+from mitmproxy.proxy.layers import quic
+from mitmproxy.proxy.layers import tcp
+from mitmproxy.proxy.layers import tls
+from mitmproxy.proxy.layers import udp
+from mitmproxy.tcp import TCPFlow
+from mitmproxy.udp import UDPFlow
+from mitmproxy.udp import UDPMessage
from mitmproxy.utils import data
from test.mitmproxy.proxy import tutils
-from mitmproxy.tcp import TCPFlow
-
tlsdata = data.Data(__name__)
-T = TypeVar('T', bound=layer.Layer)
+T = TypeVar("T", bound=layer.Layer)
class DummyLayer(layer.Layer):
@@ -44,26 +58,44 @@ class TlsEchoLayer(tutils.EchoLayer):
yield commands.SendData(
event.connection, f"open-connection failed: {err}".encode()
)
- elif isinstance(event, events.DataReceived) and event.data == b"close-connection":
+ elif (
+ isinstance(event, events.DataReceived) and event.data == b"close-connection"
+ ):
yield commands.CloseConnection(event.connection)
- elif isinstance(event, events.DataReceived) and event.data == b"close-connection-error":
+ elif (
+ isinstance(event, events.DataReceived)
+ and event.data == b"close-connection-error"
+ ):
yield quic.CloseQuicConnection(event.connection, 123, None, "error")
elif isinstance(event, events.DataReceived) and event.data == b"stop-stream":
yield quic.StopQuicStream(event.connection, 24, 123)
- elif isinstance(event, events.DataReceived) and event.data == b"invalid-command":
+ elif (
+ isinstance(event, events.DataReceived) and event.data == b"invalid-command"
+ ):
+
class InvalidConnectionCommand(commands.ConnectionCommand):
pass
+
yield InvalidConnectionCommand(event.connection)
- elif isinstance(event, events.DataReceived) and event.data == b"invalid-stream-command":
+ elif (
+ isinstance(event, events.DataReceived)
+ and event.data == b"invalid-stream-command"
+ ):
+
class InvalidStreamCommand(quic.QuicStreamCommand):
pass
+
yield InvalidStreamCommand(event.connection, 42)
elif isinstance(event, quic.QuicConnectionClosed):
self.closed = event
elif isinstance(event, quic.QuicStreamDataReceived):
- yield quic.SendQuicStreamData(event.connection, event.stream_id, event.data, event.end_stream)
+ yield quic.SendQuicStreamData(
+ event.connection, event.stream_id, event.data, event.end_stream
+ )
elif isinstance(event, quic.QuicStreamReset):
- yield quic.ResetQuicStream(event.connection, event.stream_id, event.error_code)
+ yield quic.ResetQuicStream(
+ event.connection, event.stream_id, event.error_code
+ )
else:
yield from super()._handle_event(event)
@@ -104,7 +136,7 @@ client_hello = bytes.fromhex(
def test_error_code_to_str():
assert quic.error_code_to_str(0x6) == "FINAL_SIZE_ERROR"
assert quic.error_code_to_str(0x104) == "H3_CLOSED_CRITICAL_STREAM"
- assert quic.error_code_to_str(0xdead) == f"unknown error (0xdead)"
+ assert quic.error_code_to_str(0xDEAD) == f"unknown error (0xdead)"
def test_is_success_error_code():
@@ -112,7 +144,7 @@ def test_is_success_error_code():
assert not quic.is_success_error_code(0x6)
assert quic.is_success_error_code(0x100)
assert not quic.is_success_error_code(0x104)
- assert not quic.is_success_error_code(0xdead)
+ assert not quic.is_success_error_code(0xDEAD)
@pytest.mark.parametrize("value", ["s1 s2\n", "s1 s2"])
@@ -133,7 +165,7 @@ class TestParseClientHello:
)
with pytest.raises(ValueError, match="not initial"):
quic.quic_parse_client_hello(
- b'\\s\xd8\xd8\xa5dT\x8bc\xd3\xae\x1c\xb2\x8a7-\x1d\x19j\x85\xb0~\x8c\x80\xa5\x8cY\xac\x0ecK\x7fC2f\xbcm\x1b\xac~'
+ b"\\s\xd8\xd8\xa5dT\x8bc\xd3\xae\x1c\xb2\x8a7-\x1d\x19j\x85\xb0~\x8c\x80\xa5\x8cY\xac\x0ecK\x7fC2f\xbcm\x1b\xac~"
)
def test_invalid(self, monkeypatch):
@@ -156,7 +188,9 @@ class TestParseClientHello:
def test_no_return(self):
with pytest.raises(ValueError, match="No ClientHello"):
- quic.quic_parse_client_hello(client_hello[0:1200] + b'\x00' + client_hello[1200:])
+ quic.quic_parse_client_hello(
+ client_hello[0:1200] + b"\x00" + client_hello[1200:]
+ )
class TestQuicStreamLayer:
@@ -247,13 +281,17 @@ class TestRawQuicLayer:
<< udp.UdpMessageHook(udpflow)
>> tutils.reply()
<< commands.SendData(tctx.server, b"msg2")
- >> udp.UdpMessageInjected(UDPFlow(("other", 80), tctx.server), UDPMessage(True, b"msg3"))
+ >> udp.UdpMessageInjected(
+ UDPFlow(("other", 80), tctx.server), UDPMessage(True, b"msg3")
+ )
<< udp.UdpMessageHook(udpflow)
>> tutils.reply()
<< commands.SendData(tctx.server, b"msg3")
)
with pytest.raises(AssertionError, match="not associated"):
- playbook >> udp.UdpMessageInjected(UDPFlow(("notfound", 0), ("noexist", 0)), UDPMessage(True, b"msg2"))
+ playbook >> udp.UdpMessageInjected(
+ UDPFlow(("notfound", 0), ("noexist", 0)), UDPMessage(True, b"msg2")
+ )
assert playbook
def test_reset_with_end_hook(self, tctx: context.Context):
@@ -316,8 +354,10 @@ class TestRawQuicLayer:
>> tutils.reply(None)
)
with pytest.raises(AssertionError, match="Unexpected stream event"):
+
class InvalidStreamEvent(quic.QuicStreamEvent):
pass
+
playbook >> InvalidStreamEvent(tctx.client, 0)
assert playbook
@@ -329,8 +369,10 @@ class TestRawQuicLayer:
>> tutils.reply(None)
)
with pytest.raises(AssertionError, match="Unexpected event"):
+
class InvalidEvent(events.Event):
pass
+
playbook >> InvalidEvent()
assert playbook
@@ -359,12 +401,16 @@ class TestRawQuicLayer:
tutils.Playbook(quic.RawQuicLayer(tctx))
<< commands.OpenConnection(tctx.server)
>> tutils.reply(None)
- >> quic.QuicStreamDataReceived(tctx.client, 0, b"open-connection", end_stream=False)
+ >> quic.QuicStreamDataReceived(
+ tctx.client, 0, b"open-connection", end_stream=False
+ )
<< layer.NextLayerHook(tutils.Placeholder())
>> tutils.reply_next_layer(echo_new_server)
<< commands.OpenConnection(server)
>> tutils.reply("uhoh")
- << quic.SendQuicStreamData(tctx.client, 0, b"open-connection failed: uhoh", end_stream=False)
+ << quic.SendQuicStreamData(
+ tctx.client, 0, b"open-connection failed: uhoh", end_stream=False
+ )
)
def test_invalid_connection_command(self, tctx: context.Context):
@@ -378,8 +424,12 @@ class TestRawQuicLayer:
>> tutils.reply_next_layer(TlsEchoLayer)
<< quic.SendQuicStreamData(tctx.client, 0, b"msg1", end_stream=False)
)
- with pytest.raises(AssertionError, match="Unexpected stream connection command"):
- playbook >> quic.QuicStreamDataReceived(tctx.client, 0, b"invalid-command", end_stream=False)
+ with pytest.raises(
+ AssertionError, match="Unexpected stream connection command"
+ ):
+ playbook >> quic.QuicStreamDataReceived(
+ tctx.client, 0, b"invalid-command", end_stream=False
+ )
assert playbook
@@ -412,8 +462,8 @@ def make_mock_quic(
quic_layer.quic = mock
quic_layer.tunnel_state = (
tls.tunnel.TunnelState.OPEN
- if established else
- tls.tunnel.TunnelState.ESTABLISHING
+ if established
+ else tls.tunnel.TunnelState.ESTABLISHING
)
return tutils.Playbook(quic_layer), mock
@@ -423,21 +473,19 @@ class TestQuicLayer:
def test_invalid_event(self, tctx: context.Context, established: bool):
class InvalidEvent(quic_events.QuicEvent):
pass
+
playbook, conn = make_mock_quic(
tctx, event=InvalidEvent(), established=established
)
with pytest.raises(AssertionError, match="Unexpected event"):
- assert (
- playbook
- >> events.DataReceived(tctx.client, b"")
- )
+ assert playbook >> events.DataReceived(tctx.client, b"")
def test_invalid_stream_command(self, tctx: context.Context):
playbook, conn = make_mock_quic(
tctx, quic_events.DatagramFrameReceived(b"invalid-stream-command")
)
with pytest.raises(AssertionError, match="Unexpected stream command"):
- assert (playbook >> events.DataReceived(tctx.client, b""))
+ assert playbook >> events.DataReceived(tctx.client, b"")
def test_close(self, tctx: context.Context):
playbook, conn = make_mock_quic(
@@ -470,7 +518,7 @@ class TestQuicLayer:
tctx, quic_events.DatagramFrameReceived(b"packet")
)
assert not conn._datagrams_pending
- assert (playbook >> events.DataReceived(tctx.client, b""))
+ assert playbook >> events.DataReceived(tctx.client, b"")
assert len(conn._datagrams_pending) == 1
assert conn._datagrams_pending[0] == b"packet"
@@ -479,15 +527,13 @@ class TestQuicLayer:
tctx, quic_events.StreamDataReceived(b"packet", False, 42)
)
assert 42 not in conn._streams
- assert (playbook >> events.DataReceived(tctx.client, b""))
+ assert playbook >> events.DataReceived(tctx.client, b"")
assert b"packet" == conn._streams[42].sender._buffer
def test_stream_reset(self, tctx: context.Context):
- playbook, conn = make_mock_quic(
- tctx, quic_events.StreamReset(123, 42)
- )
+ playbook, conn = make_mock_quic(tctx, quic_events.StreamReset(123, 42))
assert 42 not in conn._streams
- assert (playbook >> events.DataReceived(tctx.client, b""))
+ assert playbook >> events.DataReceived(tctx.client, b"")
assert conn._streams[42].sender.reset_pending
assert conn._streams[42].sender._reset_error_code == 123
@@ -497,7 +543,7 @@ class TestQuicLayer:
)
assert 24 not in conn._streams
conn._get_or_create_stream_for_send(24)
- assert (playbook >> events.DataReceived(tctx.client, b""))
+ assert playbook >> events.DataReceived(tctx.client, b"")
assert conn._streams[24].receiver.stop_pending
assert conn._streams[24].receiver._stop_error_code == 123
@@ -521,7 +567,9 @@ class SSLTest:
self.ctx.verify_mode = ssl.CERT_OPTIONAL
self.ctx.load_verify_locations(
- cafile=tlsdata.path("../../net/data/verificationcerts/trusted-root.crt"),
+ cafile=tlsdata.path(
+ "../../net/data/verificationcerts/trusted-root.crt"
+ ),
)
if alpn:
@@ -613,7 +661,7 @@ def finish_handshake(
playbook: tutils.Playbook,
conn: connection.Connection,
tssl: SSLTest,
- child_layer: type[T]
+ child_layer: type[T],
) -> T:
result: Optional[T] = None
@@ -644,9 +692,7 @@ def finish_handshake(
return result
-def reply_tls_start_client(
- alpn: Optional[str] = None, *args, **kwargs
-) -> tutils.reply:
+def reply_tls_start_client(alpn: Optional[str] = None, *args, **kwargs) -> tutils.reply:
"""
Helper function to simplify the syntax for quic_start_client hooks.
"""
@@ -658,9 +704,9 @@ def reply_tls_start_client(
tlsdata.path("../../net/data/verificationcerts/trusted-leaf.key"),
)
tls_start.settings = quic.QuicTlsSettings(
- certificate = config.certificate,
- certificate_chain = config.certificate_chain,
- certificate_private_key = config.private_key,
+ certificate=config.certificate,
+ certificate_chain=config.certificate_chain,
+ certificate_private_key=config.private_key,
)
if alpn is not None:
tls_start.settings.alpn_protocols = [alpn]
@@ -668,9 +714,7 @@ def reply_tls_start_client(
return tutils.reply(*args, side_effect=make_client_conn, **kwargs)
-def reply_tls_start_server(
- alpn: Optional[str] = None, *args, **kwargs
-) -> tutils.reply:
+def reply_tls_start_server(alpn: Optional[str] = None, *args, **kwargs) -> tutils.reply:
"""
Helper function to simplify the syntax for quic_start_server hooks.
"""
@@ -799,7 +843,7 @@ class TestServerTLS:
>> events.Wakeup(playbook.actual[9])
<< commands.Log(
"Server QUIC handshake failed. hostname 'wrong.host.mitmproxy.org' doesn't match 'example.mitmproxy.org'",
- WARNING
+ WARNING,
)
<< tls.TlsFailedServerHook(tls_hook_data)
>> tutils.reply()
@@ -810,7 +854,8 @@ class TestServerTLS:
)
)
assert (
- tls_hook_data().conn.error == "hostname 'wrong.host.mitmproxy.org' doesn't match 'example.mitmproxy.org'"
+ tls_hook_data().conn.error
+ == "hostname 'wrong.host.mitmproxy.org' doesn't match 'example.mitmproxy.org'"
)
assert not tctx.server.tls_established
@@ -822,7 +867,11 @@ def make_client_tls_layer(
# This is a bit contrived as the client layer expects a server layer as parent.
# We also set child layers manually to avoid NextLayer noise.
- server_layer = DummyLayer(tctx) if no_server else quic.ServerQuicLayer(tctx, time=lambda: tssl_client.now)
+ server_layer = (
+ DummyLayer(tctx)
+ if no_server
+ else quic.ServerQuicLayer(tctx, time=lambda: tssl_client.now)
+ )
client_layer = quic.ClientQuicLayer(tctx, time=lambda: tssl_client.now)
server_layer.child_layer = client_layer
playbook = tutils.Playbook(server_layer)
@@ -881,13 +930,21 @@ class TestClientTLS:
assert (
playbook
>> events.Wakeup(playbook.actual[16])
- << commands.Log(" >> Wakeup(command=RequestWakeup({'delay': 0.20000000000000004}))", DEBUG)
- << commands.Log(" [quic] close_notify Client(client:1234, state=open, tls) (reason=Idle timeout)", DEBUG)
+ << commands.Log(
+ " >> Wakeup(command=RequestWakeup({'delay': 0.20000000000000004}))",
+ DEBUG,
+ )
+ << commands.Log(
+ " [quic] close_notify Client(client:1234, state=open, tls) (reason=Idle timeout)",
+ DEBUG,
+ )
<< commands.CloseConnection(tctx.client)
)
@pytest.mark.parametrize("server_state", ["open", "closed"])
- def test_server_required(self, tctx: context.Context, server_state: Literal["open", "closed"]):
+ def test_server_required(
+ self, tctx: context.Context, server_state: Literal["open", "closed"]
+ ):
"""
Test the scenario where a server connection is required (for example, because of an unknown ALPN)
to establish TLS with the client.
@@ -959,7 +1016,9 @@ class TestClientTLS:
_test_echo(playbook, tssl_server, tctx.server)
@pytest.mark.parametrize("server_state", ["open", "closed"])
- def test_passthrough_from_clienthello(self, tctx: context.Context, server_state: Literal["open", "closed"]):
+ def test_passthrough_from_clienthello(
+ self, tctx: context.Context, server_state: Literal["open", "closed"]
+ ):
"""
Test the scenario where the connection is moved to passthrough mode in the tls_clienthello hook.
"""
@@ -1017,7 +1076,9 @@ class TestClientTLS:
client_layer.debug = ""
assert (
playbook
- >> events.DataReceived(connection.Server(address=None), b"data on other stream")
+ >> events.DataReceived(
+ connection.Server(address=None), b"data on other stream"
+ )
<< commands.Log(">> DataReceived(server, b'data on other stream')", DEBUG)
<< commands.Log(
"[quic] Swallowing DataReceived(server, b'data on other stream') as handshake failed.",
@@ -1093,12 +1154,16 @@ class TestClientTLS:
>> tutils.reply()
<< commands.Log(f"No QUIC context was provided, failing connection.", ERROR)
<< commands.CloseConnection(tctx.client)
- << commands.Log("Client QUIC handshake failed. connection closed early", WARNING)
+ << commands.Log(
+ "Client QUIC handshake failed. connection closed early", WARNING
+ )
<< tls.TlsFailedClientHook(tutils.Placeholder())
)
def test_no_server_tls(self, tctx: context.Context):
- playbook, client_layer, tssl_client = make_client_tls_layer(tctx, no_server=True)
+ playbook, client_layer, tssl_client = make_client_tls_layer(
+ tctx, no_server=True
+ )
def require_server_conn(client_hello: tls.ClientHelloData) -> None:
client_hello.establish_server_tls_first = True
@@ -1129,29 +1194,35 @@ class TestClientTLS:
def test_non_init_clienthello(self, tctx: context.Context):
playbook, client_layer, tssl_client = make_client_tls_layer(tctx)
data = (
- b'\xc2\x00\x00\x00\x01\x08q\xda\x98\x03X-\x13o\x08y\xa5RQv\xbe\xe3\xeb\x00@a\x98\x19\xf95t\xad-\x1c\\a\xdd\x8c\xd0\x15F'
- b'\xdf\xdc\x87cb\x1eu\xb0\x95*\xac\xa8\xf7a \xb8\nQ\xbd=\xf5x\xca\r\xe6\x8b\x05 w\x9f\xcd\x8d\xcb\xa0\x06\x1e \x8d.\x8f'
- b'T\xda\x12et\xe4\x83\x93X\x8aa\xd1\xb2\x18\xb6\xa7\xf50y\x9b\xc5T\xe1\x87\xdd\x9fqv\xb0\x90\xa7s'
- b'\xee\x00\x00\x00\x01\x08q\xda\x98\x03X-\x13o\x08y\xa5RQv\xbe\xe3\xeb@a*.\xa8j\x90\x1b\x1a\x7fZ\x04\x0b\\\xc7\x00\x03'
- b'\xd7sC\xf8G\x84\x1e\xba\xcf\x08Z\xdd\x98+\xaa\x98J\xca\xe3\xb7u1\x89\x00\xdf\x8e\x16`\xd9^\xc0@i\x1a\x10\x99\r\xd8'
- b'\x1dv3\xc6\xb8"\xb9\xa8F\x95K\x9a/\xbc\'\xd8\xd8\x94\x8f\xe7B/\x05\x9d\xfb\x80\xa9\xda@\xe6\xb0J\xfe\xe0\x0f\x02L}'
- b'\xd9\xed\xd2L\xa7\xcf'
+ b"\xc2\x00\x00\x00\x01\x08q\xda\x98\x03X-\x13o\x08y\xa5RQv\xbe\xe3\xeb\x00@a\x98\x19\xf95t\xad-\x1c\\a\xdd\x8c\xd0\x15F"
+ b"\xdf\xdc\x87cb\x1eu\xb0\x95*\xac\xa8\xf7a \xb8\nQ\xbd=\xf5x\xca\r\xe6\x8b\x05 w\x9f\xcd\x8d\xcb\xa0\x06\x1e \x8d.\x8f"
+ b"T\xda\x12et\xe4\x83\x93X\x8aa\xd1\xb2\x18\xb6\xa7\xf50y\x9b\xc5T\xe1\x87\xdd\x9fqv\xb0\x90\xa7s"
+ b"\xee\x00\x00\x00\x01\x08q\xda\x98\x03X-\x13o\x08y\xa5RQv\xbe\xe3\xeb@a*.\xa8j\x90\x1b\x1a\x7fZ\x04\x0b\\\xc7\x00\x03"
+ b"\xd7sC\xf8G\x84\x1e\xba\xcf\x08Z\xdd\x98+\xaa\x98J\xca\xe3\xb7u1\x89\x00\xdf\x8e\x16`\xd9^\xc0@i\x1a\x10\x99\r\xd8"
+ b"\x1dv3\xc6\xb8\"\xb9\xa8F\x95K\x9a/\xbc'\xd8\xd8\x94\x8f\xe7B/\x05\x9d\xfb\x80\xa9\xda@\xe6\xb0J\xfe\xe0\x0f\x02L}"
+ b"\xd9\xed\xd2L\xa7\xcf"
)
assert (
playbook
>> events.DataReceived(tctx.client, data)
- << commands.Log(f"Client QUIC handshake failed. Invalid handshake received, roaming not supported. ({data.hex()})", WARNING)
+ << commands.Log(
+ f"Client QUIC handshake failed. Invalid handshake received, roaming not supported. ({data.hex()})",
+ WARNING,
+ )
<< tls.TlsFailedClientHook(tutils.Placeholder())
)
assert client_layer.tunnel_state == tls.tunnel.TunnelState.ESTABLISHING
def test_invalid_clienthello(self, tctx: context.Context):
playbook, client_layer, tssl_client = make_client_tls_layer(tctx)
- data = client_hello[0:1200] + b'\x00' + client_hello[1200:]
+ data = client_hello[0:1200] + b"\x00" + client_hello[1200:]
assert (
playbook
>> events.DataReceived(tctx.client, data)
- << commands.Log(f"Client QUIC handshake failed. Cannot parse ClientHello: No ClientHello returned. ({data.hex()})", WARNING)
+ << commands.Log(
+ f"Client QUIC handshake failed. Cannot parse ClientHello: No ClientHello returned. ({data.hex()})",
+ WARNING,
+ )
<< tls.TlsFailedClientHook(tutils.Placeholder())
)
assert client_layer.tunnel_state == tls.tunnel.TunnelState.ESTABLISHING
diff --git a/test/mitmproxy/proxy/layers/test_socks5_fuzz.py b/test/mitmproxy/proxy/layers/test_socks5_fuzz.py
index bbefa4b01..e8762fd35 100644
--- a/test/mitmproxy/proxy/layers/test_socks5_fuzz.py
+++ b/test/mitmproxy/proxy/layers/test_socks5_fuzz.py
@@ -8,11 +8,14 @@ from mitmproxy.proxy.events import DataReceived
from mitmproxy.proxy.layers.modes import Socks5Proxy
opts = options.Options()
-tctx = Context(Client(
- peername=("client", 1234),
- sockname=("127.0.0.1", 8080),
- timestamp_start=1605699329
-), opts)
+tctx = Context(
+ Client(
+ peername=("client", 1234),
+ sockname=("127.0.0.1", 8080),
+ timestamp_start=1605699329,
+ ),
+ opts,
+)
@given(binary())
diff --git a/test/mitmproxy/proxy/layers/test_tcp.py b/test/mitmproxy/proxy/layers/test_tcp.py
index df01fa9f9..786462259 100644
--- a/test/mitmproxy/proxy/layers/test_tcp.py
+++ b/test/mitmproxy/proxy/layers/test_tcp.py
@@ -1,11 +1,18 @@
import pytest
-from mitmproxy.proxy.commands import CloseConnection, CloseTcpConnection, OpenConnection, SendData
-from mitmproxy.proxy.events import ConnectionClosed, DataReceived
+from ..tutils import Placeholder
+from ..tutils import Playbook
+from ..tutils import reply
+from mitmproxy.proxy.commands import CloseConnection
+from mitmproxy.proxy.commands import CloseTcpConnection
+from mitmproxy.proxy.commands import OpenConnection
+from mitmproxy.proxy.commands import SendData
+from mitmproxy.proxy.events import ConnectionClosed
+from mitmproxy.proxy.events import DataReceived
from mitmproxy.proxy.layers import tcp
from mitmproxy.proxy.layers.tcp import TcpMessageInjected
-from mitmproxy.tcp import TCPFlow, TCPMessage
-from ..tutils import Placeholder, Playbook, reply
+from mitmproxy.tcp import TCPFlow
+from mitmproxy.tcp import TCPMessage
def test_open_connection(tctx):
diff --git a/test/mitmproxy/proxy/layers/test_tls.py b/test/mitmproxy/proxy/layers/test_tls.py
index 7422a5322..1fde306fa 100644
--- a/test/mitmproxy/proxy/layers/test_tls.py
+++ b/test/mitmproxy/proxy/layers/test_tls.py
@@ -1,20 +1,26 @@
import ssl
-from logging import DEBUG, WARNING
-
import time
+from logging import DEBUG
+from logging import WARNING
from typing import Optional
import pytest
-
from OpenSSL import SSL
+
from mitmproxy import connection
-from mitmproxy.connection import ConnectionState, Server
-from mitmproxy.proxy import commands, context, events, layer
+from mitmproxy.connection import ConnectionState
+from mitmproxy.connection import Server
+from mitmproxy.proxy import commands
+from mitmproxy.proxy import context
+from mitmproxy.proxy import events
+from mitmproxy.proxy import layer
from mitmproxy.proxy.layers import tls
-from mitmproxy.tls import ClientHelloData, TlsData
+from mitmproxy.tls import ClientHelloData
+from mitmproxy.tls import TlsData
from mitmproxy.utils import data
from test.mitmproxy.proxy import tutils
-from test.mitmproxy.proxy.tutils import BytesMatching, StrMatching
+from test.mitmproxy.proxy.tutils import BytesMatching
+from test.mitmproxy.proxy.tutils import StrMatching
tlsdata = data.Data(__name__)
@@ -136,7 +142,7 @@ class SSLTest:
def bio_write(self, buf: bytes) -> int:
return self.inc.write(buf)
- def bio_read(self, bufsize: int = 2 ** 16) -> bytes:
+ def bio_read(self, bufsize: int = 2**16) -> bytes:
return self.out.read(bufsize)
def do_handshake(self) -> None:
@@ -365,7 +371,9 @@ class TestServerTLS:
>> events.DataReceived(tctx.server, tssl.bio_read())
<< commands.Log(
# different casing in OpenSSL < 3.0
- StrMatching("Server TLS handshake failed. Certificate verify failed: [Hh]ostname mismatch"),
+ StrMatching(
+ "Server TLS handshake failed. Certificate verify failed: [Hh]ostname mismatch"
+ ),
WARNING,
)
<< tls.TlsFailedServerHook(tls_hook_data)
@@ -374,11 +382,14 @@ class TestServerTLS:
<< commands.SendData(
tctx.client,
# different casing in OpenSSL < 3.0
- BytesMatching(b"open-connection failed: Certificate verify failed: [Hh]ostname mismatch"),
+ BytesMatching(
+ b"open-connection failed: Certificate verify failed: [Hh]ostname mismatch"
+ ),
)
)
assert (
- tls_hook_data().conn.error.lower() == "Certificate verify failed: Hostname mismatch".lower()
+ tls_hook_data().conn.error.lower()
+ == "Certificate verify failed: Hostname mismatch".lower()
)
assert not tctx.server.tls_established
@@ -780,7 +791,9 @@ def test_is_dtls_handshake_record():
def test_dtls_record_contents():
- data = bytes.fromhex("16fefd00000000000000000002beef" "16fefd00000000000000000001ff")
+ data = bytes.fromhex(
+ "16fefd00000000000000000002beef" "16fefd00000000000000000001ff"
+ )
assert list(tls.dtls_handshake_record_contents(data)) == [b"\xbe\xef", b"\xff"]
for i in range(12):
assert list(tls.dtls_handshake_record_contents(data[:i])) == []
@@ -800,8 +813,8 @@ dtls_client_hello_no_extensions = bytes.fromhex(
"cc02bc02fc00ac014c02cc03001000000"
)
dtls_client_hello_with_extensions = bytes.fromhex(
- "16fefd00000000000000000085" # record layer
- "010000790000000000000079" # hanshake layer
+ "16fefd00000000000000000085" # record layer
+ "010000790000000000000079" # hanshake layer
"fefd62bf0e0bf809df43e7669197be831919878b1a72c07a584d3c0a8ca6665878010000000cc02bc02fc00ac014c02cc0"
"3001000043000d0010000e0403050306030401050106010807ff01000100000a00080006001d00170018000b00020100001"
"7000000000010000e00000b6578616d706c652e636f6d"
@@ -809,26 +822,35 @@ dtls_client_hello_with_extensions = bytes.fromhex(
def test_dtls_get_client_hello():
- single_record = bytes.fromhex("16fefd00000000000000000042") + dtls_client_hello_no_extensions
+ single_record = (
+ bytes.fromhex("16fefd00000000000000000042") + dtls_client_hello_no_extensions
+ )
assert tls.get_dtls_client_hello(single_record) == dtls_client_hello_no_extensions
split_over_two_records = (
- bytes.fromhex("16fefd00000000000000000020")
- + dtls_client_hello_no_extensions[:32]
- + bytes.fromhex("16fefd00000000000000000022")
- + dtls_client_hello_no_extensions[32:]
+ bytes.fromhex("16fefd00000000000000000020")
+ + dtls_client_hello_no_extensions[:32]
+ + bytes.fromhex("16fefd00000000000000000022")
+ + dtls_client_hello_no_extensions[32:]
+ )
+ assert (
+ tls.get_dtls_client_hello(split_over_two_records)
+ == dtls_client_hello_no_extensions
)
- assert tls.get_dtls_client_hello(split_over_two_records) == dtls_client_hello_no_extensions
incomplete = split_over_two_records[:42]
assert tls.get_dtls_client_hello(incomplete) is None
def test_dtls_parse_client_hello():
- assert tls.dtls_parse_client_hello(dtls_client_hello_with_extensions).sni == "example.com"
+ assert (
+ tls.dtls_parse_client_hello(dtls_client_hello_with_extensions).sni
+ == "example.com"
+ )
assert tls.dtls_parse_client_hello(dtls_client_hello_with_extensions[:50]) is None
with pytest.raises(ValueError):
tls.dtls_parse_client_hello(
# Server Name Length longer than actual Server Name
- dtls_client_hello_with_extensions[:-16] + b"\x00\x0e\x00\x00\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ dtls_client_hello_with_extensions[:-16]
+ + b"\x00\x0e\x00\x00\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
)
diff --git a/test/mitmproxy/proxy/layers/test_tls_fuzz.py b/test/mitmproxy/proxy/layers/test_tls_fuzz.py
index 402c08a5f..e15740989 100644
--- a/test/mitmproxy/proxy/layers/test_tls_fuzz.py
+++ b/test/mitmproxy/proxy/layers/test_tls_fuzz.py
@@ -1,8 +1,10 @@
-from hypothesis import given, example
-from hypothesis.strategies import binary, integers
+from hypothesis import example
+from hypothesis import given
+from hypothesis.strategies import binary
+from hypothesis.strategies import integers
-from mitmproxy.tls import ClientHello
from mitmproxy.proxy.layers.tls import parse_client_hello
+from mitmproxy.tls import ClientHello
client_hello_with_extensions = bytes.fromhex(
"16030300bb" # record layer
diff --git a/test/mitmproxy/proxy/layers/test_udp.py b/test/mitmproxy/proxy/layers/test_udp.py
index 14b344a57..9b8d3b419 100644
--- a/test/mitmproxy/proxy/layers/test_udp.py
+++ b/test/mitmproxy/proxy/layers/test_udp.py
@@ -1,11 +1,17 @@
import pytest
-from mitmproxy.proxy.commands import CloseConnection, OpenConnection, SendData
-from mitmproxy.proxy.events import ConnectionClosed, DataReceived
+from ..tutils import Placeholder
+from ..tutils import Playbook
+from ..tutils import reply
+from mitmproxy.proxy.commands import CloseConnection
+from mitmproxy.proxy.commands import OpenConnection
+from mitmproxy.proxy.commands import SendData
+from mitmproxy.proxy.events import ConnectionClosed
+from mitmproxy.proxy.events import DataReceived
from mitmproxy.proxy.layers import udp
from mitmproxy.proxy.layers.udp import UdpMessageInjected
-from mitmproxy.udp import UDPFlow, UDPMessage
-from ..tutils import Placeholder, Playbook, reply
+from mitmproxy.udp import UDPFlow
+from mitmproxy.udp import UDPMessage
def test_open_connection(tctx):
diff --git a/test/mitmproxy/proxy/layers/test_websocket.py b/test/mitmproxy/proxy/layers/test_websocket.py
index a1d96133f..eebca259d 100644
--- a/test/mitmproxy/proxy/layers/test_websocket.py
+++ b/test/mitmproxy/proxy/layers/test_websocket.py
@@ -2,20 +2,28 @@ 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
-from mitmproxy.proxy.commands import SendData, CloseConnection, Log
-from mitmproxy.connection import ConnectionState
-from mitmproxy.proxy.events import DataReceived, ConnectionClosed
-from mitmproxy.proxy.layers import http, websocket
-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
+from mitmproxy.connection import ConnectionState
+from mitmproxy.http import HTTPFlow
+from mitmproxy.http import Request
+from mitmproxy.http import Response
+from mitmproxy.proxy.commands import CloseConnection
+from mitmproxy.proxy.commands import Log
+from mitmproxy.proxy.commands import SendData
+from mitmproxy.proxy.events import ConnectionClosed
+from mitmproxy.proxy.events import DataReceived
+from mitmproxy.proxy.layers import http
+from mitmproxy.proxy.layers import websocket
+from mitmproxy.proxy.layers.http import HTTPMode
+from mitmproxy.proxy.layers.websocket import WebSocketMessageInjected
+from mitmproxy.websocket import WebSocketData
+from mitmproxy.websocket import WebSocketMessage
+from test.mitmproxy.proxy.tutils import Placeholder
+from test.mitmproxy.proxy.tutils import Playbook
+from test.mitmproxy.proxy.tutils import reply
+
@dataclass
class _Masked:
diff --git a/test/mitmproxy/proxy/test_context.py b/test/mitmproxy/proxy/test_context.py
index 62e9c9b7a..1ac2bd833 100644
--- a/test/mitmproxy/proxy/test_context.py
+++ b/test/mitmproxy/proxy/test_context.py
@@ -1,5 +1,6 @@
from mitmproxy.proxy import context
-from mitmproxy.test import tflow, taddons
+from mitmproxy.test import taddons
+from mitmproxy.test import tflow
def test_context():
diff --git a/test/mitmproxy/proxy/test_events.py b/test/mitmproxy/proxy/test_events.py
index c415fadad..5e867369e 100644
--- a/test/mitmproxy/proxy/test_events.py
+++ b/test/mitmproxy/proxy/test_events.py
@@ -3,7 +3,8 @@ from unittest.mock import Mock
import pytest
from mitmproxy import connection
-from mitmproxy.proxy import events, commands
+from mitmproxy.proxy import commands
+from mitmproxy.proxy import events
@pytest.fixture
diff --git a/test/mitmproxy/proxy/test_layer.py b/test/mitmproxy/proxy/test_layer.py
index 1d4baef7e..b646c2e02 100644
--- a/test/mitmproxy/proxy/test_layer.py
+++ b/test/mitmproxy/proxy/test_layer.py
@@ -2,7 +2,9 @@ from logging import DEBUG
import pytest
-from mitmproxy.proxy import commands, events, layer
+from mitmproxy.proxy import commands
+from mitmproxy.proxy import events
+from mitmproxy.proxy import layer
from mitmproxy.proxy.context import Context
from test.mitmproxy.proxy import tutils
diff --git a/test/mitmproxy/proxy/test_mode_servers.py b/test/mitmproxy/proxy/test_mode_servers.py
index eea437ebb..917645fc8 100644
--- a/test/mitmproxy/proxy/test_mode_servers.py
+++ b/test/mitmproxy/proxy/test_mode_servers.py
@@ -1,14 +1,18 @@
import asyncio
import platform
from typing import cast
-from unittest.mock import AsyncMock, MagicMock, Mock
+from unittest.mock import AsyncMock
+from unittest.mock import MagicMock
+from unittest.mock import Mock
import pytest
import mitmproxy.platform
from mitmproxy.addons.proxyserver import Proxyserver
from mitmproxy.net import udp
-from mitmproxy.proxy.mode_servers import DnsInstance, ServerInstance, WireGuardServerInstance
+from mitmproxy.proxy.mode_servers import DnsInstance
+from mitmproxy.proxy.mode_servers import ServerInstance
+from mitmproxy.proxy.mode_servers import WireGuardServerInstance
from mitmproxy.proxy.server import ConnectionHandler
from mitmproxy.test import taddons
@@ -18,14 +22,23 @@ def test_make():
context = MagicMock()
assert ServerInstance.make("regular", manager)
- for mode in ["regular", "http3", "upstream:example.com", "transparent", "reverse:example.com", "socks5"]:
+ for mode in [
+ "regular",
+ "http3",
+ "upstream:example.com",
+ "transparent",
+ "reverse:example.com",
+ "socks5",
+ ]:
inst = ServerInstance.make(mode, manager)
assert inst
assert inst.make_top_layer(context)
assert inst.mode.description
assert inst.to_json()
- with pytest.raises(ValueError, match="is not a spec for a WireGuardServerInstance server."):
+ with pytest.raises(
+ ValueError, match="is not a spec for a WireGuardServerInstance server."
+ ):
WireGuardServerInstance.make("regular", manager)
@@ -86,7 +99,9 @@ async def test_transparent(failure, monkeypatch, caplog_async):
if failure:
monkeypatch.setattr(mitmproxy.platform, "original_addr", None)
else:
- monkeypatch.setattr(mitmproxy.platform, "original_addr", lambda s: ("address", 42))
+ monkeypatch.setattr(
+ mitmproxy.platform, "original_addr", lambda s: ("address", 42)
+ )
with taddons.context(Proxyserver()) as tctx:
tctx.options.connection_strategy = "lazy"
@@ -199,12 +214,16 @@ async def test_wireguard_invalid_conf(tmp_path):
async def test_tcp_start_error():
manager = MagicMock()
- server = await asyncio.start_server(MagicMock(), host="127.0.0.1", port=0, reuse_address=False)
+ server = await asyncio.start_server(
+ MagicMock(), host="127.0.0.1", port=0, reuse_address=False
+ )
port = server.sockets[0].getsockname()[1]
with taddons.context() as tctx:
inst = ServerInstance.make(f"regular@127.0.0.1:{port}", manager)
- with pytest.raises(OSError, match=f"proxy failed to listen on 127\\.0\\.0\\.1:{port}"):
+ with pytest.raises(
+ OSError, match=f"proxy failed to listen on 127\\.0\\.0\\.1:{port}"
+ ):
await inst.start()
tctx.options.listen_host = "127.0.0.1"
tctx.options.listen_port = port
@@ -253,7 +272,9 @@ async def test_udp_start_error():
await inst.start()
port = inst.listen_addrs[0][1]
inst2 = ServerInstance.make(f"dns@127.0.0.1:{port}", manager)
- with pytest.raises(OSError, match=f"server failed to listen on 127\\.0\\.0\\.1:{port}"):
+ with pytest.raises(
+ OSError, match=f"server failed to listen on 127\\.0\\.0\\.1:{port}"
+ ):
await inst2.start()
await inst.stop()
@@ -267,8 +288,12 @@ async def test_udp_connection_reuse(monkeypatch):
with taddons.context():
inst = cast(DnsInstance, ServerInstance.make("dns", manager))
- inst.handle_udp_datagram(MagicMock(), b"\x00\x00\x01", ("remoteaddr", 0), ("localaddr", 0))
- inst.handle_udp_datagram(MagicMock(), b"\x00\x00\x02", ("remoteaddr", 0), ("localaddr", 0))
+ inst.handle_udp_datagram(
+ MagicMock(), b"\x00\x00\x01", ("remoteaddr", 0), ("localaddr", 0)
+ )
+ inst.handle_udp_datagram(
+ MagicMock(), b"\x00\x00\x02", ("remoteaddr", 0), ("localaddr", 0)
+ )
await asyncio.sleep(0)
assert len(inst.manager.connections) == 1
diff --git a/test/mitmproxy/proxy/test_mode_specs.py b/test/mitmproxy/proxy/test_mode_specs.py
index be83e5238..b52c72196 100644
--- a/test/mitmproxy/proxy/test_mode_specs.py
+++ b/test/mitmproxy/proxy/test_mode_specs.py
@@ -2,7 +2,8 @@ import dataclasses
import pytest
-from mitmproxy.proxy.mode_specs import ProxyMode, Socks5Mode
+from mitmproxy.proxy.mode_specs import ProxyMode
+from mitmproxy.proxy.mode_specs import Socks5Mode
def test_parse():
@@ -45,7 +46,10 @@ def test_listen_addr():
assert ProxyMode.parse("regular").listen_host() == ""
assert ProxyMode.parse("regular@127.0.0.2:8080").listen_host() == "127.0.0.2"
assert ProxyMode.parse("regular").listen_host(default="127.0.0.3") == "127.0.0.3"
- assert ProxyMode.parse("regular@127.0.0.2:8080").listen_host(default="127.0.0.3") == "127.0.0.2"
+ assert (
+ ProxyMode.parse("regular@127.0.0.2:8080").listen_host(default="127.0.0.3")
+ == "127.0.0.2"
+ )
assert ProxyMode.parse("reverse:https://1.2.3.4").listen_port() == 8080
assert ProxyMode.parse("reverse:dns://8.8.8.8").listen_port() == 53
diff --git a/test/mitmproxy/proxy/test_tunnel.py b/test/mitmproxy/proxy/test_tunnel.py
index ad9af4112..0256390cf 100644
--- a/test/mitmproxy/proxy/test_tunnel.py
+++ b/test/mitmproxy/proxy/test_tunnel.py
@@ -2,12 +2,22 @@ from typing import Optional
import pytest
-from mitmproxy.proxy import tunnel, layer
-from mitmproxy.proxy.commands import CloseTcpConnection, SendData, Log, CloseConnection, OpenConnection
-from mitmproxy.connection import Server, ConnectionState
+from mitmproxy.connection import ConnectionState
+from mitmproxy.connection import Server
+from mitmproxy.proxy import layer
+from mitmproxy.proxy import tunnel
+from mitmproxy.proxy.commands import CloseConnection
+from mitmproxy.proxy.commands import CloseTcpConnection
+from mitmproxy.proxy.commands import Log
+from mitmproxy.proxy.commands import OpenConnection
+from mitmproxy.proxy.commands import SendData
from mitmproxy.proxy.context import Context
-from mitmproxy.proxy.events import Event, DataReceived, Start, ConnectionClosed
-from test.mitmproxy.proxy.tutils import Playbook, reply
+from mitmproxy.proxy.events import ConnectionClosed
+from mitmproxy.proxy.events import DataReceived
+from mitmproxy.proxy.events import Event
+from mitmproxy.proxy.events import Start
+from test.mitmproxy.proxy.tutils import Playbook
+from test.mitmproxy.proxy.tutils import reply
class TChildLayer(layer.Layer):
diff --git a/test/mitmproxy/proxy/test_tutils.py b/test/mitmproxy/proxy/test_tutils.py
index 04880990e..ec676405b 100644
--- a/test/mitmproxy/proxy/test_tutils.py
+++ b/test/mitmproxy/proxy/test_tutils.py
@@ -4,8 +4,10 @@ from typing import Any
import pytest
-from mitmproxy.proxy import commands, events, layer
from . import tutils
+from mitmproxy.proxy import commands
+from mitmproxy.proxy import events
+from mitmproxy.proxy import layer
class TEvent(events.Event):
diff --git a/test/mitmproxy/proxy/tutils.py b/test/mitmproxy/proxy/tutils.py
index 087db7131..618f6da0b 100644
--- a/test/mitmproxy/proxy/tutils.py
+++ b/test/mitmproxy/proxy/tutils.py
@@ -1,17 +1,24 @@
import collections.abc
import difflib
-import logging
-
import itertools
+import logging
import re
import textwrap
import traceback
-from collections.abc import Callable, Iterable
-from typing import Any, AnyStr, Generic, Optional, TypeVar, Union
+from collections.abc import Callable
+from collections.abc import Iterable
+from typing import Any
+from typing import AnyStr
+from typing import Generic
+from typing import Optional
+from typing import TypeVar
+from typing import Union
-from mitmproxy.proxy import commands, context, layer
-from mitmproxy.proxy import events
from mitmproxy.connection import ConnectionState
+from mitmproxy.proxy import commands
+from mitmproxy.proxy import context
+from mitmproxy.proxy import events
+from mitmproxy.proxy import layer
from mitmproxy.proxy.events import command_reply_subclasses
from mitmproxy.proxy.layer import Layer
diff --git a/test/mitmproxy/script/test_concurrent.py b/test/mitmproxy/script/test_concurrent.py
index 4bc5f1582..446fbb8d9 100644
--- a/test/mitmproxy/script/test_concurrent.py
+++ b/test/mitmproxy/script/test_concurrent.py
@@ -4,8 +4,8 @@ import time
import pytest
-from mitmproxy.test import tflow
from mitmproxy.test import taddons
+from mitmproxy.test import tflow
class TestConcurrent:
diff --git a/test/mitmproxy/test_addonmanager.py b/test/mitmproxy/test_addonmanager.py
index 77057d11b..4122f377c 100644
--- a/test/mitmproxy/test_addonmanager.py
+++ b/test/mitmproxy/test_addonmanager.py
@@ -7,7 +7,8 @@ from mitmproxy import exceptions
from mitmproxy import hooks
from mitmproxy import master
from mitmproxy import options
-from mitmproxy.proxy.layers.http import HttpRequestHook, HttpResponseHook
+from mitmproxy.proxy.layers.http import HttpRequestHook
+from mitmproxy.proxy.layers.http import HttpResponseHook
from mitmproxy.test import taddons
from mitmproxy.test import tflow
diff --git a/test/mitmproxy/test_certs.py b/test/mitmproxy/test_certs.py
index 448efdfea..815a84c61 100644
--- a/test/mitmproxy/test_certs.py
+++ b/test/mitmproxy/test_certs.py
@@ -1,13 +1,14 @@
import os
-from datetime import datetime, timezone
+from datetime import datetime
+from datetime import timezone
from pathlib import Path
+
+import pytest
from cryptography import x509
from cryptography.x509 import NameOID
-import pytest
-
-from mitmproxy import certs
from ..conftest import skip_windows
+from mitmproxy import certs
# class TestDNTree:
diff --git a/test/mitmproxy/test_command_lexer.py b/test/mitmproxy/test_command_lexer.py
index dfe9b2719..dd7be31dd 100644
--- a/test/mitmproxy/test_command_lexer.py
+++ b/test/mitmproxy/test_command_lexer.py
@@ -1,6 +1,7 @@
import pyparsing
import pytest
-from hypothesis import given, example
+from hypothesis import example
+from hypothesis import given
from hypothesis.strategies import text
from mitmproxy import command_lexer
diff --git a/test/mitmproxy/test_connection.py b/test/mitmproxy/test_connection.py
index 300015c76..eee660785 100644
--- a/test/mitmproxy/test_connection.py
+++ b/test/mitmproxy/test_connection.py
@@ -1,14 +1,20 @@
import pytest
-from mitmproxy.connection import Server, Client, ConnectionState
-from mitmproxy.test.tflow import tclient_conn, tserver_conn
+from mitmproxy.connection import Client
+from mitmproxy.connection import ConnectionState
+from mitmproxy.connection import Server
+from mitmproxy.test.tflow import tclient_conn
+from mitmproxy.test.tflow import tserver_conn
class TestConnection:
def test_basic(self):
- c = Client(peername=("127.0.0.1", 52314), sockname=("127.0.0.1", 8080),
- timestamp_start=1607780791,
- state=ConnectionState.OPEN)
+ c = Client(
+ peername=("127.0.0.1", 52314),
+ sockname=("127.0.0.1", 8080),
+ timestamp_start=1607780791,
+ state=ConnectionState.OPEN,
+ )
assert not c.tls_established
c.timestamp_tls_setup = 1607780792
assert c.tls_established
@@ -34,7 +40,7 @@ class TestClient:
peername=("127.0.0.1", 52314),
sockname=("127.0.0.1", 8080),
timestamp_start=1607780791,
- cipher_list=["foo", "bar"]
+ cipher_list=["foo", "bar"],
)
assert repr(c)
assert str(c)
diff --git a/test/mitmproxy/test_dns.py b/test/mitmproxy/test_dns.py
index 6a5075c91..cf9af2ac3 100644
--- a/test/mitmproxy/test_dns.py
+++ b/test/mitmproxy/test_dns.py
@@ -1,5 +1,6 @@
import ipaddress
import struct
+
import pytest
from mitmproxy import dns
@@ -111,7 +112,7 @@ class TestMessage:
with pytest.raises(ValueError):
req.packed
- test("id", 0, 2 ** 16 - 1)
+ test("id", 0, 2**16 - 1)
test("reserved", 0, 7)
test("op_code", 0, 0b1111)
test("response_code", 0, 0b1111)
diff --git a/test/mitmproxy/test_flow.py b/test/mitmproxy/test_flow.py
index a44408c25..29f2eeb93 100644
--- a/test/mitmproxy/test_flow.py
+++ b/test/mitmproxy/test_flow.py
@@ -8,8 +8,10 @@ from mitmproxy import flowfilter
from mitmproxy import options
from mitmproxy.exceptions import FlowReadException
from mitmproxy.io import tnetstring
-from mitmproxy.proxy import server_hooks, layers
-from mitmproxy.test import taddons, tflow
+from mitmproxy.proxy import layers
+from mitmproxy.proxy import server_hooks
+from mitmproxy.test import taddons
+from mitmproxy.test import tflow
class State:
diff --git a/test/mitmproxy/test_flowfilter.py b/test/mitmproxy/test_flowfilter.py
index cf6388c1e..b494c9333 100644
--- a/test/mitmproxy/test_flowfilter.py
+++ b/test/mitmproxy/test_flowfilter.py
@@ -1,8 +1,11 @@
import io
-import pytest
from unittest.mock import patch
+
+import pytest
+
+from mitmproxy import flowfilter
+from mitmproxy import http
from mitmproxy.test import tflow
-from mitmproxy import flowfilter, http
class TestParsing:
diff --git a/test/mitmproxy/test_http.py b/test/mitmproxy/test_http.py
index 169aafd71..acdff67d9 100644
--- a/test/mitmproxy/test_http.py
+++ b/test/mitmproxy/test_http.py
@@ -1,17 +1,21 @@
import asyncio
import email
-import time
import json
+import time
from unittest import mock
import pytest
from mitmproxy import flow
from mitmproxy import flowfilter
-from mitmproxy.http import Headers, Request, Response, HTTPFlow
+from mitmproxy.http import Headers
+from mitmproxy.http import HTTPFlow
+from mitmproxy.http import Request
+from mitmproxy.http import Response
from mitmproxy.net.http.cookies import CookieAttrs
from mitmproxy.test.tflow import tflow
-from mitmproxy.test.tutils import treq, tresp
+from mitmproxy.test.tutils import treq
+from mitmproxy.test.tutils import tresp
class TestRequest:
diff --git a/test/mitmproxy/test_optmanager.py b/test/mitmproxy/test_optmanager.py
index 391a7d0b7..62df7d0b5 100644
--- a/test/mitmproxy/test_optmanager.py
+++ b/test/mitmproxy/test_optmanager.py
@@ -1,14 +1,14 @@
+import argparse
import copy
import io
from collections.abc import Sequence
from typing import Optional
import pytest
-import argparse
+from mitmproxy import exceptions
from mitmproxy import options
from mitmproxy import optmanager
-from mitmproxy import exceptions
class TO(optmanager.OptManager):
diff --git a/test/mitmproxy/test_tcp.py b/test/mitmproxy/test_tcp.py
index 13001c862..3fdde8b23 100644
--- a/test/mitmproxy/test_tcp.py
+++ b/test/mitmproxy/test_tcp.py
@@ -1,7 +1,7 @@
import pytest
-from mitmproxy import tcp
from mitmproxy import flowfilter
+from mitmproxy import tcp
from mitmproxy.test import tflow
diff --git a/test/mitmproxy/test_tls.py b/test/mitmproxy/test_tls.py
index af23bc3ab..b04491b81 100644
--- a/test/mitmproxy/test_tls.py
+++ b/test/mitmproxy/test_tls.py
@@ -103,10 +103,11 @@ class TestDTLSClientHello:
assert c.cipher_suites == [2, 3, 10, 5, 4, 9]
assert c.alpn_protocols == [b"h2", b"http/1.1"]
assert c.extensions == [
- (13, b'\x00\x0e\x04\x03\x05\x03\x06\x03\x04\x01\x05\x01\x06\x01\x08\x07'),
- (65281, b'\x00'),
- (10, b'\x00\x06\x00\x1d\x00\x17\x00\x18'),
- (11, b'\x01\x00'), (23, b''),
- (0, b'\x00\x0e\x00\x00\x0bexample.com'),
- (16, b'\x00\x0c\x02h2\x08http/1.1')
+ (13, b"\x00\x0e\x04\x03\x05\x03\x06\x03\x04\x01\x05\x01\x06\x01\x08\x07"),
+ (65281, b"\x00"),
+ (10, b"\x00\x06\x00\x1d\x00\x17\x00\x18"),
+ (11, b"\x01\x00"),
+ (23, b""),
+ (0, b"\x00\x0e\x00\x00\x0bexample.com"),
+ (16, b"\x00\x0c\x02h2\x08http/1.1"),
]
diff --git a/test/mitmproxy/test_types.py b/test/mitmproxy/test_types.py
index 29d2b1f03..31a33b429 100644
--- a/test/mitmproxy/test_types.py
+++ b/test/mitmproxy/test_types.py
@@ -1,17 +1,16 @@
+import contextlib
+import os
from collections.abc import Sequence
import pytest
-import os
-import contextlib
import mitmproxy.exceptions
import mitmproxy.types
-from mitmproxy.test import taddons
-from mitmproxy.test import tflow
+from . import test_command
from mitmproxy import command
from mitmproxy import flow
-
-from . import test_command
+from mitmproxy.test import taddons
+from mitmproxy.test import tflow
@contextlib.contextmanager
diff --git a/test/mitmproxy/test_udp.py b/test/mitmproxy/test_udp.py
index 2a6a8dd12..ba652f74f 100644
--- a/test/mitmproxy/test_udp.py
+++ b/test/mitmproxy/test_udp.py
@@ -1,7 +1,7 @@
import pytest
-from mitmproxy import udp
from mitmproxy import flowfilter
+from mitmproxy import udp
from mitmproxy.test import tflow
diff --git a/test/mitmproxy/test_websocket.py b/test/mitmproxy/test_websocket.py
index f227d0dc5..08117b0fb 100644
--- a/test/mitmproxy/test_websocket.py
+++ b/test/mitmproxy/test_websocket.py
@@ -1,9 +1,9 @@
import pytest
+from wsproto.frame_protocol import Opcode
from mitmproxy import http
from mitmproxy import websocket
from mitmproxy.test import tflow
-from wsproto.frame_protocol import Opcode
class TestWebSocketData:
diff --git a/test/mitmproxy/tools/console/test_contentview.py b/test/mitmproxy/tools/console/test_contentview.py
index 9819ea9a2..ee0b72757 100644
--- a/test/mitmproxy/tools/console/test_contentview.py
+++ b/test/mitmproxy/tools/console/test_contentview.py
@@ -1,6 +1,6 @@
-from mitmproxy.test import tflow
from mitmproxy import contentviews
from mitmproxy.contentviews.base import format_text
+from mitmproxy.test import tflow
class TContentView(contentviews.View):
diff --git a/test/mitmproxy/tools/console/test_keymap.py b/test/mitmproxy/tools/console/test_keymap.py
index fb73471e3..624412ab2 100644
--- a/test/mitmproxy/tools/console/test_keymap.py
+++ b/test/mitmproxy/tools/console/test_keymap.py
@@ -1,8 +1,10 @@
-from mitmproxy.tools.console import keymap
-from mitmproxy.test import taddons
from unittest import mock
+
import pytest
+from mitmproxy.test import taddons
+from mitmproxy.tools.console import keymap
+
def test_binding():
b = keymap.Binding("space", "cmd", ["options"], "")
diff --git a/test/mitmproxy/tools/console/test_quickhelp.py b/test/mitmproxy/tools/console/test_quickhelp.py
index 958bf6ae4..722af3dab 100644
--- a/test/mitmproxy/tools/console/test_quickhelp.py
+++ b/test/mitmproxy/tools/console/test_quickhelp.py
@@ -1,7 +1,8 @@
import pytest
from mitmproxy.test.tflow import tflow
-from mitmproxy.tools.console import defaultkeys, quickhelp
+from mitmproxy.tools.console import defaultkeys
+from mitmproxy.tools.console import quickhelp
from mitmproxy.tools.console.eventlog import EventLog
from mitmproxy.tools.console.flowlist import FlowListBox
from mitmproxy.tools.console.flowview import FlowView
@@ -38,7 +39,7 @@ tflow2.marked = "x"
(EventLog, None, True),
(PathEditor, None, False),
(SimpleOverlay, None, False),
- ]
+ ],
)
def test_quickhelp(widget, flow, keymap, is_root_widget):
qh = quickhelp.make(widget, flow, is_root_widget)
diff --git a/test/mitmproxy/tools/web/test_app.py b/test/mitmproxy/tools/web/test_app.py
index 9a8ece62a..d4b29906b 100644
--- a/test/mitmproxy/tools/web/test_app.py
+++ b/test/mitmproxy/tools/web/test_app.py
@@ -1,5 +1,5 @@
-import io
import gzip
+import io
import json
import logging
import textwrap
@@ -14,7 +14,10 @@ import tornado.testing
from tornado import httpclient
from tornado import websocket
-from mitmproxy import certs, log, options, optmanager
+from mitmproxy import certs
+from mitmproxy import log
+from mitmproxy import options
+from mitmproxy import optmanager
from mitmproxy.http import Headers
from mitmproxy.proxy.mode_servers import ServerInstance
from mitmproxy.test import tflow
@@ -159,7 +162,9 @@ class TestApp(tornado.testing.AsyncHTTPTestCase):
o = options.Options(http2=False)
return webmaster.WebMaster(o, with_termlog=False)
- m: webmaster.WebMaster = self.io_loop.asyncio_loop.run_until_complete(make_master())
+ m: webmaster.WebMaster = self.io_loop.asyncio_loop.run_until_complete(
+ make_master()
+ )
f = tflow.tflow(resp=True)
f.id = "42"
f.request.content = b"foo\nbar"
@@ -177,11 +182,13 @@ class TestApp(tornado.testing.AsyncHTTPTestCase):
si2 = ServerInstance.make("reverse:example.com", m.proxyserver)
si2.last_exception = RuntimeError("I failed somehow.")
si3 = ServerInstance.make("socks5", m.proxyserver)
- m.proxyserver.servers._instances.update({
- si1.mode: si1,
- si2.mode: si2,
- si3.mode: si3,
- })
+ m.proxyserver.servers._instances.update(
+ {
+ si1.mode: si1,
+ si2.mode: si2,
+ si3.mode: si3,
+ }
+ )
self.master = m
self.view = m.view
self.events = m.events
@@ -497,11 +504,14 @@ class TestApp(tornado.testing.AsyncHTTPTestCase):
"export function TBackendState(): Required {\n"
" return %s\n"
"}\n"
- % textwrap.indent(json.dumps(data, indent=4, sort_keys=True), " ").lstrip()
+ % textwrap.indent(
+ json.dumps(data, indent=4, sort_keys=True), " "
+ ).lstrip()
)
(
- Path(__file__).parent / "../../../../web/src/js/__tests__/ducks/_tbackendstate.ts"
+ Path(__file__).parent
+ / "../../../../web/src/js/__tests__/ducks/_tbackendstate.ts"
).write_bytes(content.encode())
def test_err(self):
diff --git a/test/mitmproxy/tools/web/test_master.py b/test/mitmproxy/tools/web/test_master.py
index c193ea87b..14b104694 100644
--- a/test/mitmproxy/tools/web/test_master.py
+++ b/test/mitmproxy/tools/web/test_master.py
@@ -2,12 +2,15 @@ import asyncio
from unittest.mock import MagicMock
import pytest
+
from mitmproxy.options import Options
from mitmproxy.tools.web.master import WebMaster
async def test_reuse():
- server = await asyncio.start_server(MagicMock(), host="127.0.0.1", port=0, reuse_address=False)
+ server = await asyncio.start_server(
+ MagicMock(), host="127.0.0.1", port=0, reuse_address=False
+ )
port = server.sockets[0].getsockname()[1]
master = WebMaster(Options(), with_termlog=False)
master.options.web_host = "127.0.0.1"
diff --git a/test/mitmproxy/tools/web/test_static_viewer.py b/test/mitmproxy/tools/web/test_static_viewer.py
index 4364e2557..74473a18f 100644
--- a/test/mitmproxy/tools/web/test_static_viewer.py
+++ b/test/mitmproxy/tools/web/test_static_viewer.py
@@ -1,14 +1,13 @@
import json
from unittest import mock
+from mitmproxy import flowfilter
+from mitmproxy.addons import readfile
+from mitmproxy.addons import save
from mitmproxy.test import taddons
from mitmproxy.test import tflow
-
-from mitmproxy import flowfilter
-from mitmproxy.tools.web.app import flow_to_json
-
from mitmproxy.tools.web import static_viewer
-from mitmproxy.addons import save, readfile
+from mitmproxy.tools.web.app import flow_to_json
def test_save_static(tmpdir):
diff --git a/test/mitmproxy/utils/test_arg_check.py b/test/mitmproxy/utils/test_arg_check.py
index 97102f49b..d498d1c43 100644
--- a/test/mitmproxy/utils/test_arg_check.py
+++ b/test/mitmproxy/utils/test_arg_check.py
@@ -1,5 +1,5 @@
-import io
import contextlib
+import io
from unittest import mock
import pytest
diff --git a/test/mitmproxy/utils/test_data.py b/test/mitmproxy/utils/test_data.py
index f40fc8665..4e7c7af2a 100644
--- a/test/mitmproxy/utils/test_data.py
+++ b/test/mitmproxy/utils/test_data.py
@@ -1,4 +1,5 @@
import pytest
+
from mitmproxy.utils import data
diff --git a/test/mitmproxy/utils/test_debug.py b/test/mitmproxy/utils/test_debug.py
index a61bff868..6384a5981 100644
--- a/test/mitmproxy/utils/test_debug.py
+++ b/test/mitmproxy/utils/test_debug.py
@@ -1,6 +1,7 @@
import io
import sys
from unittest import mock
+
import pytest
from mitmproxy.utils import debug
diff --git a/test/mitmproxy/utils/test_emoji.py b/test/mitmproxy/utils/test_emoji.py
index a147ba885..2b099926b 100644
--- a/test/mitmproxy/utils/test_emoji.py
+++ b/test/mitmproxy/utils/test_emoji.py
@@ -1,5 +1,5 @@
-from mitmproxy.utils import emoji
from mitmproxy.tools.console.common import SYMBOL_MARK
+from mitmproxy.utils import emoji
def test_emoji():
diff --git a/test/mitmproxy/utils/test_human.py b/test/mitmproxy/utils/test_human.py
index 944740611..d4791de3c 100644
--- a/test/mitmproxy/utils/test_human.py
+++ b/test/mitmproxy/utils/test_human.py
@@ -1,5 +1,7 @@
import time
+
import pytest
+
from mitmproxy.utils import human
@@ -16,8 +18,8 @@ def test_parse_size():
assert human.parse_size("0b") == 0
assert human.parse_size("1") == 1
assert human.parse_size("1k") == 1024
- assert human.parse_size("1m") == 1024 ** 2
- assert human.parse_size("1g") == 1024 ** 3
+ assert human.parse_size("1m") == 1024**2
+ assert human.parse_size("1g") == 1024**3
with pytest.raises(ValueError):
human.parse_size("1f")
with pytest.raises(ValueError):
diff --git a/test/mitmproxy/utils/test_magisk.py b/test/mitmproxy/utils/test_magisk.py
index 83116d7f3..2382e3921 100644
--- a/test/mitmproxy/utils/test_magisk.py
+++ b/test/mitmproxy/utils/test_magisk.py
@@ -1,8 +1,10 @@
-from mitmproxy.utils import magisk
-from cryptography import x509
-from mitmproxy.test import taddons
import os
+from cryptography import x509
+
+from mitmproxy.test import taddons
+from mitmproxy.utils import magisk
+
def test_get_ca(tdata):
with taddons.context() as tctx:
diff --git a/test/mitmproxy/utils/test_signals.py b/test/mitmproxy/utils/test_signals.py
index 1fcc4f26d..dd856eb58 100644
--- a/test/mitmproxy/utils/test_signals.py
+++ b/test/mitmproxy/utils/test_signals.py
@@ -1,7 +1,9 @@
from unittest import mock
import pytest
-from mitmproxy.utils.signals import AsyncSignal, SyncSignal
+
+from mitmproxy.utils.signals import AsyncSignal
+from mitmproxy.utils.signals import SyncSignal
def test_sync_signal() -> None:
diff --git a/test/mitmproxy/utils/test_spec.py b/test/mitmproxy/utils/test_spec.py
index 6cefcacc7..630dd1799 100644
--- a/test/mitmproxy/utils/test_spec.py
+++ b/test/mitmproxy/utils/test_spec.py
@@ -1,4 +1,5 @@
import pytest
+
from mitmproxy.utils.spec import parse_spec
diff --git a/test/mitmproxy/utils/test_strutils.py b/test/mitmproxy/utils/test_strutils.py
index 3459a673f..f5b2894ac 100644
--- a/test/mitmproxy/utils/test_strutils.py
+++ b/test/mitmproxy/utils/test_strutils.py
@@ -44,7 +44,7 @@ def test_escape_control_characters():
def test_bytes_to_escaped_str():
assert strutils.bytes_to_escaped_str(b"foo") == "foo"
assert strutils.bytes_to_escaped_str(b"\b") == r"\x08"
- assert strutils.bytes_to_escaped_str(br"&!?=\)") == r"&!?=\\)"
+ assert strutils.bytes_to_escaped_str(rb"&!?=\)") == r"&!?=\\)"
assert strutils.bytes_to_escaped_str(b"\xc3\xbc") == r"\xc3\xbc"
assert strutils.bytes_to_escaped_str(b"'") == r"'"
assert strutils.bytes_to_escaped_str(b'"') == r'"'
@@ -69,9 +69,9 @@ def test_bytes_to_escaped_str():
def test_escaped_str_to_bytes():
assert strutils.escaped_str_to_bytes("foo") == b"foo"
assert strutils.escaped_str_to_bytes("\x08") == b"\b"
- assert strutils.escaped_str_to_bytes("&!?=\\\\)") == br"&!?=\)"
+ assert strutils.escaped_str_to_bytes("&!?=\\\\)") == rb"&!?=\)"
assert strutils.escaped_str_to_bytes("\\x08") == b"\b"
- assert strutils.escaped_str_to_bytes("&!?=\\\\)") == br"&!?=\)"
+ assert strutils.escaped_str_to_bytes("&!?=\\\\)") == rb"&!?=\)"
assert strutils.escaped_str_to_bytes("\u00fc") == b"\xc3\xbc"
with pytest.raises(ValueError):
diff --git a/test/mitmproxy/utils/test_typecheck.py b/test/mitmproxy/utils/test_typecheck.py
index 347e39f30..0f480157c 100644
--- a/test/mitmproxy/utils/test_typecheck.py
+++ b/test/mitmproxy/utils/test_typecheck.py
@@ -1,7 +1,10 @@
import io
import typing
from collections.abc import Sequence
-from typing import Any, Optional, TextIO, Union
+from typing import Any
+from typing import Optional
+from typing import TextIO
+from typing import Union
import pytest
@@ -84,4 +87,4 @@ def test_typesec_to_str():
def test_typing_aliases():
assert (typecheck.typespec_to_str(typing.Sequence[str])) == "sequence of str"
typecheck.check_option_type("foo", [10], typing.Sequence[int])
- typecheck.check_option_type("foo", (42, "42"), typing.Tuple[int, str])
+ typecheck.check_option_type("foo", (42, "42"), tuple[int, str])