From 7a9d40817ce0a97317b7940f7da2bb64da02eb51 Mon Sep 17 00:00:00 2001 From: Thomas Kriechbaumer Date: Mon, 6 Feb 2017 17:48:44 +0100 Subject: [PATCH] pytest.raises: shim new API --- test/conftest.py | 29 ++++------------ test/mitmproxy/addons/test_replace.py | 6 ++-- test/mitmproxy/addons/test_script.py | 6 ++-- test/mitmproxy/addons/test_setheaders.py | 4 +-- test/mitmproxy/addons/test_stickycookie.py | 2 +- test/mitmproxy/addons/test_streamfile.py | 2 +- test/mitmproxy/addons/test_view.py | 4 +-- test/mitmproxy/net/http/http1/test_read.py | 6 ++-- test/mitmproxy/net/test_socks.py | 3 +- test/mitmproxy/net/test_tcp.py | 4 +-- test/mitmproxy/net/websockets/test_frame.py | 4 +-- test/mitmproxy/test_flow.py | 14 ++++---- test/mitmproxy/test_optmanager.py | 12 +++---- test/mitmproxy/test_platform_pf.py | 4 +-- test/mitmproxy/test_proxy.py | 20 +++++------ test/mitmproxy/test_proxy_config.py | 6 ++-- test/pathod/test_language_base.py | 37 +++++++++------------ test/pathod/test_language_http.py | 8 ++--- test/pathod/test_language_http2.py | 4 +-- test/pathod/test_language_websocket.py | 4 +-- test/pathod/test_pathoc.py | 8 ++--- test/pathod/test_pathod.py | 2 +- 22 files changed, 83 insertions(+), 106 deletions(-) diff --git a/test/conftest.py b/test/conftest.py index 4b05624ba..50ec34211 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -2,6 +2,7 @@ import os import pytest import OpenSSL import functools +from contextlib import contextmanager import mitmproxy.net.tcp @@ -29,35 +30,19 @@ skip_appveyor = pytest.mark.skipif( original_pytest_raises = pytest.raises +# TODO: remove this wrapper when pytest 3.1.0 is released +@contextmanager @functools.wraps(original_pytest_raises) def raises(exc, *args, **kwargs): - if isinstance(exc, str): - return RaisesContext(exc) - else: - return original_pytest_raises(exc, *args, **kwargs) + with original_pytest_raises(exc, *args, **kwargs) as exc_info: + yield + if 'match' in kwargs: + assert exc_info.match(kwargs['match']) pytest.raises = raises -class RaisesContext: - def __init__(self, expected_exception): - self.expected_exception = expected_exception - - def __enter__(self): - return - - def __exit__(self, exc_type, exc_val, exc_tb): - if not exc_type: - raise AssertionError("No exception raised.") - else: - if self.expected_exception.lower() not in str(exc_val).lower(): - raise AssertionError( - "Expected %s, but caught %s" % (repr(self.expected_exception), repr(exc_val)) - ) - return True - - @pytest.fixture() def disable_alpn(monkeypatch): monkeypatch.setattr(mitmproxy.net.tcp, 'HAS_ALPN', False) diff --git a/test/mitmproxy/addons/test_replace.py b/test/mitmproxy/addons/test_replace.py index 5583b2c02..126c6e3df 100644 --- a/test/mitmproxy/addons/test_replace.py +++ b/test/mitmproxy/addons/test_replace.py @@ -16,16 +16,16 @@ class TestReplace: assert x == ("foo", "bar", "vo/ing/") x = replace.parse_hook("/bar/voing") assert x == (".*", "bar", "voing") - with pytest.raises("invalid replacement"): + with pytest.raises(Exception, match="Invalid replacement"): replace.parse_hook("/") def test_configure(self): r = replace.Replace() with taddons.context() as tctx: tctx.configure(r, replacements=[("one", "two", "three")]) - with pytest.raises("invalid filter pattern"): + with pytest.raises(Exception, match="Invalid filter pattern"): tctx.configure(r, replacements=[("~b", "two", "three")]) - with pytest.raises("invalid regular expression"): + with pytest.raises(Exception, match="Invalid regular expression"): tctx.configure(r, replacements=[("foo", "+", "three")]) tctx.configure(r, replacements=["/a/b/c/"]) diff --git a/test/mitmproxy/addons/test_script.py b/test/mitmproxy/addons/test_script.py index ed7ec5f1e..96d7bd9e0 100644 --- a/test/mitmproxy/addons/test_script.py +++ b/test/mitmproxy/addons/test_script.py @@ -64,11 +64,11 @@ class TestParseCommand: script.parse_command(" ") def test_no_script_file(self): - with pytest.raises("not found"): + with pytest.raises(Exception, match="not found"): script.parse_command("notfound") with tutils.tmpdir() as dir: - with pytest.raises("not a file"): + with pytest.raises(Exception, match="Not a file"): script.parse_command(dir) def test_parse_args(self): @@ -204,7 +204,7 @@ class TestScriptLoader: f = tflow.tflow(resp=True) with m.handlecontext(): - with pytest.raises("file not found"): + with pytest.raises(Exception, match="file not found"): sl.run_once("nonexistent", [f]) def test_simple(self): diff --git a/test/mitmproxy/addons/test_setheaders.py b/test/mitmproxy/addons/test_setheaders.py index 0091fc967..6355f2be0 100644 --- a/test/mitmproxy/addons/test_setheaders.py +++ b/test/mitmproxy/addons/test_setheaders.py @@ -14,13 +14,13 @@ class TestSetHeaders: assert x == ("foo", "bar", "vo/ing/") x = setheaders.parse_setheader("/bar/voing") assert x == (".*", "bar", "voing") - with pytest.raises("invalid replacement"): + with pytest.raises(Exception, match="Invalid replacement"): setheaders.parse_setheader("/") def test_configure(self): sh = setheaders.SetHeaders() with taddons.context() as tctx: - with pytest.raises("invalid setheader filter pattern"): + with pytest.raises(Exception, match="Invalid setheader filter pattern"): tctx.configure(sh, setheaders = [("~b", "one", "two")]) tctx.configure(sh, setheaders = ["/foo/bar/voing"]) diff --git a/test/mitmproxy/addons/test_stickycookie.py b/test/mitmproxy/addons/test_stickycookie.py index 2297fe2cd..157f2959d 100644 --- a/test/mitmproxy/addons/test_stickycookie.py +++ b/test/mitmproxy/addons/test_stickycookie.py @@ -16,7 +16,7 @@ class TestStickyCookie: def test_config(self): sc = stickycookie.StickyCookie() with taddons.context() as tctx: - with pytest.raises("invalid filter"): + with pytest.raises(Exception, match="invalid filter"): tctx.configure(sc, stickycookie="~b") tctx.configure(sc, stickycookie="foo") diff --git a/test/mitmproxy/addons/test_streamfile.py b/test/mitmproxy/addons/test_streamfile.py index 79e66c1e1..4922fc0be 100644 --- a/test/mitmproxy/addons/test_streamfile.py +++ b/test/mitmproxy/addons/test_streamfile.py @@ -18,7 +18,7 @@ def test_configure(): p = os.path.join(tdir, "foo") with pytest.raises(exceptions.OptionsError): tctx.configure(sa, streamfile=tdir) - with pytest.raises("invalid filter"): + with pytest.raises(Exception, match="Invalid filter"): tctx.configure(sa, streamfile=p, filtstr="~~") tctx.configure(sa, filtstr="foo") assert sa.filt diff --git a/test/mitmproxy/addons/test_view.py b/test/mitmproxy/addons/test_view.py index 7145bfc83..a063416ff 100644 --- a/test/mitmproxy/addons/test_view.py +++ b/test/mitmproxy/addons/test_view.py @@ -396,11 +396,11 @@ def test_configure(): v = view.View() with taddons.context(options=Options()) as tctx: tctx.configure(v, filter="~q") - with pytest.raises("invalid interception filter"): + with pytest.raises(Exception, match="Invalid interception filter"): tctx.configure(v, filter="~~") tctx.configure(v, console_order="method") - with pytest.raises("unknown flow order"): + with pytest.raises(Exception, match="Unknown flow order"): tctx.configure(v, console_order="no") tctx.configure(v, console_order_reversed=True) diff --git a/test/mitmproxy/net/http/http1/test_read.py b/test/mitmproxy/net/http/http1/test_read.py index 01d03e7ca..642b91c04 100644 --- a/test/mitmproxy/net/http/http1/test_read.py +++ b/test/mitmproxy/net/http/http1/test_read.py @@ -356,11 +356,11 @@ def test_read_chunked(): assert b"".join(_read_chunked(BytesIO(data))) == b"ab" data = b"\r\n" - with pytest.raises("closed prematurely"): + with pytest.raises(Exception, match="closed prematurely"): b"".join(_read_chunked(BytesIO(data))) data = b"1\r\nfoo" - with pytest.raises("malformed chunked body"): + with pytest.raises(Exception, match="Malformed chunked body"): b"".join(_read_chunked(BytesIO(data))) data = b"foo\r\nfoo" @@ -368,5 +368,5 @@ def test_read_chunked(): b"".join(_read_chunked(BytesIO(data))) data = b"5\r\naaaaa\r\n0\r\n\r\n" - with pytest.raises("too large"): + with pytest.raises(Exception, match="too large"): b"".join(_read_chunked(BytesIO(data), limit=2)) diff --git a/test/mitmproxy/net/test_socks.py b/test/mitmproxy/net/test_socks.py index c1bd0603e..e00dd4109 100644 --- a/test/mitmproxy/net/test_socks.py +++ b/test/mitmproxy/net/test_socks.py @@ -181,9 +181,8 @@ def test_message_ipv6(): def test_message_invalid_host(): raw = tutils.treader(b"\xEE\x01\x00\x03\x0bexample@com\xDE\xAD\xBE\xEF") - with pytest.raises(socks.SocksError) as exc_info: + with pytest.raises(socks.SocksError, match="Invalid hostname: b'example@com'"): socks.Message.from_file(raw) - assert exc_info.match("Invalid hostname: b'example@com'") def test_message_invalid_rsv(): diff --git a/test/mitmproxy/net/test_tcp.py b/test/mitmproxy/net/test_tcp.py index eb09f3287..ff6362c88 100644 --- a/test/mitmproxy/net/test_tcp.py +++ b/test/mitmproxy/net/test_tcp.py @@ -430,7 +430,7 @@ class TestServerCipherListError(tservers.ServerTestBase): def test_echo(self): c = tcp.TCPClient(("127.0.0.1", self.port)) with c.connect(): - with pytest.raises("handshake error"): + with pytest.raises(Exception, match="handshake error"): c.convert_to_ssl(sni="foo.com") @@ -443,7 +443,7 @@ class TestClientCipherListError(tservers.ServerTestBase): def test_echo(self): c = tcp.TCPClient(("127.0.0.1", self.port)) with c.connect(): - with pytest.raises("cipher specification"): + with pytest.raises(Exception, match="cipher specification"): c.convert_to_ssl(sni="foo.com", cipher_list="bogus") diff --git a/test/mitmproxy/net/websockets/test_frame.py b/test/mitmproxy/net/websockets/test_frame.py index 183c7caa4..2a5bd5561 100644 --- a/test/mitmproxy/net/websockets/test_frame.py +++ b/test/mitmproxy/net/websockets/test_frame.py @@ -108,9 +108,9 @@ class TestFrameHeader: assert not f2.mask def test_violations(self): - with pytest.raises("opcode"): + with pytest.raises(Exception, match="opcode"): websockets.FrameHeader(opcode=17) - with pytest.raises("masking key"): + with pytest.raises(Exception, match="Masking key"): websockets.FrameHeader(masking_key=b"x") def test_automask(self): diff --git a/test/mitmproxy/test_flow.py b/test/mitmproxy/test_flow.py index f546d61b2..3b5d0ac13 100644 --- a/test/mitmproxy/test_flow.py +++ b/test/mitmproxy/test_flow.py @@ -251,9 +251,8 @@ class TestSerialize: sio.write(b"bogus") sio.seek(0) r = mitmproxy.io.FlowReader(sio) - with pytest.raises(FlowReadException) as exc_info: + with pytest.raises(FlowReadException, match='Invalid data format'): list(r.stream()) - assert exc_info.match('Invalid data format') sio = io.BytesIO() f = tflow.tdummyflow() @@ -261,9 +260,8 @@ class TestSerialize: w.add(f) sio.seek(0) r = mitmproxy.io.FlowReader(sio) - with pytest.raises(FlowReadException) as exc_info: + with pytest.raises(FlowReadException, match='Unknown flow type'): list(r.stream()) - assert exc_info.match('Unknown flow type') f = FlowReadException("foo") assert str(f) == "foo" @@ -277,7 +275,7 @@ class TestSerialize: sio.seek(0) r = mitmproxy.io.FlowReader(sio) - with pytest.raises("version"): + with pytest.raises(Exception, match="version"): list(r.stream()) @@ -287,15 +285,15 @@ class TestFlowMaster: fm = master.Master(None, DummyServer()) f = tflow.tflow(resp=True) f.request.content = None - with pytest.raises("missing"): + with pytest.raises(Exception, match="missing"): fm.replay_request(f) f.intercepted = True - with pytest.raises("intercepted"): + with pytest.raises(Exception, match="intercepted"): fm.replay_request(f) f.live = True - with pytest.raises("live"): + with pytest.raises(Exception, match="live"): fm.replay_request(f) def test_create_flow(self): diff --git a/test/mitmproxy/test_optmanager.py b/test/mitmproxy/test_optmanager.py index f177df7b7..65691fdf8 100644 --- a/test/mitmproxy/test_optmanager.py +++ b/test/mitmproxy/test_optmanager.py @@ -71,9 +71,9 @@ def test_options(): with pytest.raises(TypeError): TO(nonexistent = "value") - with pytest.raises("no such option"): + with pytest.raises(Exception, match="No such option"): o.nonexistent = "value" - with pytest.raises("no such option"): + with pytest.raises(Exception, match="No such option"): o.update(nonexistent = "value") rec = [] @@ -97,7 +97,7 @@ def test_setter(): f = o.setter("two") f("xxx") assert o.two == "xxx" - with pytest.raises("no such option"): + with pytest.raises(Exception, match="No such option"): o.setter("nonexistent") @@ -108,7 +108,7 @@ def test_toggler(): assert o.two is False f() assert o.two is True - with pytest.raises("no such option"): + with pytest.raises(Exception, match="No such option"): o.toggler("nonexistent") @@ -193,11 +193,11 @@ def test_serialize(): assert o2 == o t = "invalid: foo\ninvalid" - with pytest.raises("config error"): + with pytest.raises(Exception, match="Config error"): o2.load(t) t = "invalid" - with pytest.raises("config error"): + with pytest.raises(Exception, match="Config error"): o2.load(t) t = "" diff --git a/test/mitmproxy/test_platform_pf.py b/test/mitmproxy/test_platform_pf.py index ebb011fef..f644bcc5a 100644 --- a/test/mitmproxy/test_platform_pf.py +++ b/test/mitmproxy/test_platform_pf.py @@ -14,7 +14,7 @@ class TestLookup: p = tutils.test_data.path("mitmproxy/data/pf01") d = open(p, "rb").read() assert pf.lookup("192.168.1.111", 40000, d) == ("5.5.5.5", 80) - with pytest.raises("Could not resolve original destination"): + with pytest.raises(Exception, match="Could not resolve original destination"): pf.lookup("192.168.1.112", 40000, d) - with pytest.raises("Could not resolve original destination"): + with pytest.raises(Exception, match="Could not resolve original destination"): pf.lookup("192.168.1.111", 40001, d) diff --git a/test/mitmproxy/test_proxy.py b/test/mitmproxy/test_proxy.py index 9d7935725..a14c851ee 100644 --- a/test/mitmproxy/test_proxy.py +++ b/test/mitmproxy/test_proxy.py @@ -96,27 +96,27 @@ class TestProcessProxyOptions: @mock.patch("mitmproxy.platform.original_addr", None) def test_no_transparent(self): - with pytest.raises("transparent mode not supported"): + with pytest.raises(Exception, match="Transparent mode not supported"): self.p("-T") @mock.patch("mitmproxy.platform.original_addr") def test_modes(self, _): self.assert_noerr("-R", "http://localhost") - with pytest.raises("expected one argument"): + with pytest.raises(Exception, match="expected one argument"): self.p("-R") - with pytest.raises("Invalid server specification"): + with pytest.raises(Exception, match="Invalid server specification"): self.p("-R", "reverse") self.assert_noerr("-T") self.assert_noerr("-U", "http://localhost") - with pytest.raises("Invalid server specification"): + with pytest.raises(Exception, match="Invalid server specification"): self.p("-U", "upstream") self.assert_noerr("--upstream-auth", "test:test") - with pytest.raises("expected one argument"): + with pytest.raises(Exception, match="expected one argument"): self.p("--upstream-auth") - with pytest.raises("mutually exclusive"): + with pytest.raises(Exception, match="mutually exclusive"): self.p("-R", "http://localhost", "-T") def test_client_certs(self): @@ -125,14 +125,14 @@ class TestProcessProxyOptions: self.assert_noerr( "--client-certs", os.path.join(tutils.test_data.path("mitmproxy/data/clientcert"), "client.pem")) - with pytest.raises("path does not exist"): + with pytest.raises(Exception, match="path does not exist"): self.p("--client-certs", "nonexistent") def test_certs(self): self.assert_noerr( "--cert", tutils.test_data.path("mitmproxy/data/testkey.pem")) - with pytest.raises("does not exist"): + with pytest.raises(Exception, match="does not exist"): self.p("--cert", "nonexistent") def test_insecure(self): @@ -156,12 +156,12 @@ class TestProxyServer: def test_err(self): # binding to 0.0.0.0:1 works without special permissions on Windows conf = ProxyConfig(options.Options(listen_port=1)) - with pytest.raises("error starting proxy server"): + with pytest.raises(Exception, match="Error starting proxy server"): ProxyServer(conf) def test_err_2(self): conf = ProxyConfig(options.Options(listen_host="invalidhost")) - with pytest.raises("error starting proxy server"): + with pytest.raises(Exception, match="Error starting proxy server"): ProxyServer(conf) diff --git a/test/mitmproxy/test_proxy_config.py b/test/mitmproxy/test_proxy_config.py index 27563e3a3..4272d9527 100644 --- a/test/mitmproxy/test_proxy_config.py +++ b/test/mitmproxy/test_proxy_config.py @@ -3,7 +3,7 @@ from mitmproxy.proxy import config def test_parse_server_spec(): - with pytest.raises("Invalid server specification"): + with pytest.raises(Exception, match="Invalid server specification"): config.parse_server_spec("") assert config.parse_server_spec("http://foo.com:88") == ( "http", ("foo.com", 88) @@ -14,7 +14,7 @@ def test_parse_server_spec(): assert config.parse_server_spec("https://foo.com") == ( "https", ("foo.com", 443) ) - with pytest.raises("Invalid server specification"): + with pytest.raises(Exception, match="Invalid server specification"): config.parse_server_spec("foo.com") - with pytest.raises("Invalid server specification"): + with pytest.raises(Exception, match="Invalid server specification"): config.parse_server_spec("http://") diff --git a/test/pathod/test_language_base.py b/test/pathod/test_language_base.py index 190c39b3d..85e9e53b5 100644 --- a/test/pathod/test_language_base.py +++ b/test/pathod/test_language_base.py @@ -149,11 +149,11 @@ class TestTokValueFile: v = base.TokValue.parseString("