aboutsummaryrefslogtreecommitdiffstats
path: root/test
diff options
context:
space:
mode:
Diffstat (limited to 'test')
-rw-r--r--test/conftest.py124
-rw-r--r--test/full_coverage_plugin.py119
-rw-r--r--test/mitmproxy/__init__.py1
-rw-r--r--test/mitmproxy/contentviews/image/test_image_parser.py6
-rw-r--r--test/mitmproxy/contentviews/image/test_view.py8
-rw-r--r--test/mitmproxy/contentviews/test_auto.py12
-rw-r--r--test/mitmproxy/proxy/protocol/test_http2.py2
7 files changed, 149 insertions, 123 deletions
diff --git a/test/conftest.py b/test/conftest.py
index 83823a19..b4e1da93 100644
--- a/test/conftest.py
+++ b/test/conftest.py
@@ -6,6 +6,7 @@ from contextlib import contextmanager
import mitmproxy.net.tcp
+pytest_plugins = ('test.full_coverage_plugin',)
requires_alpn = pytest.mark.skipif(
not mitmproxy.net.tcp.HAS_ALPN,
@@ -27,10 +28,17 @@ skip_appveyor = pytest.mark.skipif(
)
-original_pytest_raises = pytest.raises
+@pytest.fixture()
+def disable_alpn(monkeypatch):
+ monkeypatch.setattr(mitmproxy.net.tcp, 'HAS_ALPN', False)
+ monkeypatch.setattr(OpenSSL.SSL._lib, 'Cryptography_HAS_ALPN', False)
+################################################################################
# TODO: remove this wrapper when pytest 3.1.0 is released
+original_pytest_raises = pytest.raises
+
+
@contextmanager
@functools.wraps(original_pytest_raises)
def raises(exc, *args, **kwargs):
@@ -41,116 +49,4 @@ def raises(exc, *args, **kwargs):
pytest.raises = raises
-
-
-@pytest.fixture()
-def disable_alpn(monkeypatch):
- monkeypatch.setattr(mitmproxy.net.tcp, 'HAS_ALPN', False)
- monkeypatch.setattr(OpenSSL.SSL._lib, 'Cryptography_HAS_ALPN', False)
-
-
-enable_coverage = False
-coverage_values = []
-coverage_passed = False
-
-
-def pytest_addoption(parser):
- parser.addoption('--full-cov',
- action='append',
- dest='full_cov',
- default=[],
- help="Require full test coverage of 100%% for this module/path/filename (multi-allowed). Default: none")
-
- parser.addoption('--no-full-cov',
- action='append',
- dest='no_full_cov',
- default=[],
- help="Exclude file from a parent 100%% coverage requirement (multi-allowed). Default: none")
-
-
-def pytest_configure(config):
- global enable_coverage
- enable_coverage = (
- len(config.getoption('file_or_dir')) == 0 and
- len(config.getoption('full_cov')) > 0 and
- config.pluginmanager.getplugin("_cov") is not None and
- config.pluginmanager.getplugin("_cov").cov_controller is not None and
- config.pluginmanager.getplugin("_cov").cov_controller.cov is not None
- )
-
-
-@pytest.hookimpl(hookwrapper=True)
-def pytest_runtestloop(session):
- global enable_coverage
- global coverage_values
- global coverage_passed
-
- if not enable_coverage:
- yield
- return
-
- cov = pytest.config.pluginmanager.getplugin("_cov").cov_controller.cov
-
- if os.name == 'nt':
- cov.exclude('pragma: windows no cover')
-
- yield
-
- coverage_values = dict([(name, 0) for name in pytest.config.option.full_cov])
-
- prefix = os.getcwd()
- excluded_files = [os.path.normpath(f) for f in pytest.config.option.no_full_cov]
- measured_files = [os.path.normpath(os.path.relpath(f, prefix)) for f in cov.get_data().measured_files()]
- measured_files = [f for f in measured_files if not any(f.startswith(excluded_f) for excluded_f in excluded_files)]
-
- for name in coverage_values.keys():
- files = [f for f in measured_files if f.startswith(os.path.normpath(name))]
- try:
- with open(os.devnull, 'w') as null:
- overall = cov.report(files, ignore_errors=True, file=null)
- singles = [(s, cov.report(s, ignore_errors=True, file=null)) for s in files]
- coverage_values[name] = (overall, singles)
- except:
- pass
-
- if any(v < 100 for v, _ in coverage_values.values()):
- # make sure we get the EXIT_TESTSFAILED exit code
- session.testsfailed += 1
- else:
- coverage_passed = True
-
-
-def pytest_terminal_summary(terminalreporter, exitstatus):
- global enable_coverage
- global coverage_values
- global coverage_passed
-
- if not enable_coverage:
- return
-
- terminalreporter.write('\n')
- if not coverage_passed:
- markup = {'red': True, 'bold': True}
- msg = "FAIL: Full test coverage not reached!\n"
- terminalreporter.write(msg, **markup)
-
- for name in sorted(coverage_values.keys()):
- msg = 'Coverage for {}: {:.2f}%\n'.format(name, coverage_values[name][0])
- if coverage_values[name][0] < 100:
- markup = {'red': True, 'bold': True}
- for s, v in sorted(coverage_values[name][1]):
- if v < 100:
- msg += ' {}: {:.2f}%\n'.format(s, v)
- else:
- markup = {'green': True}
- terminalreporter.write(msg, **markup)
- else:
- markup = {'green': True}
- msg = 'SUCCESS: Full test coverage reached in modules and files:\n'
- msg += '{}\n\n'.format('\n'.join(pytest.config.option.full_cov))
- terminalreporter.write(msg, **markup)
-
- msg = '\nExcluded files:\n'
- for s in sorted(pytest.config.option.no_full_cov):
- msg += " {}\n".format(s)
- terminalreporter.write(msg)
+################################################################################
diff --git a/test/full_coverage_plugin.py b/test/full_coverage_plugin.py
new file mode 100644
index 00000000..e9951af9
--- /dev/null
+++ b/test/full_coverage_plugin.py
@@ -0,0 +1,119 @@
+import os
+import configparser
+import pytest
+
+
+enable_coverage = False
+coverage_values = []
+coverage_passed = True
+no_full_cov = []
+
+
+def pytest_addoption(parser):
+ parser.addoption('--full-cov',
+ action='append',
+ dest='full_cov',
+ default=[],
+ help="Require full test coverage of 100%% for this module/path/filename (multi-allowed). Default: none")
+
+ parser.addoption('--no-full-cov',
+ action='append',
+ dest='no_full_cov',
+ default=[],
+ help="Exclude file from a parent 100%% coverage requirement (multi-allowed). Default: none")
+
+
+def pytest_configure(config):
+ global enable_coverage
+ global no_full_cov
+
+ enable_coverage = (
+ len(config.getoption('file_or_dir')) == 0 and
+ len(config.getoption('full_cov')) > 0 and
+ config.pluginmanager.getplugin("_cov") is not None and
+ config.pluginmanager.getplugin("_cov").cov_controller is not None and
+ config.pluginmanager.getplugin("_cov").cov_controller.cov is not None
+ )
+
+ c = configparser.ConfigParser()
+ c.read('setup.cfg')
+ fs = c['tool:full_coverage']['exclude'].split('\n')
+ no_full_cov = config.option.no_full_cov + [f.strip() for f in fs]
+
+
+@pytest.hookimpl(hookwrapper=True)
+def pytest_runtestloop(session):
+ global enable_coverage
+ global coverage_values
+ global coverage_passed
+ global no_full_cov
+
+ if not enable_coverage:
+ yield
+ return
+
+ cov = pytest.config.pluginmanager.getplugin("_cov").cov_controller.cov
+
+ if os.name == 'nt':
+ cov.exclude('pragma: windows no cover')
+
+ yield
+
+ coverage_values = dict([(name, 0) for name in pytest.config.option.full_cov])
+
+ prefix = os.getcwd()
+
+ excluded_files = [os.path.normpath(f) for f in no_full_cov]
+ measured_files = [os.path.normpath(os.path.relpath(f, prefix)) for f in cov.get_data().measured_files()]
+ measured_files = [f for f in measured_files if not any(f.startswith(excluded_f) for excluded_f in excluded_files)]
+
+ for name in coverage_values.keys():
+ files = [f for f in measured_files if f.startswith(os.path.normpath(name))]
+ try:
+ with open(os.devnull, 'w') as null:
+ overall = cov.report(files, ignore_errors=True, file=null)
+ singles = [(s, cov.report(s, ignore_errors=True, file=null)) for s in files]
+ coverage_values[name] = (overall, singles)
+ except:
+ pass
+
+ if any(v < 100 for v, _ in coverage_values.values()):
+ # make sure we get the EXIT_TESTSFAILED exit code
+ session.testsfailed += 1
+ coverage_passed = False
+
+
+def pytest_terminal_summary(terminalreporter, exitstatus):
+ global enable_coverage
+ global coverage_values
+ global coverage_passed
+ global no_full_cov
+
+ if not enable_coverage:
+ return
+
+ terminalreporter.write('\n')
+ if not coverage_passed:
+ markup = {'red': True, 'bold': True}
+ msg = "FAIL: Full test coverage not reached!\n"
+ terminalreporter.write(msg, **markup)
+
+ for name in sorted(coverage_values.keys()):
+ msg = 'Coverage for {}: {:.2f}%\n'.format(name, coverage_values[name][0])
+ if coverage_values[name][0] < 100:
+ markup = {'red': True, 'bold': True}
+ for s, v in sorted(coverage_values[name][1]):
+ if v < 100:
+ msg += ' {}: {:.2f}%\n'.format(s, v)
+ else:
+ markup = {'green': True}
+ terminalreporter.write(msg, **markup)
+ else:
+ msg = 'SUCCESS: Full test coverage reached in modules and files:\n'
+ msg += '{}\n\n'.format('\n'.join(pytest.config.option.full_cov))
+ terminalreporter.write(msg, green=True)
+
+ msg = '\nExcluded files:\n'
+ for s in sorted(no_full_cov):
+ msg += " {}\n".format(s)
+ terminalreporter.write(msg)
diff --git a/test/mitmproxy/__init__.py b/test/mitmproxy/__init__.py
index 28dc133f..6f114e18 100644
--- a/test/mitmproxy/__init__.py
+++ b/test/mitmproxy/__init__.py
@@ -3,5 +3,4 @@ import logging
logging.getLogger("hyper").setLevel(logging.WARNING)
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("passlib").setLevel(logging.WARNING)
-logging.getLogger("PIL").setLevel(logging.WARNING)
logging.getLogger("tornado").setLevel(logging.WARNING)
diff --git a/test/mitmproxy/contentviews/image/test_image_parser.py b/test/mitmproxy/contentviews/image/test_image_parser.py
index 3c8bfdf7..3cb44ca6 100644
--- a/test/mitmproxy/contentviews/image/test_image_parser.py
+++ b/test/mitmproxy/contentviews/image/test_image_parser.py
@@ -80,7 +80,7 @@ def test_parse_png(filename, metadata):
# check comment
"mitmproxy/data/image_parser/hopper.gif": [
('Format', 'Compuserve GIF'),
- ('version', 'GIF89a'),
+ ('Version', 'GIF89a'),
('Size', '128 x 128 px'),
('background', '0'),
('comment', "b'File written by Adobe Photoshop\\xa8 4.0'")
@@ -88,7 +88,7 @@ def test_parse_png(filename, metadata):
# check background
"mitmproxy/data/image_parser/chi.gif": [
('Format', 'Compuserve GIF'),
- ('version', 'GIF89a'),
+ ('Version', 'GIF89a'),
('Size', '320 x 240 px'),
('background', '248'),
('comment', "b'Created with GIMP'")
@@ -96,7 +96,7 @@ def test_parse_png(filename, metadata):
# check working with color table
"mitmproxy/data/image_parser/iss634.gif": [
('Format', 'Compuserve GIF'),
- ('version', 'GIF89a'),
+ ('Version', 'GIF89a'),
('Size', '245 x 245 px'),
('background', '0')
],
diff --git a/test/mitmproxy/contentviews/image/test_view.py b/test/mitmproxy/contentviews/image/test_view.py
index ee2f9eaa..34f655a1 100644
--- a/test/mitmproxy/contentviews/image/test_view.py
+++ b/test/mitmproxy/contentviews/image/test_view.py
@@ -9,9 +9,11 @@ def test_view_image():
"mitmproxy/data/image.png",
"mitmproxy/data/image.gif",
"mitmproxy/data/all.jpeg",
- "mitmproxy/data/image.ico"
+ # https://bugs.python.org/issue21574
+ # "mitmproxy/data/image.ico",
]:
with open(tutils.test_data.path(img), "rb") as f:
- assert v(f.read())
+ viewname, lines = v(f.read())
+ assert img.split(".")[-1].upper() in viewname
- assert not v(b"flibble")
+ assert v(b"flibble") == ('Unknown Image', [[('header', 'Image Format: '), ('text', 'unknown')]])
diff --git a/test/mitmproxy/contentviews/test_auto.py b/test/mitmproxy/contentviews/test_auto.py
index a077affa..2ff43139 100644
--- a/test/mitmproxy/contentviews/test_auto.py
+++ b/test/mitmproxy/contentviews/test_auto.py
@@ -30,6 +30,18 @@ def test_view_auto():
)
assert f[0].startswith("XML")
+ f = v(
+ b"<svg></svg>",
+ headers=http.Headers(content_type="image/svg+xml")
+ )
+ assert f[0].startswith("XML")
+
+ f = v(
+ b"verybinary",
+ headers=http.Headers(content_type="image/new-magic-image-format")
+ )
+ assert f[0] == "Unknown Image"
+
f = v(b"\xFF" * 30)
assert f[0] == "Hex"
diff --git a/test/mitmproxy/proxy/protocol/test_http2.py b/test/mitmproxy/proxy/protocol/test_http2.py
index f5d9259d..cede0b80 100644
--- a/test/mitmproxy/proxy/protocol/test_http2.py
+++ b/test/mitmproxy/proxy/protocol/test_http2.py
@@ -23,8 +23,6 @@ logging.getLogger("hyper.packages.hpack.hpack").setLevel(logging.WARNING)
logging.getLogger("requests.packages.urllib3.connectionpool").setLevel(logging.WARNING)
logging.getLogger("passlib.utils.compat").setLevel(logging.WARNING)
logging.getLogger("passlib.registry").setLevel(logging.WARNING)
-logging.getLogger("PIL.Image").setLevel(logging.WARNING)
-logging.getLogger("PIL.PngImagePlugin").setLevel(logging.WARNING)
# inspect the log: