repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/openstack/lifecyclemanagement.py
diagrams/openstack/lifecyclemanagement.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _OpenStack class _Lifecyclemanagement(_OpenStack): _type = "lifecyclemanagement" _icon_dir = "resources/openstack/lifecyclemanagement" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/openstack/adjacentenablers.py
diagrams/openstack/adjacentenablers.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _OpenStack class _Adjacentenablers(_OpenStack): _type = "adjacentenablers" _icon_dir = "resources/openstack/adjacentenablers" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/openstack/nfv.py
diagrams/openstack/nfv.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _OpenStack class _NFV(_OpenStack): _type = "nfv" _icon_dir = "resources/openstack/nfv" class Tacker(_NFV): _icon = "tacker.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/openstack/__init__.py
diagrams/openstack/__init__.py
""" Openstack provides a set of general OpenStack services. """ from diagrams import Node class _OpenStack(Node): _provider = "openstack" _icon_dir = "resources/openstack" fontcolor = "#ffffff" class OpenStack(_OpenStack): _icon = "openstack.png"
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/openstack/deployment.py
diagrams/openstack/deployment.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _OpenStack class _Deployment(_OpenStack): _type = "deployment" _icon_dir = "resources/openstack/deployment" class Ansible(_Deployment): _icon = "ansible.png" class Charms(_Deployment): _icon = "charms.png" class Chef(_Deployment): _icon = "chef.png" class Helm(_Deployment): _icon = "helm.png" class Kolla(_Deployment): _icon = "kolla.png" class Tripleo(_Deployment): _icon = "tripleo.png" # Aliases KollaAnsible = Kolla TripleO = Tripleo
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/openstack/frontend.py
diagrams/openstack/frontend.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _OpenStack class _Frontend(_OpenStack): _type = "frontend" _icon_dir = "resources/openstack/frontend" class Horizon(_Frontend): _icon = "horizon.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/openstack/billing.py
diagrams/openstack/billing.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _OpenStack class _Billing(_OpenStack): _type = "billing" _icon_dir = "resources/openstack/billing" class Cloudkitty(_Billing): _icon = "cloudkitty.png" # Aliases CloudKitty = Cloudkitty
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/format.py
diagrams/gis/format.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Format(_GIS): _type = "format" _icon_dir = "resources/gis/format" class Geopackage(_Format): _icon = "geopackage.png" class Geoparquet(_Format): _icon = "geoparquet.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/cli.py
diagrams/gis/cli.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Cli(_GIS): _type = "cli" _icon_dir = "resources/gis/cli" class Gdal(_Cli): _icon = "gdal.png" class Imposm(_Cli): _icon = "imposm.png" class Lastools(_Cli): _icon = "lastools.png" class Mapnik(_Cli): _icon = "mapnik.png" class Mdal(_Cli): _icon = "mdal.png" class Pdal(_Cli): _icon = "pdal.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/javascript.py
diagrams/gis/javascript.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Javascript(_GIS): _type = "javascript" _icon_dir = "resources/gis/javascript" class Cesium(_Javascript): _icon = "cesium.png" class Geostyler(_Javascript): _icon = "geostyler.png" class Keplerjs(_Javascript): _icon = "keplerjs.png" class Leaflet(_Javascript): _icon = "leaflet.png" class Maplibre(_Javascript): _icon = "maplibre.png" class OlExt(_Javascript): _icon = "ol-ext.png" class Openlayers(_Javascript): _icon = "openlayers.png" class Turfjs(_Javascript): _icon = "turfjs.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/organization.py
diagrams/gis/organization.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Organization(_GIS): _type = "organization" _icon_dir = "resources/gis/organization" class Osgeo(_Organization): _icon = "osgeo.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/java.py
diagrams/gis/java.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Java(_GIS): _type = "java" _icon_dir = "resources/gis/java" class Geotools(_Java): _icon = "geotools.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/python.py
diagrams/gis/python.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Python(_GIS): _type = "python" _icon_dir = "resources/gis/python" class Geopandas(_Python): _icon = "geopandas.png" class Pysal(_Python): _icon = "pysal.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/toolkit.py
diagrams/gis/toolkit.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Toolkit(_GIS): _type = "toolkit" _icon_dir = "resources/gis/toolkit" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/mobile.py
diagrams/gis/mobile.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Mobile(_GIS): _type = "mobile" _icon_dir = "resources/gis/mobile" class Mergin(_Mobile): _icon = "mergin.png" class Qfield(_Mobile): _icon = "qfield.png" class Smash(_Mobile): _icon = "smash.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/database.py
diagrams/gis/database.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Database(_GIS): _type = "database" _icon_dir = "resources/gis/database" class Postgis(_Database): _icon = "postgis.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/__init__.py
diagrams/gis/__init__.py
""" GIS provides a set of services for Geographic Information Systems provider. """ from diagrams import Node class _GIS(Node): _provider = "gis" _icon_dir = "resources/gis" fontcolor = "#2d3436"
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/desktop.py
diagrams/gis/desktop.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Desktop(_GIS): _type = "desktop" _icon_dir = "resources/gis/desktop" class Maptunik(_Desktop): _icon = "maptunik.png" class QGIS(_Desktop): _icon = "qgis.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/geocoding.py
diagrams/gis/geocoding.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Geocoding(_GIS): _type = "geocoding" _icon_dir = "resources/gis/geocoding" class Addok(_Geocoding): _icon = "addok.png" class Gisgraphy(_Geocoding): _icon = "gisgraphy.png" class Nominatim(_Geocoding): _icon = "nominatim.png" class Pelias(_Geocoding): _icon = "pelias.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/georchestra.py
diagrams/gis/georchestra.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Georchestra(_GIS): _type = "georchestra" _icon_dir = "resources/gis/georchestra" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/server.py
diagrams/gis/server.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Server(_GIS): _type = "server" _icon_dir = "resources/gis/server" class Actinia(_Server): _icon = "actinia.png" class Baremaps(_Server): _icon = "baremaps.png" class Deegree(_Server): _icon = "deegree.png" class G3WSuite(_Server): _icon = "g3w-suite.png" class Geohealthcheck(_Server): _icon = "geohealthcheck.png" class Geomapfish(_Server): _icon = "geomapfish.png" class Geomesa(_Server): _icon = "geomesa.png" class Geonetwork(_Server): _icon = "geonetwork.png" class Geonode(_Server): _icon = "geonode.png" class Georchestra(_Server): _icon = "georchestra.png" class Geoserver(_Server): _icon = "geoserver.png" class Geowebcache(_Server): _icon = "geowebcache.png" class Kepler(_Server): _icon = "kepler.png" class Mapproxy(_Server): _icon = "mapproxy.png" class Mapserver(_Server): _icon = "mapserver.png" class Mapstore(_Server): _icon = "mapstore.png" class Mviewer(_Server): _icon = "mviewer.png" class Pg_Tileserv(_Server): _icon = "pg_tileserv.png" class Pycsw(_Server): _icon = "pycsw.png" class Pygeoapi(_Server): _icon = "pygeoapi.png" class QGISServer(_Server): _icon = "qgis-server.png" class Zooproject(_Server): _icon = "zooproject.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/routing.py
diagrams/gis/routing.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Routing(_GIS): _type = "routing" _icon_dir = "resources/gis/routing" class Graphhopper(_Routing): _icon = "graphhopper.png" class Osrm(_Routing): _icon = "osrm.png" class Pgrouting(_Routing): _icon = "pgrouting.png" class Valhalla(_Routing): _icon = "valhalla.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/data.py
diagrams/gis/data.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Data(_GIS): _type = "data" _icon_dir = "resources/gis/data" class BAN(_Data): _icon = "ban.png" class Here(_Data): _icon = "here.png" class IGN(_Data): _icon = "ign.png" class Openstreetmap(_Data): _icon = "openstreetmap.png" class Overturemaps(_Data): _icon = "overturemaps.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/ogc.py
diagrams/gis/ogc.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _OGC(_GIS): _type = "ogc" _icon_dir = "resources/gis/ogc" class OGC(_OGC): _icon = "ogc.png" class WFS(_OGC): _icon = "wfs.png" class WMS(_OGC): _icon = "wms.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mingrammer/diagrams
https://github.com/mingrammer/diagrams/blob/072474aa2a7d24cd074b2e1a61d0b714c3daa945/diagrams/gis/cplusplus.py
diagrams/gis/cplusplus.py
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _GIS class _Cplusplus(_GIS): _type = "cplusplus" _icon_dir = "resources/gis/cplusplus" class Mapnik(_Cplusplus): _icon = "mapnik.png" # Aliases
python
MIT
072474aa2a7d24cd074b2e1a61d0b714c3daa945
2026-01-04T14:39:58.534150Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/release/selftest.py
release/selftest.py
""" This addons is used for binaries to perform a minimal selftest. Use like so: mitmdump -s selftest.py -p 0 """ import asyncio import logging import ssl import sys from pathlib import Path from mitmproxy import ctx from mitmproxy.utils import asyncio_utils def load(_): # force a random port ctx.options.listen_port = 0 try: ctx.options.web_open_browser = False except KeyError: pass def running(): asyncio_utils.create_task( make_request(), name="selftest", keep_ref=True, ) async def make_request(): try: cafile = Path(ctx.options.confdir).expanduser() / "mitmproxy-ca.pem" while not cafile.exists(): await asyncio.sleep(0.01) ssl_ctx = ssl.create_default_context(cafile=cafile) port = ctx.master.addons.get("proxyserver").listen_addrs()[0][1] reader, writer = await asyncio.open_connection("127.0.0.1", port, ssl=ssl_ctx) writer.write(b"GET / HTTP/1.1\r\nHost: mitm.it\r\nConnection: close\r\n\r\n") await writer.drain() resp = await reader.read() if b"This page is served by your local mitmproxy instance" not in resp: raise RuntimeError(resp) logging.info("Self-test successful.") ctx.master.shutdown() except Exception as e: print(f"{e!r}") sys.exit(1)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/release/build.py
release/build.py
#!/usr/bin/env python3 from __future__ import annotations import hashlib import os import platform import re import shutil import subprocess import tarfile import urllib.request import warnings import zipfile from datetime import datetime from pathlib import Path import click import cryptography.fernet here = Path(__file__).absolute().parent TEMP_DIR = here / "build" DIST_DIR = here / "dist" @click.group(chain=True) @click.option("--dirty", is_flag=True) def cli(dirty): if dirty: print("Keeping temporary files.") else: print("Cleaning up temporary files...") if TEMP_DIR.exists(): shutil.rmtree(TEMP_DIR) if DIST_DIR.exists(): shutil.rmtree(DIST_DIR) TEMP_DIR.mkdir() DIST_DIR.mkdir() @cli.command() def wheel(): """Build the wheel for PyPI.""" print("Building wheel...") subprocess.check_call( [ "python", "-m", "build", "--outdir", DIST_DIR, ] ) if os.environ.get("GITHUB_REF", "").startswith("refs/tags/"): ver = version() # assert for tags that the version matches the tag. else: ver = "*" (whl,) = DIST_DIR.glob(f"mitmproxy-{ver}-py3-none-any.whl") print(f"Found wheel package: {whl}") class ZipFile2(zipfile.ZipFile): # ZipFile and tarfile have slightly different APIs. Let's fix that. def add(self, name: str, arcname: str) -> None: return self.write(name, arcname) def __enter__(self) -> ZipFile2: return self @property def name(self) -> str: assert self.filename return self.filename def archive(path: Path) -> tarfile.TarFile | ZipFile2: if platform.system() == "Windows": return ZipFile2(path.with_name(f"{path.name}.zip"), "w") else: return tarfile.open(path.with_name(f"{path.name}.tar.gz"), "w:gz") def version() -> str: if ref := os.environ.get("GITHUB_REF", ""): if ref.startswith("refs/tags/") and not ref.startswith("refs/tags/v"): raise AssertionError(f"Unexpected tag: {ref}") return ( ref.removeprefix("refs/heads/") .removeprefix("refs/pull/") .removeprefix("refs/tags/v") .replace("/", "-") ) else: return os.environ.get("BUILD_VERSION", "dev") def operating_system() -> str: match platform.system(): case "Windows": system = "windows" case "Linux": system = "linux" case "Darwin": system = "macos" case other: warnings.warn("Unexpected system.") system = other match platform.machine(): case "AMD64" | "x86_64": machine = "x86_64" case "arm64": machine = "arm64" case other: warnings.warn("Unexpected platform.") machine = other return f"{system}-{machine}" def _pyinstaller(specfile: str) -> None: print(f"Invoking PyInstaller with {specfile}...") subprocess.check_call( [ "pyinstaller", "--clean", "--workpath", TEMP_DIR / "pyinstaller/temp", "--distpath", TEMP_DIR / "pyinstaller/out", specfile, ], cwd=here / "specs", ) @cli.command() def standalone_binaries(): """Windows and Linux: Build the standalone binaries generated with PyInstaller""" with archive(DIST_DIR / f"mitmproxy-{version()}-{operating_system()}") as f: _pyinstaller("standalone.spec") _test_binaries(TEMP_DIR / "pyinstaller/out") for tool in ["mitmproxy", "mitmdump", "mitmweb"]: executable = TEMP_DIR / "pyinstaller/out" / tool if platform.system() == "Windows": executable = executable.with_suffix(".exe") f.add(str(executable), str(executable.name)) print(f"Packed {f.name!r}.") @cli.command() @click.option("--keychain") @click.option("--team-id") @click.option("--apple-id") @click.option("--password") def macos_app( keychain: str | None, team_id: str | None, apple_id: str | None, password: str | None, ) -> None: """ macOS: Build into mitmproxy.app. If you do not specify options, notarization is skipped. """ _pyinstaller("onedir.spec") _test_binaries(TEMP_DIR / "pyinstaller/out/mitmproxy.app/Contents/MacOS") if keychain: assert isinstance(team_id, str) assert isinstance(apple_id, str) assert isinstance(password, str) # Notarize the app bundle. subprocess.check_call( [ "xcrun", "notarytool", "store-credentials", "AC_PASSWORD", *(["--keychain", keychain]), *(["--team-id", team_id]), *(["--apple-id", apple_id]), *(["--password", password]), ] ) subprocess.check_call( [ "ditto", "-c", "-k", "--keepParent", TEMP_DIR / "pyinstaller/out/mitmproxy.app", TEMP_DIR / "notarize.zip", ] ) subprocess.check_call( [ "xcrun", "notarytool", "submit", TEMP_DIR / "notarize.zip", *(["--keychain", keychain]), *(["--keychain-profile", "AC_PASSWORD"]), "--wait", ] ) # 2023: it's not possible to staple to unix executables. # subprocess.check_call([ # "xcrun", # "stapler", # "staple", # TEMP_DIR / "pyinstaller/out/mitmproxy.app", # ]) else: warnings.warn("Notarization skipped.") with archive(DIST_DIR / f"mitmproxy-{version()}-{operating_system()}") as f: f.add(str(TEMP_DIR / "pyinstaller/out/mitmproxy.app"), "mitmproxy.app") print(f"Packed {f.name!r}.") def _ensure_pyinstaller_onedir(): if not (TEMP_DIR / "pyinstaller/out/onedir").exists(): _pyinstaller("onedir.spec") _test_binaries(TEMP_DIR / "pyinstaller/out/onedir") def _test_binaries(binary_directory: Path) -> None: for tool in ["mitmproxy", "mitmdump", "mitmweb"]: executable = binary_directory / tool if platform.system() == "Windows": executable = executable.with_suffix(".exe") print(f"> {tool} --version") subprocess.check_call([executable, "--version"]) if tool == "mitmproxy": continue # requires a TTY, which we don't have here. print(f"> {tool} -s selftest.py") subprocess.check_call([executable, "-s", here / "selftest.py"]) @cli.command() def msix_installer(): """Windows: Build the MSIX installer for the Windows Store.""" _ensure_pyinstaller_onedir() shutil.copytree( TEMP_DIR / "pyinstaller/out/onedir", TEMP_DIR / "msix", dirs_exist_ok=True, ) shutil.copytree(here / "windows-installer", TEMP_DIR / "msix", dirs_exist_ok=True) manifest = TEMP_DIR / "msix/AppxManifest.xml" app_version = version() if not re.match(r"\d+\.\d+\.\d+", app_version): app_version = ( datetime.now() .strftime("%y%m.%d.%H%M") .replace(".0", ".") .replace(".0", ".") .replace(".0", ".") ) manifest.write_text(manifest.read_text().replace("1.2.3", app_version)) makeappx_exe = ( Path(os.environ["ProgramFiles(x86)"]) / "Windows Kits/10/App Certification Kit/makeappx.exe" ) subprocess.check_call( [ makeappx_exe, "pack", "/d", TEMP_DIR / "msix", "/p", DIST_DIR / f"mitmproxy-{version()}-installer.msix", ], ) assert (DIST_DIR / f"mitmproxy-{version()}-installer.msix").exists() @cli.command() def installbuilder_installer(): """Windows: Build the InstallBuilder installer.""" _ensure_pyinstaller_onedir() IB_VERSION = "23.4.0" IB_SETUP_SHA256 = "e4ff212ed962f9e0030d918b8a6e4d6dd8a9adc8bf8bc1833459351ee649eff3" IB_DIR = here / "installbuilder" IB_SETUP = IB_DIR / "setup" / f"{IB_VERSION}-installer.exe" IB_CLI = Path( rf"C:\Program Files\InstallBuilder Enterprise {IB_VERSION}\bin\builder-cli.exe" ) IB_LICENSE = IB_DIR / "license.xml" if not IB_LICENSE.exists(): print("Decrypt InstallBuilder license...") f = cryptography.fernet.Fernet(os.environ["CI_BUILD_KEY"].encode()) with ( open(IB_LICENSE.with_suffix(".xml.enc"), "rb") as infile, open(IB_LICENSE, "wb") as outfile, ): outfile.write(f.decrypt(infile.read())) if not IB_CLI.exists(): if not IB_SETUP.exists(): url = ( f"https://github.com/mitmproxy/installbuilder-mirror/releases/download/" f"{IB_VERSION}/installbuilder-enterprise-{IB_VERSION}-windows-x64-installer.exe" ) print(f"Downloading InstallBuilder from {url}...") def report(block, blocksize, total): done = block * blocksize if round(100 * done / total) != round(100 * (done - blocksize) / total): print(f"Downloading... {round(100 * done / total)}%") tmp = IB_SETUP.with_suffix(".tmp") urllib.request.urlretrieve( url, tmp, reporthook=report, ) tmp.rename(IB_SETUP) ib_setup_hash = hashlib.sha256() with IB_SETUP.open("rb") as fp: while True: data = fp.read(65_536) if not data: break ib_setup_hash.update(data) if ib_setup_hash.hexdigest() != IB_SETUP_SHA256: # pragma: no cover raise RuntimeError( f"InstallBuilder hashes don't match: {ib_setup_hash.hexdigest()}" ) print("Install InstallBuilder...") subprocess.run( [IB_SETUP, "--mode", "unattended", "--unattendedmodeui", "none"], check=True ) assert IB_CLI.is_file() print("Run InstallBuilder...") subprocess.check_call( [ IB_CLI, "build", str(IB_DIR / "mitmproxy.xml"), "windows-x64", "--license", str(IB_LICENSE), "--setvars", f"project.version={version()}", "--verbose", ], cwd=IB_DIR, ) installer = DIST_DIR / f"mitmproxy-{version()}-windows-x64-installer.exe" assert installer.exists() # unify filenames installer = installer.rename( installer.with_name(installer.name.replace("x64", "x86_64")) ) print("Run installer...") subprocess.run( [installer, "--mode", "unattended", "--unattendedmodeui", "none"], check=True ) _test_binaries(Path(r"C:\Program Files\mitmproxy\bin")) if __name__ == "__main__": cli()
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/release/deploy.py
release/deploy.py
#!/usr/bin/env python3 import os import subprocess from pathlib import Path # Security: No third-party dependencies here! root = Path(__file__).absolute().parent.parent if __name__ == "__main__": ref = os.environ["GITHUB_REF"] branch: str | None = None tag: str | None = None if ref.startswith("refs/heads/"): branch = ref.replace("refs/heads/", "") elif ref.startswith("refs/tags/"): if not ref.startswith("refs/tags/v"): raise AssertionError(f"Unexpected tag: {ref}") tag = ref.replace("refs/tags/v", "") else: raise AssertionError # Upload binaries (be it release or snapshot) if tag: upload_dir = tag else: upload_dir = f"branches/{branch}" # Ideally we could have R2 pull from S3 automatically, but that's not possible yet. So we upload to both. print(f"Uploading binaries to snapshots.mitmproxy.org/{upload_dir}...") subprocess.check_call( [ "aws", "s3", "sync", "--delete", *("--acl", "public-read"), *("--exclude", "*.msix"), root / "release/dist", f"s3://snapshots.mitmproxy.org/{upload_dir}", ] ) if tag: # We can't scope R2 tokens, so they are only exposed in the deploy env. print(f"Uploading binaries to downloads.mitmproxy.org/{upload_dir}...") subprocess.check_call( [ "aws", "s3", "sync", "--delete", *("--acl", "public-read"), *("--exclude", "*.msix"), *( "--endpoint-url", f"https://{os.environ['R2_ACCOUNT_ID']}.r2.cloudflarestorage.com", ), root / "release/dist", f"s3://downloads/{upload_dir}", ], env={ **os.environ, "AWS_REGION": "auto", "AWS_DEFAULT_REGION": "auto", "AWS_ACCESS_KEY_ID": os.environ["R2_ACCESS_KEY_ID"], "AWS_SECRET_ACCESS_KEY": os.environ["R2_SECRET_ACCESS_KEY"], }, ) # Upload releases to PyPI if tag: print(f"Uploading wheel to PyPI...") (whl,) = root.glob("release/dist/mitmproxy-*-py3-none-any.whl") subprocess.check_call(["twine", "upload", whl]) # Upload docs def upload_docs(path: str, src: Path = root / "docs/public"): subprocess.check_call(["aws", "configure", "set", "preview.cloudfront", "true"]) subprocess.check_call( [ "aws", "s3", "sync", "--delete", "--acl", "public-read", src, f"s3://docs.mitmproxy.org{path}", ] ) subprocess.check_call( [ "aws", "cloudfront", "create-invalidation", "--distribution-id", "E1TH3USJHFQZ5Q", "--paths", f"{path}/*", ] ) if branch == "main": print(f"Uploading dev docs...") upload_docs("/dev") if tag: print(f"Uploading release docs...") upload_docs("/stable") upload_docs(f"/archive/v{tag.split('.')[0]}", src=root / "docs/archive")
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/release/deploy-microsoft-store.py
release/deploy-microsoft-store.py
#!/usr/bin/env python3 """ This script submits a single MSIX installer to the Microsoft Store. The client_secret will expire after 24 months and needs to be recreated (see docstring below). References: - https://docs.microsoft.com/en-us/windows/uwp/monetize/manage-app-submissions - https://docs.microsoft.com/en-us/windows/uwp/monetize/python-code-examples-for-the-windows-store-submission-api - https://docs.microsoft.com/en-us/windows/uwp/monetize/python-code-examples-for-submissions-game-options-and-trailers """ import http.client import json import os import sys import tempfile import urllib.parse from zipfile import ZipFile # Security: No third-party dependencies here! assert ( os.environ["GITHUB_REF"].startswith("refs/tags/") or os.environ["GITHUB_REF"] == "refs/heads/citest" ) app_id = os.environ["MSFT_APP_ID"] """ The public application ID / product ID of the app. For https://www.microsoft.com/store/productId/9NWNDLQMNZD7, the app id is 9NWNDLQMNZD7. """ app_flight = os.environ.get("MSFT_APP_FLIGHT", "") """ The application flight we want to target. This is useful to deploy ci test builds to a subset of users. """ tenant_id = os.environ["MSFT_TENANT_ID"] """ The tenant ID for the Azure AD application. https://partner.microsoft.com/en-us/dashboard/account/v3/usermanagement """ client_id = os.environ["MSFT_CLIENT_ID"] """ The client ID for the Azure AD application. https://partner.microsoft.com/en-us/dashboard/account/v3/usermanagement """ client_secret = os.environ["MSFT_CLIENT_SECRET"] """ The client secret. Expires every 24 months and needs to be recreated at https://partner.microsoft.com/en-us/dashboard/account/v3/usermanagement or at https://portal.azure.com/ -> App registrations -> Certificates & Secrets -> Client secrets. (we only need to update the secret, the "Secret ID" can be ignored) """ try: _, msi_file = sys.argv except ValueError: print(f"Usage: {sys.argv[0]} installer.msix") sys.exit(1) if app_flight: app_id = f"{app_id}/flights/{app_flight}" pending_submission = "pendingFlightSubmission" packages = "flightPackages" else: pending_submission = "pendingApplicationSubmission" packages = "applicationPackages" print("Obtaining auth token...") auth = http.client.HTTPSConnection("login.microsoftonline.com") auth.request( "POST", f"/{tenant_id}/oauth2/token", body=urllib.parse.urlencode( { "grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret, "resource": "https://manage.devcenter.microsoft.com", } ), headers={"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"}, ) token = json.loads(auth.getresponse().read())["access_token"] auth.close() headers = { "Authorization": f"Bearer {token}", "Content-type": "application/json", "User-Agent": "Python/mitmproxy", } def request(method: str, path: str, body: str = "") -> bytes: print(f"{method} {path}") conn.request(method, path, body, headers=headers) resp = conn.getresponse() data = resp.read() print(f"{resp.status} {resp.reason}") # noinspection PyUnreachableCode if False: assert "CI" not in os.environ # This contains sensitive data such as the fileUploadUrl, so don't print it in production. print(data.decode(errors="ignore")) assert 200 <= resp.status < 300 return data print("Getting app info...") conn = http.client.HTTPSConnection("manage.devcenter.microsoft.com") # print(request("GET", f"/v1.0/my/applications/{app_id}/listflights")) app_info = json.loads(request("GET", f"/v1.0/my/applications/{app_id}")) if pending_submission in app_info: print("Deleting pending submission...") request( "DELETE", f"/v1.0/my/applications/{app_id}/submissions/{app_info[pending_submission]['id']}", ) print("Creating new submission...") submission = json.loads(request("POST", f"/v1.0/my/applications/{app_id}/submissions")) print("Updating submission...") # Mark all existing packages for deletion. for package in submission[packages]: package["fileStatus"] = "PendingDelete" submission[packages].append( { "fileName": f"installer.msix", "fileStatus": "PendingUpload", "minimumDirectXVersion": "None", "minimumSystemRam": "None", } ) request( "PUT", f"/v1.0/my/applications/{app_id}/submissions/{submission['id']}", json.dumps(submission), ) conn.close() print(f"Zipping {msi_file}...") with tempfile.TemporaryFile() as zipfile: with ZipFile(zipfile, "w") as f: f.write(msi_file, f"installer.msix") zip_size = zipfile.tell() zipfile.seek(0) print("Uploading zip file...") host, _, path = submission["fileUploadUrl"].removeprefix("https://").partition("/") upload = http.client.HTTPSConnection(host) upload.request( "PUT", "/" + path, zipfile, { "x-ms-blob-type": "BlockBlob", "x-ms-version": "2019-12-12", "Content-Length": str(zip_size), }, ) resp = upload.getresponse() resp.read() print(resp.status, resp.reason) assert 200 <= resp.status < 300 upload.close() print("Publishing submission...") # previous connection has timed out during upload. conn = http.client.HTTPSConnection("manage.devcenter.microsoft.com") request("POST", f"/v1.0/my/applications/{app_id}/submissions/{submission['id']}/commit") # We could wait until it's published here, but CI is billed by the minute. # resp = request("GET", f"/v1.0/my/applications/{app_id}/submissions/{submission['id']}/status") conn.close()
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/release/release.py
release/release.py
#!/usr/bin/env -S python3 -u import datetime import http.client import json import os import re import subprocess import sys import time from pathlib import Path # Security: No third-party dependencies here! root = Path(__file__).absolute().parent.parent def get(url: str) -> http.client.HTTPResponse: assert url.startswith("https://") host, path = re.split(r"(?=/)", url.removeprefix("https://"), maxsplit=1) conn = http.client.HTTPSConnection(host) conn.request("GET", path, headers={"User-Agent": "mitmproxy/release-bot"}) resp = conn.getresponse() print(f"HTTP {resp.status} {resp.reason}") return resp def get_json(url: str) -> dict: resp = get(url) body = resp.read() try: return json.loads(body) except Exception as e: raise RuntimeError(f"{resp.status=} {body=}") from e if __name__ == "__main__": version = sys.argv[1] assert re.match(r"^\d+\.\d+\.\d+$", version) major_version = int(version.split(".")[0]) skip_branch_status_check = sys.argv[2] == "true" # changing this is useful for testing on a fork. repo = os.environ.get("GITHUB_REPOSITORY", "mitmproxy/mitmproxy") print(f"{version=} {skip_branch_status_check=} {repo=}") branch = subprocess.run( ["git", "branch", "--show-current"], cwd=root, check=True, capture_output=True, text=True, ).stdout.strip() print("➡️ Working dir clean?") assert not subprocess.run(["git", "status", "--porcelain"]).stdout if skip_branch_status_check: print(f"⚠️ Skipping status check for {branch}.") else: print(f"➡️ CI is passing for {branch}?") assert ( get_json(f"https://api.github.com/repos/{repo}/commits/{branch}/status")[ "state" ] == "success" ) print("➡️ Updating CHANGELOG.md...") changelog = root / "CHANGELOG.md" date = datetime.date.today().strftime("%d %B %Y") title = f"## {date}: mitmproxy {version}" cl = changelog.read_text("utf8") assert title not in cl cl, ok = re.subn(r"(?<=## Unreleased: mitmproxy next)", f"\n\n\n{title}", cl) assert ok == 1 changelog.write_text(cl, "utf8") print("➡️ Updating web assets...") subprocess.run(["npm", "ci"], cwd=root / "web", check=True, capture_output=True) subprocess.run( ["npm", "run", "ci-build-release"], cwd=root / "web", check=True, ) subprocess.run( ["git", "add", "--all", f"mitmproxy/tools/web"], cwd=root, capture_output=True ) print("➡️ Updating version...") version_py = root / "mitmproxy" / "version.py" ver = version_py.read_text("utf8") ver, ok = re.subn(r'(?<=VERSION = ")[^"]+', version, ver) assert ok == 1 version_py.write_text(ver, "utf8") print("➡️ Do release commit...") subprocess.run( ["git", "config", "user.email", "noreply@mitmproxy.org"], cwd=root, check=True ) subprocess.run( ["git", "config", "user.name", "mitmproxy release bot"], cwd=root, check=True ) subprocess.run( ["git", "commit", "-a", "-m", f"mitmproxy {version}"], cwd=root, check=True ) tag_name = f"v{version}" subprocess.run(["git", "tag", tag_name], cwd=root, check=True) release_sha = subprocess.run( ["git", "rev-parse", "HEAD"], cwd=root, check=True, capture_output=True, text=True, ).stdout.strip() if branch == "main": print("➡️ Bump version...") next_dev_version = f"{major_version + 1}.0.0.dev" ver, ok = re.subn(r'(?<=VERSION = ")[^"]+', next_dev_version, ver) assert ok == 1 version_py.write_text(ver, "utf8") print("➡️ Reopen main for development...") subprocess.run( ["git", "commit", "-a", "-m", f"reopen main for development"], cwd=root, check=True, ) print("➡️ Pushing...") subprocess.run( ["git", "push", "--atomic", "origin", branch, tag_name], cwd=root, check=True ) print("➡️ Creating release on GitHub...") subprocess.run( [ "gh", "release", "create", tag_name, "--title", f"mitmproxy {version}", "--notes-file", "release/github-release-notes.txt", ], cwd=root, check=True, ) print("➡️ Dispatching release workflow...") subprocess.run( ["gh", "workflow", "run", "main.yml", "--ref", tag_name], cwd=root, check=True ) print("") print("✅ CI is running now.") while True: print("⌛ Waiting for CI...") workflows = get_json( f"https://api.github.com/repos/{repo}/actions/runs?head_sha={release_sha}" )["workflow_runs"] all_done = True if not workflows: all_done = False # we expect to have at least one workflow. for workflow in workflows: if workflow["status"] != "completed": all_done = False if workflow["status"] == "waiting": print(f"⚠️ CI is waiting for approval: {workflow['html_url']}") if all_done: for workflow in workflows: if workflow["conclusion"] != "success": print(f"⚠️ {workflow['display_title']} workflow run failed.") break else: time.sleep(30) # relatively strict rate limits here. print("➡️ Checking GitHub Releases...") resp = get(f"https://api.github.com/repos/{repo}/releases/tags/{tag_name}") assert resp.status == 200 print("➡️ Checking PyPI...") pypi_data = get_json("https://pypi.org/pypi/mitmproxy/json") assert version in pypi_data["releases"] print("➡️ Checking docs archive...") resp = get(f"https://docs.mitmproxy.org/archive/v{major_version}/") assert resp.status == 200 print(f"➡️ Checking Docker ({version} tag)...") resp = get( f"https://hub.docker.com/v2/repositories/mitmproxy/mitmproxy/tags/{version}" ) assert resp.status == 200 if branch == "main": print("➡️ Checking Docker (latest tag)...") docker_latest_data = get_json( "https://hub.docker.com/v2/repositories/mitmproxy/mitmproxy/tags/latest" ) docker_last_updated = datetime.datetime.fromisoformat( docker_latest_data["last_updated"].replace("Z", "+00:00") ) print(f"Last update: {docker_last_updated.isoformat(timespec='minutes')}") assert docker_last_updated > datetime.datetime.now( datetime.UTC ) - datetime.timedelta(hours=2) print("") print("✅ All done. 🥳") print("")
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/filename_matching.py
test/filename_matching.py
#!/usr/bin/env python3 import glob import os import re import sys def check_src_files_have_test(): missing_test_files = [] excluded = [ "mitmproxy/contrib/", "mitmproxy/io/proto/", "mitmproxy/proxy/layers/http", "mitmproxy/test/", "mitmproxy/tools/", "mitmproxy/platform/", "mitmproxy/utils/pyinstaller/", ] src_files = glob.glob("mitmproxy/**/*.py", recursive=True) src_files = [f for f in src_files if os.path.basename(f) != "__init__.py"] src_files = [ f for f in src_files if not any(os.path.normpath(p) in f for p in excluded) ] for f in src_files: p = os.path.join("test", os.path.dirname(f), "test_" + os.path.basename(f)) if not os.path.isfile(p): missing_test_files.append((f, p)) return missing_test_files def check_test_files_have_src(): unknown_test_files = [] excluded = [ "test/mitmproxy/data/", "test/mitmproxy/net/data/", "/tservers.py", "/conftest.py", ] test_files = glob.glob("test/mitmproxy/**/*.py", recursive=True) test_files = [f for f in test_files if os.path.basename(f) != "__init__.py"] test_files = [ f for f in test_files if not any(os.path.normpath(p) in f for p in excluded) ] for f in test_files: p = os.path.join( re.sub("^test/", "", os.path.dirname(f)), re.sub("^test_", "", os.path.basename(f)), ) if not os.path.isfile(p): unknown_test_files.append((f, p)) return unknown_test_files def main(): exitcode = 0 missing_test_files = check_src_files_have_test() if missing_test_files: exitcode += 1 for f, p in sorted(missing_test_files): print(f"{f} MUST have a matching test file: {p}") unknown_test_files = check_test_files_have_src() if unknown_test_files: # TODO: enable this in the future # exitcode += 1 for f, p in sorted(unknown_test_files): print(f"{f} DOES NOT MATCH a source file! Expected to find: {p}") sys.exit(exitcode) if __name__ == "__main__": main()
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/conftest.py
test/conftest.py
from __future__ import annotations import asyncio import os import platform import socket import pytest from mitmproxy.utils import data skip_windows = pytest.mark.skipif(os.name == "nt", reason="Skipping due to Windows") skip_not_windows = pytest.mark.skipif( os.name != "nt", reason="Skipping due to not Windows" ) skip_not_linux = pytest.mark.skipif( platform.system() != "Linux", reason="Skipping due to not Linux" ) try: s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) s.bind(("::1", 0)) s.close() except OSError: no_ipv6 = True else: no_ipv6 = False skip_no_ipv6 = pytest.mark.skipif(no_ipv6, reason="Host has no IPv6 support") class EagerTaskCreationEventLoopPolicy(asyncio.DefaultEventLoopPolicy): def new_event_loop(self): loop = super().new_event_loop() loop.set_task_factory(asyncio.eager_task_factory) return loop @pytest.fixture(scope="session") def event_loop_policy(request): return EagerTaskCreationEventLoopPolicy() @pytest.fixture() def tdata(): return data.Data(__name__) class AsyncLogCaptureFixture: def __init__(self, caplog: pytest.LogCaptureFixture): self.caplog = caplog def set_level(self, level: int | str, logger: str | None = None) -> None: self.caplog.set_level(level, logger) async def await_log(self, text, timeout=2): await asyncio.sleep(0) for i in range(int(timeout / 0.01)): if text in self.caplog.text: return True else: await asyncio.sleep(0.01) raise AssertionError(f"Did not find {text!r} in log:\n{self.caplog.text}") def clear(self) -> None: self.caplog.clear() @pytest.fixture def caplog_async(caplog): return AsyncLogCaptureFixture(caplog)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/individual_coverage.py
test/individual_coverage.py
#!/usr/bin/env python3 import ast import asyncio import fnmatch import os import re import subprocess import sys import tomllib from pathlib import Path root = Path(__file__).parent.parent.absolute() async def main(): with open("pyproject.toml", "rb") as f: data = tomllib.load(f) exclude = re.compile( "|".join( f"({fnmatch.translate(x)})" for x in data["tool"]["pytest"]["individual_coverage"]["exclude"] ) ) sem = asyncio.Semaphore(os.cpu_count() or 1) async def run_tests(f: Path, should_fail: bool) -> None: if f.name == "__init__.py": mod = ast.parse(f.read_text()) full_cov_on_import = all( isinstance(stmt, (ast.ImportFrom, ast.Import, ast.Assign)) for stmt in mod.body ) if full_cov_on_import: if should_fail: raise RuntimeError( f"Remove {f} from tool.pytest.individual_coverage in pyproject.toml." ) else: print(f"{f}: skip __init__.py file without logic") return test_file = Path("test") / f.parent.with_name(f"test_{f.parent.name}.py") else: test_file = Path("test") / f.with_name(f"test_{f.name}") coverage_file = f".coverage-{str(f).replace('/', '-')}" async with sem: try: proc = await asyncio.create_subprocess_exec( "pytest", "-qq", "--disable-pytest-warnings", "--cov", str(f.with_suffix("")).replace("/", "."), "--cov-fail-under", "100", "--cov-report", "term-missing:skip-covered", test_file, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={ "COVERAGE_FILE": coverage_file, **os.environ, }, ) stdout, stderr = await asyncio.wait_for(proc.communicate(), 60) except TimeoutError: raise RuntimeError(f"{f}: timeout") finally: Path(coverage_file).unlink(missing_ok=True) if should_fail: if proc.returncode != 0: print(f"{f}: excluded") else: raise RuntimeError( f"{f} is now fully covered by {test_file}. Remove it from tool.pytest.individual_coverage in pyproject.toml." ) else: if proc.returncode == 0: print(f"{f}: ok") else: raise RuntimeError( f"{f} is not fully covered by {test_file}:\n{stdout.decode(errors='ignore')}\n{stderr.decode(errors='ignore')}" ) tasks = [] for f in (root / "mitmproxy").glob("**/*.py"): f = f.relative_to(root) if len(sys.argv) > 1 and sys.argv[1] not in str(f): continue if f.name == "__init__.py" and f.stat().st_size == 0: print(f"{f}: empty") continue tasks.append( asyncio.create_task(run_tests(f, should_fail=exclude.match(str(f)))) ) exit_code = 0 for task in asyncio.as_completed(tasks): try: await task except RuntimeError as e: print(e) exit_code = 1 sys.exit(exit_code) if __name__ == "__main__": asyncio.run(main())
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/__init__.py
test/__init__.py
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/bench/benchmark.py
test/bench/benchmark.py
import asyncio import cProfile import logging from mitmproxy import ctx class Benchmark: """ A simple profiler addon. """ def __init__(self): self.pr = cProfile.Profile() self.started = False self.resps = 0 self.reqs = 0 def request(self, f): self.reqs += 1 def response(self, f): self.resps += 1 async def procs(self): logging.error("starting benchmark") backend = await asyncio.create_subprocess_exec("devd", "-q", "-p", "10001", ".") traf = await asyncio.create_subprocess_exec( "wrk", "-c50", "-d5s", "http://localhost:%s/benchmark.py" % ctx.master.server.address[1], stdout=asyncio.subprocess.PIPE, ) stdout, _ = await traf.communicate() with open(ctx.options.benchmark_save_path + ".bench", mode="wb") as f: f.write(stdout) logging.error(f"Proxy saw {self.reqs} requests, {self.resps} responses") logging.error(stdout.decode("ascii")) backend.kill() ctx.master.shutdown() def load(self, loader): loader.add_option( "benchmark_save_path", str, "/tmp/profile", "Destination for the .prof and .bench result files", ) ctx.options.update( mode="reverse:http://devd.io:10001", ) self.pr.enable() def running(self): if not self.started: self.started = True self._task = asyncio.create_task(self.procs()) def done(self): self.pr.dump_stats(ctx.options.benchmark_save_path + ".prof") addons = [Benchmark()]
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/examples/__init__.py
test/examples/__init__.py
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/examples/test_examples.py
test/examples/test_examples.py
from mitmproxy import contentviews from mitmproxy.http import Headers from mitmproxy.test import taddons from mitmproxy.test import tflow from mitmproxy.test import tutils class TestScripts: def test_add_header(self, tdata): with taddons.context() as tctx: a = tctx.script(tdata.path("../examples/addons/anatomy2.py")) f = tflow.tflow() a.request(f) assert f.request.headers["myheader"] == "value" def test_custom_contentviews(self, tdata): with taddons.context() as tctx: tctx.script(tdata.path("../examples/addons/contentview.py")) swapcase = contentviews.registry["swapcase"] result = swapcase.prettify(b"<html>Test!</html>", contentviews.Metadata()) assert "tEST!" in result def test_modify_form(self, tdata): with taddons.context() as tctx: sc = tctx.script(tdata.path("../examples/addons/http-modify-form.py")) form_header = Headers(content_type="application/x-www-form-urlencoded") f = tflow.tflow(req=tutils.treq(headers=form_header)) sc.request(f) assert f.request.urlencoded_form["mitmproxy"] == "rocks" f.request.headers["content-type"] = "" sc.request(f) assert list(f.request.urlencoded_form.items()) == [("foo", "bar")] def test_modify_querystring(self, tdata): with taddons.context() as tctx: sc = tctx.script( tdata.path("../examples/addons/http-modify-query-string.py") ) f = tflow.tflow(req=tutils.treq(path="/search?q=term")) sc.request(f) assert f.request.query["mitmproxy"] == "rocks" f.request.path = "/" sc.request(f) assert f.request.query["mitmproxy"] == "rocks" def test_redirect_requests(self, tdata): with taddons.context() as tctx: sc = tctx.script(tdata.path("../examples/addons/http-redirect-requests.py")) f = tflow.tflow(req=tutils.treq(host="example.org")) sc.request(f) assert f.request.host == "mitmproxy.org" def test_send_reply_from_proxy(self, tdata): with taddons.context() as tctx: sc = tctx.script(tdata.path("../examples/addons/http-reply-from-proxy.py")) f = tflow.tflow(req=tutils.treq(host="example.com", port=80)) sc.request(f) assert f.response.content == b"Hello World"
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_addonmanager.py
test/mitmproxy/test_addonmanager.py
import pytest from mitmproxy import addonmanager from mitmproxy import addons from mitmproxy import command from mitmproxy import exceptions from mitmproxy import hooks from mitmproxy import master from mitmproxy import options from mitmproxy.addonmanager import Loader from mitmproxy.proxy.layers.http import HttpRequestHook from mitmproxy.proxy.layers.http import HttpResponseHook from mitmproxy.test import taddons from mitmproxy.test import tflow class TAddon: def __init__(self, name, addons=None): self.name = name self.response = True self.running_called = False if addons: self.addons = addons @command.command("test.command") def testcommand(self) -> str: return "here" def __repr__(self): return "Addon(%s)" % self.name def done(self): pass def running(self): self.running_called = True class AsyncTAddon(TAddon): async def done(self): pass async def running(self): self.running_called = True class THalt: def running(self): raise exceptions.AddonHalt class AsyncTHalt: async def running(self): raise exceptions.AddonHalt class AOption: def load(self, loader: Loader): loader.add_option("custom_option", bool, False, "help") class AOldAPI: def clientconnect(self): pass def test_command(): with taddons.context() as tctx: tctx.master.addons.add(TAddon("test")) assert tctx.master.commands.execute("test.command") == "here" async def test_halt(): o = options.Options() m = master.Master(o) a = addonmanager.AddonManager(m) halt = THalt() end = TAddon("end") a.add(halt) a.add(end) assert not end.running_called a.trigger(hooks.RunningHook()) assert not end.running_called a.remove(halt) a.trigger(hooks.RunningHook()) assert end.running_called async def test_async_halt(): o = options.Options() m = master.Master(o) a = addonmanager.AddonManager(m) halt = AsyncTHalt() end = AsyncTAddon("end") a.add(halt) a.add(end) assert not end.running_called await a.trigger_event(hooks.RunningHook()) assert not end.running_called a.remove(halt) await a.trigger_event(hooks.RunningHook()) assert end.running_called async def test_lifecycle(): o = options.Options() m = master.Master(o) a = addonmanager.AddonManager(m) a.add(TAddon("one")) assert str(a) with pytest.raises(exceptions.AddonManagerError): a.add(TAddon("one")) with pytest.raises(exceptions.AddonManagerError): a.remove(TAddon("nonexistent")) f = tflow.tflow() await a.handle_lifecycle(HttpRequestHook(f)) a._configure_all(o.keys()) def test_defaults(): assert addons.default_addons() async def test_mixed_async_sync(caplog): with taddons.context(loadcore=False) as tctx: a = tctx.master.addons assert len(a) == 0 a1 = TAddon("sync") a2 = AsyncTAddon("async") a.add(a1) a.add(a2) # test that we can call both sync and async hooks asynchronously assert not a1.running_called assert not a2.running_called await a.trigger_event(hooks.RunningHook()) assert a1.running_called assert a2.running_called # test that calling an async hook synchronously fails a1.running_called = False a2.running_called = False a.trigger(hooks.RunningHook()) assert a1.running_called assert "called from sync context" in caplog.text async def test_loader(caplog): with taddons.context() as tctx: loader = addonmanager.Loader(tctx.master) loader.add_option("custom_option", bool, False, "help") assert "custom_option" in loader.master.options # calling this again with the same signature is a no-op. loader.add_option("custom_option", bool, False, "help") assert not caplog.text # a different signature should emit a warning though. loader.add_option("custom_option", bool, True, "help") assert "Over-riding existing option" in caplog.text def cmd(a: str) -> str: return "foo" loader.add_command("test.command", cmd) async def test_simple(caplog): with taddons.context(loadcore=False) as tctx: a = tctx.master.addons assert len(a) == 0 a.add(TAddon("one")) assert a.get("one") assert not a.get("two") assert len(a) == 1 a.clear() assert len(a) == 0 assert not a.chain with taddons.context(loadcore=False) as tctx: a.add(TAddon("one")) a.trigger("nonexistent") assert "AssertionError" in caplog.text f = tflow.tflow() a.trigger(hooks.RunningHook()) a.trigger(HttpResponseHook(f)) assert "not callable" in caplog.text caplog.clear() caplog.clear() a.get("one").response = addons a.trigger(HttpResponseHook(f)) assert "not callable" not in caplog.text a.remove(a.get("one")) assert not a.get("one") ta = TAddon("one") a.add(ta) a.trigger(hooks.RunningHook()) assert ta.running_called assert ta in a async def test_load_option(): o = options.Options() m = master.Master(o) a = addonmanager.AddonManager(m) a.add(AOption()) assert "custom_option" in m.options._options async def test_nesting(): o = options.Options() m = master.Master(o) a = addonmanager.AddonManager(m) a.add( TAddon("one", addons=[TAddon("two"), TAddon("three", addons=[TAddon("four")])]) ) assert len(a.chain) == 1 assert a.get("one") assert a.get("two") assert a.get("three") assert a.get("four") a.trigger(hooks.RunningHook()) assert a.get("one").running_called assert a.get("two").running_called assert a.get("three").running_called assert a.get("four").running_called a.remove(a.get("three")) assert not a.get("three") assert not a.get("four") async def test_old_api(caplog): with taddons.context(loadcore=False) as tctx: tctx.master.addons.add(AOldAPI()) assert "clientconnect event has been removed" in caplog.text
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_dns.py
test/mitmproxy/test_dns.py
import ipaddress import struct import pytest from mitmproxy import dns from mitmproxy import flowfilter from mitmproxy.dns import DNSMessage from mitmproxy.test import tflow from mitmproxy.test import tutils class TestResourceRecord: def test_str(self): assert ( str(dns.ResourceRecord.A("test", ipaddress.IPv4Address("1.2.3.4"))) == "1.2.3.4" ) assert ( str(dns.ResourceRecord.AAAA("test", ipaddress.IPv6Address("::1"))) == "::1" ) assert ( str(dns.ResourceRecord.CNAME("test", "some.other.host")) == "some.other.host" ) assert ( str(dns.ResourceRecord.PTR("test", "some.other.host")) == "some.other.host" ) assert ( str(dns.ResourceRecord.TXT("test", "unicode text 😀")) == "unicode text 😀" ) params = { 0: b"\x00", 1: b"\x01", 2: b"", 3: b"\x02", 4: b"\x03", 5: b"\x04", 6: b"\x05", } record = dns.https_records.HTTPSRecord(1, "example.com", params) assert ( str(dns.ResourceRecord.HTTPS("example.com", record)) == r"{'target_name': 'example.com', 'priority': 1, 'mandatory': '\\x00', 'alpn': '\\x01', 'no_default_alpn': '', 'port': '\\x02', 'ipv4hint': '\\x03', 'ech': '\\x04', 'ipv6hint': '\\x05'}" ) assert ( str( dns.ResourceRecord( "test", dns.types.A, dns.classes.IN, dns.ResourceRecord.DEFAULT_TTL, b"", ) ) == "0x (invalid A data)" ) assert ( str( dns.ResourceRecord( "test", dns.types.SOA, dns.classes.IN, dns.ResourceRecord.DEFAULT_TTL, b"\x00\x01\x02\x03", ) ) == "0x00010203" ) def test_setter(self): rr = dns.ResourceRecord( "test", dns.types.ANY, dns.classes.IN, dns.ResourceRecord.DEFAULT_TTL, b"" ) rr.ipv4_address = ipaddress.IPv4Address("8.8.4.4") assert rr.ipv4_address == ipaddress.IPv4Address("8.8.4.4") rr.ipv6_address = ipaddress.IPv6Address("2001:4860:4860::8844") assert rr.ipv6_address == ipaddress.IPv6Address("2001:4860:4860::8844") rr.domain_name = "www.example.org" assert rr.domain_name == "www.example.org" rr.text = "sample text" assert rr.text == "sample text" def test_https_record_ech(self): rr = dns.ResourceRecord( "test", dns.types.ANY, dns.classes.IN, dns.ResourceRecord.DEFAULT_TTL, b"" ) params = {3: b"\x01\xbb"} record = dns.https_records.HTTPSRecord(1, "example.org", params) rr.data = dns.https_records.pack(record) assert rr.https_ech is None rr.https_ech = "dGVzdHN0cmluZwo=" assert rr.https_ech == "dGVzdHN0cmluZwo=" rr.https_ech = None assert rr.https_ech is None def test_https_record_alpn(self): rr = dns.ResourceRecord( "test", dns.types.ANY, dns.classes.IN, dns.ResourceRecord.DEFAULT_TTL, b"" ) record = dns.https_records.HTTPSRecord(1, "example.org", {}) rr.data = dns.https_records.pack(record) assert rr.https_alpn is None assert rr.data == b"\x00\x01\x07example\x03org\x00" rr.https_alpn = [b"h2", b"h3"] assert rr.https_alpn == (b"h2", b"h3") assert rr.data == b"\x00\x01\x07example\x03org\x00\x00\x01\x00\x06\x02h2\x02h3" rr.https_alpn = None assert rr.https_alpn is None assert rr.data == b"\x00\x01\x07example\x03org\x00" class TestMessage: def test_content_alias(self): m = tutils.tdnsresp() assert m.content == m.packed def test_to_json(self): resp = tutils.tdnsresp() json = resp.to_json() assert json["id"] == resp.id assert len(json["questions"]) == len(resp.questions) assert json["questions"][0]["name"] == resp.questions[0].name assert len(json["answers"]) == len(resp.answers) assert json["answers"][0]["data"] == str(resp.answers[0]) assert DNSMessage.from_json(resp.to_json()) == resp def test_from_json(self): assert DNSMessage.from_json( { **tutils.tdnsresp().to_json(), "answers": [ { "name": "dns.google", "type": "A", "class": "IN", "ttl": 32, "data": "8.8.8.8", }, { "name": "dns.google", "type": "AAAA", "class": "IN", "ttl": 32, "data": "::1", }, { "name": "dns.google", "type": "CNAME", "class": "IN", "ttl": 32, "data": "alias.google", }, { "name": "dns.google", "type": "TXT", "class": "IN", "ttl": 32, "data": "random text", }, { "name": "dns.google", "type": "HTTPS", "class": "IN", "ttl": 32, "data": { "target_name": "dns.google", "priority": 42, }, }, { "name": "dns.google", "type": "TYPE(42)", "class": "IN", "ttl": 32, "data": "0xffff", }, ], } ) def test_responses(self): req = tutils.tdnsreq() resp = tutils.tdnsresp() resp2 = req.succeed( [ dns.ResourceRecord.A( "dns.google", ipaddress.IPv4Address("8.8.8.8"), ttl=32 ), dns.ResourceRecord.A( "dns.google", ipaddress.IPv4Address("8.8.4.4"), ttl=32 ), ] ) resp2.timestamp = resp.timestamp assert resp == resp2 assert resp2.size == 8 with pytest.raises(ValueError): req.fail(dns.response_codes.NOERROR) assert ( req.fail(dns.response_codes.FORMERR).response_code == dns.response_codes.FORMERR ) def test_range(self): def test(what: str, min: int, max: int): req = tutils.tdnsreq() setattr(req, what, min) assert getattr(dns.DNSMessage.unpack(req.packed), what) == min setattr(req, what, min - 1) with pytest.raises(ValueError): req.packed setattr(req, what, max) assert getattr(dns.DNSMessage.unpack(req.packed), what) == max setattr(req, what, max + 1) with pytest.raises(ValueError): req.packed test("id", 0, 2**16 - 1) test("reserved", 0, 7) test("op_code", 0, 0b1111) test("response_code", 0, 0b1111) def test_packing(self): def assert_eq(m: dns.DNSMessage, b: bytes) -> None: m_b = dns.DNSMessage.unpack(b, m.timestamp) assert m_b == m assert m_b.packed == m.packed assert_eq( tutils.tdnsreq(), b"\x00\x2a\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03dns\x06google\x00\x00\x01\x00\x01", ) with pytest.raises(struct.error): dns.DNSMessage.unpack( b"\x00\x2a\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03dns\x06google\x00\x00\x01\x00\x01\x00" ) assert_eq( tutils.tdnsresp(), ( b"\x00\x2a\x81\x80\x00\x01\x00\x02\x00\x00\x00\x00\x03dns\x06google\x00\x00\x01\x00\x01" b"\xc0\x0c\x00\x01\x00\x01\x00\x00\x00 \x00\x04\x08\x08\x08\x08\xc0\x0c\x00\x01\x00\x01" b"\x00\x00\x00 \x00\x04\x08\x08\x04\x04" ), ) with pytest.raises(struct.error): # question error dns.DNSMessage.unpack( b"\x00\x2a\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03dns\x06goo" ) with pytest.raises(struct.error): # rr length error dns.DNSMessage.unpack( b"\x00\x2a\x81\x80\x00\x01\x00\x02\x00\x00\x00\x00\x03dns\x06google\x00\x00\x01\x00\x01" + b"\xc0\x0c\x00\x01\x00\x01\x00\x00\x00 \x00\x04\x08\x08\x08\x08\xc0\x0c\x00\x01\x00\x01\x00\x00\x00 \x00\x04\x08\x08\x04" ) txt = dns.DNSMessage.unpack( b"V\x1a\x81\x80\x00\x01\x00\x01\x00\x01\x00\x01\x05alive\x06github\x03com\x00\x00" + b"\x10\x00\x01\xc0\x0c\x00\x05\x00\x01\x00\x00\x0b\xc6\x00\x07\x04live\xc0\x12\xc0\x12\x00\x06\x00\x01" + b"\x00\x00\x03\x84\x00H\x07ns-1707\tawsdns-21\x02co\x02uk\x00\x11awsdns-hostmaster\x06amazon\xc0\x19\x00" + b"\x00\x00\x01\x00\x00\x1c \x00\x00\x03\x84\x00\x12u\x00\x00\x01Q\x80\x00\x00)\x02\x00\x00\x00\x00\x00\x00\x00" ) assert txt.answers[0].domain_name == "live.github.com" invalid_rr_domain_name = dns.DNSMessage.unpack( b"V\x1a\x81\x80\x00\x01\x00\x01\x00\x01\x00\x01\x05alive\x06github\x03com\x00\x00" + b"\x10\x00\x01\xc0\x0c\x00\x05\x00\x01\x00\x00\x0b\xc6\x00\x07\x99live\xc0\x12\xc0\x12\x00\x06\x00\x01" + b"\x00\x00\x03\x84\x00H\x07ns-1707\tawsdns-21\x02co\x02uk\x00\x11awsdns-hostmaster\x06amazon\xc0\x19\x00" + b"\x00\x00\x01\x00\x00\x1c \x00\x00\x03\x84\x00\x12u\x00\x00\x01Q\x80\x00\x00)\x02\x00\x00\x00\x00\x00\x00\x00" ) assert ( invalid_rr_domain_name.answers[0].data == b"\x99live\x06github\x03com\x00" ) valid_compressed_rr_data = dns.DNSMessage.unpack( b"\x10}\x81\x80\x00\x01\x00\x01\x00\x00\x00\x01\x06google\x03com\x00\x00\x06\x00\x01\xc0\x0c\x00\x06\x00" + b"\x01\x00\x00\x00\x0c\x00&\x03ns1\xc0\x0c\tdns-admin\xc0\x0c&~gw\x00\x00\x03\x84\x00\x00\x03\x84\x00" + b"\x00\x07\x08\x00\x00\x00<\x00\x00)\x02\x00\x00\x00\x00\x00\x00\x00" ) assert ( valid_compressed_rr_data.answers[0].data == b"\x03ns1\x06google\x03com\x00\tdns-admin\x06google\x03com\x00&~gw\x00\x00\x03\x84\x00\x00\x03\x84\x00" + b"\x00\x07\x08\x00\x00\x00<" ) A_record_data_contains_pointer_label = dns.DNSMessage.unpack( b"\x98A\x81\x80\x00\x01\x00\x01\x00\x00\x00\x01\x06google\x03com\x00\x00\x01\x00\x01\xc0\x0c\x00\x01\x00" + b"\x01\x00\x00\x00/\x00\x04\xd8:\xc4\xae\x00\x00)\x02\x00\x00\x00\x00\x00\x00\x00" ) assert A_record_data_contains_pointer_label.answers[0].data == b"\xd8:\xc4\xae" req = tutils.tdnsreq() for flag in ( "authoritative_answer", "truncation", "recursion_desired", "recursion_available", ): setattr(req, flag, True) assert getattr(dns.DNSMessage.unpack(req.packed), flag) is True setattr(req, flag, False) assert getattr(dns.DNSMessage.unpack(req.packed), flag) is False def test_copy(self): msg = tutils.tdnsresp() assert dns.DNSMessage.from_state(msg.get_state()) == msg copy = msg.copy() assert copy is not msg assert copy != msg copy.id = msg.id assert copy == msg assert copy.questions is not msg.questions assert copy.questions == msg.questions assert copy.answers is not msg.answers assert copy.answers == msg.answers assert copy.authorities is not msg.authorities assert copy.authorities == msg.authorities assert copy.additionals is not msg.additionals assert copy.additionals == msg.additionals class TestDNSFlow: def test_copy(self): f = tflow.tdnsflow(resp=True) assert repr(f) f.get_state() f2 = f.copy() a = f.get_state() b = f2.get_state() del a["id"] del b["id"] assert a == b assert not f == f2 assert f is not f2 assert f.request.get_state() == f2.request.get_state() assert f.request is not f2.request assert f.request == f2.request assert f.response is not f2.response assert f.response.get_state() == f2.response.get_state() assert f.response == f2.response f = tflow.tdnsflow(err=True) f2 = f.copy() assert f is not f2 assert f.request is not f2.request assert f.request == f2.request assert f.error.get_state() == f2.error.get_state() assert f.error is not f2.error def test_match(self): f = tflow.tdnsflow(resp=True) assert not flowfilter.match("~b nonexistent", f) assert flowfilter.match(None, f) assert flowfilter.match("~b dns.google", f) assert flowfilter.match("~b 8.8.8.8", f) assert flowfilter.match("~bq dns.google", f) assert not flowfilter.match("~bq 8.8.8.8", f) assert flowfilter.match("~bs dns.google", f) assert flowfilter.match("~bs 8.8.4.4", f) assert flowfilter.match("~dns", f) assert not flowfilter.match("~dns", tflow.ttcpflow()) assert not flowfilter.match("~dns", tflow.tflow()) f = tflow.tdnsflow(err=True) assert flowfilter.match("~e", f) with pytest.raises(ValueError): flowfilter.match("~", f) def test_repr(self): f = tflow.tdnsflow() assert "DNSFlow" in repr(f) def test_question(self): r = tflow.tdnsreq() assert r.question r.questions = [] assert not r.question
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_hooks.py
test/mitmproxy/test_hooks.py
from dataclasses import dataclass import pytest from mitmproxy import hooks def test_hook(): with pytest.raises(TypeError, match="may not be instantiated directly"): hooks.Hook() class NoDataClass(hooks.Hook): pass with pytest.raises(TypeError, match="not a dataclass"): NoDataClass() @dataclass class FooHook(hooks.Hook): data: bytes e = FooHook(b"foo") assert repr(e) assert e.args() == [b"foo"] assert FooHook in hooks.all_hooks.values() with pytest.warns(RuntimeWarning, match="Two conflicting event classes"): @dataclass class FooHook2(hooks.Hook): name = "foo" @dataclass class AnotherABC(hooks.Hook): name = "" assert AnotherABC not in hooks.all_hooks.values()
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_udp.py
test/mitmproxy/test_udp.py
import pytest from mitmproxy import flowfilter from mitmproxy import udp from mitmproxy.test import tflow class TestUDPFlow: def test_copy(self): f = tflow.tudpflow() f.get_state() f2 = f.copy() a = f.get_state() b = f2.get_state() del a["id"] del b["id"] assert a == b assert not f == f2 assert f is not f2 assert f.messages is not f2.messages for m in f.messages: assert m.get_state() m2 = m.copy() assert not m == m2 assert m is not m2 a = m.get_state() b = m2.get_state() assert a == b m = udp.UDPMessage(False, "foo") m.set_state(f.messages[0].get_state()) assert m.timestamp == f.messages[0].timestamp f = tflow.tudpflow(err=True) f2 = f.copy() assert f is not f2 assert f.error.get_state() == f2.error.get_state() assert f.error is not f2.error def test_match(self): f = tflow.tudpflow() assert not flowfilter.match("~b nonexistent", f) assert flowfilter.match(None, f) assert not flowfilter.match("~b nonexistent", f) f = tflow.tudpflow(err=True) assert flowfilter.match("~e", f) with pytest.raises(ValueError): flowfilter.match("~", f) def test_repr(self): f = tflow.tudpflow() assert "UDPFlow" in repr(f) assert "-> " in repr(f.messages[0])
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_ctx.py
test/mitmproxy/test_ctx.py
# TODO: write tests
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_eventsequence.py
test/mitmproxy/test_eventsequence.py
import pytest from mitmproxy import eventsequence from mitmproxy.proxy import layers from mitmproxy.test import tflow @pytest.mark.parametrize( "resp, err", [ (False, False), (True, False), (False, True), (True, True), ], ) def test_http_flow(resp, err): f = tflow.tflow(resp=resp, err=err) i = eventsequence.iterate(f) assert isinstance(next(i), layers.http.HttpRequestHeadersHook) assert isinstance(next(i), layers.http.HttpRequestHook) if resp: assert isinstance(next(i), layers.http.HttpResponseHeadersHook) assert isinstance(next(i), layers.http.HttpResponseHook) if err: assert isinstance(next(i), layers.http.HttpErrorHook) def test_websocket_flow(): f = tflow.twebsocketflow() i = eventsequence.iterate(f) assert isinstance(next(i), layers.http.HttpRequestHeadersHook) assert isinstance(next(i), layers.http.HttpRequestHook) assert isinstance(next(i), layers.http.HttpResponseHeadersHook) assert isinstance(next(i), layers.http.HttpResponseHook) assert isinstance(next(i), layers.websocket.WebsocketStartHook) assert len(f.websocket.messages) == 0 assert isinstance(next(i), layers.websocket.WebsocketMessageHook) assert len(f.websocket.messages) == 1 assert isinstance(next(i), layers.websocket.WebsocketMessageHook) assert len(f.websocket.messages) == 2 assert isinstance(next(i), layers.websocket.WebsocketMessageHook) assert len(f.websocket.messages) == 3 assert isinstance(next(i), layers.websocket.WebsocketEndHook) @pytest.mark.parametrize("err", [False, True]) def test_tcp_flow(err): f = tflow.ttcpflow(err=err) i = eventsequence.iterate(f) assert isinstance(next(i), layers.tcp.TcpStartHook) assert len(f.messages) == 0 assert isinstance(next(i), layers.tcp.TcpMessageHook) assert len(f.messages) == 1 assert isinstance(next(i), layers.tcp.TcpMessageHook) assert len(f.messages) == 2 if err: assert isinstance(next(i), layers.tcp.TcpErrorHook) else: assert isinstance(next(i), layers.tcp.TcpEndHook) @pytest.mark.parametrize("err", [False, True]) def test_udp_flow(err): f = tflow.tudpflow(err=err) i = eventsequence.iterate(f) assert isinstance(next(i), layers.udp.UdpStartHook) assert len(f.messages) == 0 assert isinstance(next(i), layers.udp.UdpMessageHook) assert len(f.messages) == 1 assert isinstance(next(i), layers.udp.UdpMessageHook) assert len(f.messages) == 2 if err: assert isinstance(next(i), layers.udp.UdpErrorHook) else: assert isinstance(next(i), layers.udp.UdpEndHook) @pytest.mark.parametrize( "resp, err", [ (False, False), (True, False), (False, True), (True, True), ], ) def test_dns(resp, err): f = tflow.tdnsflow(resp=resp, err=err) i = eventsequence.iterate(f) assert isinstance(next(i), layers.dns.DnsRequestHook) if resp: assert isinstance(next(i), layers.dns.DnsResponseHook) if err: assert isinstance(next(i), layers.dns.DnsErrorHook) def test_invalid(): with pytest.raises(TypeError): next(eventsequence.iterate(42))
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_http.py
test/mitmproxy/test_http.py
import asyncio import email import json import time from typing import Any from unittest import mock import pytest from mitmproxy import flow from mitmproxy import flowfilter from mitmproxy.http import Headers from mitmproxy.http import HTTPFlow from mitmproxy.http import Message 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 from mitmproxy.test.tutils import tresp class TestRequest: def test_simple(self): f = tflow() r = f.request u = r.url r.url = u with pytest.raises(ValueError): setattr(r, "url", "") assert r.url == u r2 = r.copy() assert r.get_state() == r2.get_state() assert hash(r) def test_get_url(self): r = treq() assert r.url == "http://address:22/path" r.scheme = "https" assert r.url == "https://address:22/path" r.host = "host" r.port = 42 assert r.url == "https://host:42/path" r.host = "address" r.port = 22 assert r.url == "https://address:22/path" assert r.pretty_url == "https://address:22/path" r.headers["Host"] = "foo.com:22" assert r.url == "https://address:22/path" assert r.pretty_url == "https://foo.com:22/path" def test_constrain_encoding(self): r = treq() r.headers["accept-encoding"] = "gzip, oink" r.constrain_encoding() assert "oink" not in r.headers["accept-encoding"] r.headers.set_all("accept-encoding", ["gzip", "oink"]) r.constrain_encoding() assert "oink" not in r.headers["accept-encoding"] def test_get_content_type(self): resp = tresp() resp.headers = Headers(content_type="text/plain") assert resp.headers["content-type"] == "text/plain" class TestRequestData: def test_init(self): with pytest.raises(UnicodeEncodeError): treq(method="fööbär") with pytest.raises(UnicodeEncodeError): treq(scheme="fööbär") assert treq(host="fööbär").host == "fööbär" with pytest.raises(UnicodeEncodeError): treq(path="/fööbär") with pytest.raises(UnicodeEncodeError): treq(http_version="föö/bä.r") with pytest.raises(ValueError): treq(headers="foobar") with pytest.raises(ValueError): treq(content="foobar") with pytest.raises(ValueError): treq(trailers="foobar") assert isinstance(treq(headers=()).headers, Headers) assert isinstance(treq(trailers=()).trailers, Headers) class TestRequestCore: """ Tests for addons and the attributes that are directly proxied from the data structure """ def test_repr(self): request = treq() assert repr(request) == "Request(GET address:22/path)" request.host = None assert repr(request) == "Request(GET /path)" def test_init_conv(self): assert Request( b"example.com", 80, "GET", "http", "example.com", "/", "HTTP/1.1", (), None, (), 0, 0, ) # type: ignore def test_make(self): r = Request.make("GET", "https://example.com/") assert r.method == "GET" assert r.scheme == "https" assert r.host == "example.com" assert r.port == 443 assert r.path == "/" r = Request.make("GET", "https://example.com/", "content", {"Foo": "bar"}) assert r.content == b"content" assert r.headers["content-length"] == "7" assert r.headers["Foo"] == "bar" Request.make("GET", "https://example.com/", content=b"content") with pytest.raises(TypeError): Request.make("GET", "https://example.com/", content=42) r = Request.make("GET", "https://example.com/", headers=[(b"foo", b"bar")]) assert r.headers["foo"] == "bar" r = Request.make("GET", "https://example.com/", headers=({"foo": "baz"})) assert r.headers["foo"] == "baz" r = Request.make("GET", "https://example.com/", headers=Headers(foo="qux")) assert r.headers["foo"] == "qux" with pytest.raises(TypeError): Request.make("GET", "https://example.com/", headers=42) def test_first_line_format(self): assert treq(method=b"CONNECT").first_line_format == "authority" assert treq(authority=b"example.com").first_line_format == "absolute" assert treq(authority=b"").first_line_format == "relative" def test_method(self): _test_decoded_attr(treq(), "method") def test_scheme(self): _test_decoded_attr(treq(), "scheme") def test_port(self): _test_passthrough_attr(treq(), "port", 1234) with pytest.raises(ValueError): treq().port = "foo" def test_path(self): _test_decoded_attr(treq(), "path") def test_authority(self): request = treq() assert request.authority == request.data.authority.decode("idna") # Test IDNA encoding # Set str, get raw bytes request.authority = "ídna.example" assert request.data.authority == b"xn--dna-qma.example" # Set raw bytes, get decoded request.data.authority = b"xn--idn-gla.example" assert request.authority == "idná.example" # Set bytes, get raw bytes request.authority = b"xn--dn-qia9b.example" assert request.data.authority == b"xn--dn-qia9b.example" # IDNA encoding is not bijective request.authority = "fußball" assert request.authority == "fussball" # Don't fail on garbage request.data.authority = b"foo\xff\x00bar" assert request.authority.startswith("foo") assert request.authority.endswith("bar") # foo.bar = foo.bar should not cause any side effects. d = request.authority request.authority = d assert request.data.authority == b"foo\xff\x00bar" def test_host_update_also_updates_header(self): request = treq() assert "host" not in request.headers request.host = "example.com" assert "host" not in request.headers request.headers["Host"] = "foo" request.authority = "foo" request.host = "example.org" assert request.headers["Host"] == request.authority == "example.org:22" def test_get_host_header(self): no_hdr = treq() assert no_hdr.host_header is None h1 = treq( headers=((b"host", b"header.example.com"),), authority=b"authority.example.com", ) assert h1.host_header == "header.example.com" h2 = h1.copy() h2.http_version = "HTTP/2.0" assert h2.host_header == "authority.example.com" h2_host_only = h2.copy() h2_host_only.authority = "" assert h2_host_only.host_header == "header.example.com" def test_modify_host_header(self): h1 = treq() assert "host" not in h1.headers h1.host_header = "example.com" assert h1.headers["Host"] == "example.com" assert not h1.authority h1.host_header = None assert "host" not in h1.headers assert not h1.authority h2 = treq(http_version=b"HTTP/2.0") h2.host_header = "example.org" assert "host" not in h2.headers assert h2.authority == "example.org" h2.headers["Host"] = "example.org" h2.host_header = "foo.example.com" assert h2.headers["Host"] == "foo.example.com" assert h2.authority == "foo.example.com" h2.host_header = None assert "host" not in h2.headers assert not h2.authority class TestRequestUtils: """ Tests for additional convenience methods. """ def test_url(self): request = treq() assert request.url == "http://address:22/path" request.url = "https://otheraddress:42/foo" assert request.scheme == "https" assert request.host == "otheraddress" assert request.port == 42 assert request.path == "/foo" with pytest.raises(ValueError): request.url = "not-a-url" def test_url_options(self): request = treq(method=b"OPTIONS", path=b"*") assert request.url == "http://address:22" def test_url_authority(self): request = treq(method=b"CONNECT") assert request.url == "address:22" def test_pretty_host(self): request = treq() # Without host header assert request.pretty_host == "address" assert request.host == "address" # Same port as self.port (22) request.headers["host"] = "other:22" assert request.pretty_host == "other" # Invalid IDNA request.headers["host"] = ".disqus.com" assert request.pretty_host == ".disqus.com" def test_pretty_url(self): request = treq() # Without host header assert request.url == "http://address:22/path" assert request.pretty_url == "http://address:22/path" request.headers["host"] = "other:22" assert request.pretty_url == "http://other:22/path" request = treq(method=b"CONNECT", authority=b"example:44") assert request.pretty_url == "example:44" def test_pretty_url_options(self): request = treq(method=b"OPTIONS", path=b"*") assert request.pretty_url == "http://address:22" def test_pretty_url_authority(self): request = treq(method=b"CONNECT", authority="address:22") assert request.pretty_url == "address:22" def test_get_query(self): request = treq() assert not request.query request.url = "http://localhost:80/foo?bar=42" assert dict(request.query) == {"bar": "42"} def test_set_query(self): request = treq() assert not request.query request.query["foo"] = "bar" assert request.query["foo"] == "bar" assert request.path == "/path?foo=bar" request.query = [("foo", "bar")] assert request.query["foo"] == "bar" assert request.path == "/path?foo=bar" def test_get_cookies_none(self): request = treq() request.headers = Headers() assert not request.cookies def test_get_cookies_single(self): request = treq() request.headers = Headers(cookie="cookiename=cookievalue") assert len(request.cookies) == 1 assert request.cookies["cookiename"] == "cookievalue" def test_get_cookies_double(self): request = treq() request.headers = Headers( cookie="cookiename=cookievalue;othercookiename=othercookievalue" ) result = request.cookies assert len(result) == 2 assert result["cookiename"] == "cookievalue" assert result["othercookiename"] == "othercookievalue" def test_get_cookies_withequalsign(self): request = treq() request.headers = Headers( cookie="cookiename=coo=kievalue;othercookiename=othercookievalue" ) result = request.cookies assert len(result) == 2 assert result["cookiename"] == "coo=kievalue" assert result["othercookiename"] == "othercookievalue" def test_set_cookies(self): request = treq() request.headers = Headers(cookie="cookiename=cookievalue") result = request.cookies result["cookiename"] = "foo" assert request.cookies["cookiename"] == "foo" request.cookies = [["one", "uno"], ["two", "due"]] assert request.cookies["one"] == "uno" assert request.cookies["two"] == "due" def test_get_path_components(self): request = treq(path=b"/foo/bar") assert request.path_components == ("foo", "bar") def test_set_path_components(self): request = treq() request.path_components = ["foo", "baz"] assert request.path == "/foo/baz" request.path_components = [] assert request.path == "/" request.path_components = ["foo", "baz"] request.query["hello"] = "hello" assert request.path_components == ("foo", "baz") request.path_components = ["abc"] assert request.path == "/abc?hello=hello" def test_anticache(self): request = treq() request.headers["If-Modified-Since"] = "foo" request.headers["If-None-Match"] = "bar" request.anticache() assert "If-Modified-Since" not in request.headers assert "If-None-Match" not in request.headers def test_anticomp(self): request = treq() request.headers["Accept-Encoding"] = "foobar" request.anticomp() assert request.headers["Accept-Encoding"] == "identity" def test_constrain_encoding(self): request = treq() h = request.headers.copy() request.constrain_encoding() # no-op if there is no accept_encoding header. assert request.headers == h request.headers["Accept-Encoding"] = "identity, gzip, foo" request.constrain_encoding() assert "foo" not in request.headers["Accept-Encoding"] assert "gzip" in request.headers["Accept-Encoding"] def test_get_urlencoded_form(self): request = treq(content=b"foobar=baz") assert not request.urlencoded_form request.headers["Content-Type"] = "application/x-www-form-urlencoded" assert list(request.urlencoded_form.items()) == [("foobar", "baz")] request.raw_content = b"\xff" assert len(request.urlencoded_form) == 1 def test_set_urlencoded_form(self): request = treq(content=b"\xec\xed") request.urlencoded_form = [("foo", "bar"), ("rab", "oof")] assert request.headers["Content-Type"] == "application/x-www-form-urlencoded" assert request.content def test_get_multipart_form(self): request = treq(content=b"foobar") assert not request.multipart_form request.headers["Content-Type"] = "multipart/form-data" assert list(request.multipart_form.items()) == [] with mock.patch("mitmproxy.net.http.multipart.decode_multipart") as m: m.side_effect = ValueError assert list(request.multipart_form.items()) == [] def test_set_multipart_form(self): request = treq() request.multipart_form = [(b"file", b"shell.jpg"), (b"file_size", b"1000")] assert request.headers["Content-Type"].startswith("multipart/form-data") assert list(request.multipart_form.items()) == [ (b"file", b"shell.jpg"), (b"file_size", b"1000"), ] class TestResponse: def test_simple(self): f = tflow(resp=True) resp = f.response resp2 = resp.copy() assert resp2.get_state() == resp.get_state() def test_get_content_type(self): resp = tresp() resp.headers = Headers(content_type="text/plain") assert resp.headers["content-type"] == "text/plain" class TestResponseData: def test_init(self): with pytest.raises(ValueError): tresp(headers="foobar") with pytest.raises(UnicodeEncodeError): tresp(http_version="föö/bä.r") with pytest.raises(UnicodeEncodeError): tresp(reason="fööbär") with pytest.raises(ValueError): tresp(content="foobar") with pytest.raises(ValueError): tresp(trailers="foobar") assert isinstance(tresp(headers=()).headers, Headers) assert isinstance(tresp(trailers=()).trailers, Headers) class TestResponseCore: """ Tests for addons and the attributes that are directly proxied from the data structure """ def test_repr(self): response = tresp() assert repr(response) == "Response(200, unknown content type, 7b)" response.content = None assert repr(response) == "Response(200, no content)" def test_make(self): r = Response.make() assert r.status_code == 200 assert r.content == b"" r = Response.make(418, "teatime") assert r.status_code == 418 assert r.content == b"teatime" assert r.headers["content-length"] == "7" Response.make(content=b"foo") Response.make(content="foo") with pytest.raises(TypeError): Response.make(content=42) r = Response.make(headers=[(b"foo", b"bar")]) assert r.headers["foo"] == "bar" r = Response.make(headers=({"foo": "baz"})) assert r.headers["foo"] == "baz" r = Response.make(headers=Headers(foo="qux")) assert r.headers["foo"] == "qux" with pytest.raises(TypeError): Response.make(headers=42) def test_status_code(self): _test_passthrough_attr(tresp(), "status_code") def test_reason(self): resp = tresp() assert resp.reason == "OK" resp.reason = "ABC" assert resp.data.reason == b"ABC" resp.reason = b"DEF" assert resp.data.reason == b"DEF" resp.data.reason = b"cr\xe9e" assert resp.reason == "crée" class TestResponseUtils: """ Tests for additional convenience methods. """ def test_get_cookies_none(self): resp = tresp() resp.headers = Headers() assert not resp.cookies def test_get_cookies_empty(self): resp = tresp() resp.headers = Headers(set_cookie="") assert not resp.cookies def test_get_cookies_simple(self): resp = tresp() resp.headers = Headers(set_cookie="cookiename=cookievalue") result = resp.cookies assert len(result) == 1 assert "cookiename" in result assert result["cookiename"] == ("cookievalue", CookieAttrs()) def test_get_cookies_with_parameters(self): resp = tresp() cookie = "cookiename=cookievalue;domain=example.com;expires=Wed Oct 21 16:29:41 2015;path=/; HttpOnly" resp.headers = Headers(set_cookie=cookie) result = resp.cookies assert len(result) == 1 assert "cookiename" in result assert result["cookiename"][0] == "cookievalue" attrs = result["cookiename"][1] assert len(attrs) == 4 assert attrs["domain"] == "example.com" assert attrs["expires"] == "Wed Oct 21 16:29:41 2015" assert attrs["path"] == "/" assert attrs["httponly"] is None def test_get_cookies_no_value(self): resp = tresp() resp.headers = Headers( set_cookie="cookiename=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/" ) result = resp.cookies assert len(result) == 1 assert "cookiename" in result assert result["cookiename"][0] == "" assert len(result["cookiename"][1]) == 2 def test_get_cookies_twocookies(self): resp = tresp() resp.headers = Headers( [ [b"Set-Cookie", b"cookiename=cookievalue"], [b"Set-Cookie", b"othercookie=othervalue"], ] ) result = resp.cookies assert len(result) == 2 assert "cookiename" in result assert result["cookiename"] == ("cookievalue", CookieAttrs()) assert "othercookie" in result assert result["othercookie"] == ("othervalue", CookieAttrs()) def test_set_cookies(self): resp = tresp() resp.cookies["foo"] = ("bar", {}) assert len(resp.cookies) == 1 assert resp.cookies["foo"] == ("bar", CookieAttrs()) resp.cookies = [ ["one", ("uno", CookieAttrs())], ["two", ("due", CookieAttrs())], ] assert list(resp.cookies.keys()) == ["one", "two"] def test_refresh(self): r = tresp() n = time.time() r.headers["date"] = email.utils.formatdate(n, usegmt=True) pre = r.headers["date"] r.refresh(946681202) assert pre == r.headers["date"] r.refresh(946681262) d = email.utils.parsedate_tz(r.headers["date"]) d = email.utils.mktime_tz(d) # Weird that this is not exact... assert abs(60 - (d - n)) <= 1 cookie = "MOO=BAR; Expires=Tue, 08-Mar-2011 00:20:38 GMT; Path=foo.com; Secure" r.headers["set-cookie"] = cookie r.refresh() # Cookie refreshing is tested in test_cookies, we just make sure that it's triggered here. assert cookie != r.headers["set-cookie"] with mock.patch("mitmproxy.net.http.cookies.refresh_set_cookie_header") as m: m.side_effect = ValueError r.refresh(n) # Test negative unixtime, which raises on at least Windows. r.headers["date"] = pre = "Mon, 01 Jan 1601 00:00:00 GMT" r.refresh(946681202) assert r.headers["date"] == pre class TestHTTPFlow: def test_copy(self): f = tflow(resp=True) assert repr(f) f.get_state() f2 = f.copy() a = f.get_state() b = f2.get_state() del a["id"] del b["id"] assert a == b assert not f == f2 assert f is not f2 assert f.request.get_state() == f2.request.get_state() assert f.request is not f2.request assert f.request.headers == f2.request.headers assert f.request.headers is not f2.request.headers assert f.response.get_state() == f2.response.get_state() assert f.response is not f2.response f = tflow(err=True) f2 = f.copy() assert f is not f2 assert f.request is not f2.request assert f.request.headers == f2.request.headers assert f.request.headers is not f2.request.headers assert f.error.get_state() == f2.error.get_state() assert f.error is not f2.error def test_match(self): f = tflow(resp=True) assert not flowfilter.match("~b test", f) assert flowfilter.match(None, f) assert not flowfilter.match("~b test", f) f = tflow(err=True) assert flowfilter.match("~e", f) with pytest.raises(ValueError): flowfilter.match("~", f) def test_backup(self): f = tflow() f.response = tresp() f.request.content = b"foo" assert not f.modified() f.backup() f.request.content = b"bar" assert f.modified() f.revert() assert f.request.content == b"foo" def test_backup_idempotence(self): f = tflow(resp=True) f.backup() f.revert() f.backup() f.revert() def test_getset_state(self): f = tflow(resp=True) state = f.get_state() assert f.get_state() == HTTPFlow.from_state(state).get_state() f.response = None f.error = flow.Error("error") state = f.get_state() assert f.get_state() == HTTPFlow.from_state(state).get_state() f2 = f.copy() f2.id = f.id # copy creates a different uuid assert f.get_state() == f2.get_state() assert not f == f2 f2.error = flow.Error("e2") assert not f == f2 f2.backup() f2.intercept() # to change the state f.set_state(f2.get_state()) assert f.get_state() == f2.get_state() def test_kill(self): f = tflow() f.intercept() f.resume() assert f.killable f.kill() assert not f.killable f = tflow() f.intercept() assert f.killable f.kill() assert not f.killable assert f.error.msg == flow.Error.KILLED_MESSAGE def test_intercept(self): f = tflow() f.intercept() assert f.intercepted f.intercept() assert f.intercepted def test_resume(self): f = tflow() f.resume() assert not f.intercepted f.intercept() assert f.intercepted f.resume() assert not f.intercepted async def test_wait_for_resume(self): f = tflow() await f.wait_for_resume() f = tflow() f.intercept() f.resume() await f.wait_for_resume() f = tflow() f.intercept() with pytest.raises(asyncio.TimeoutError): await asyncio.wait_for(f.wait_for_resume(), 0.2) f.resume() await f.wait_for_resume() f = tflow() f.intercept() with pytest.raises(asyncio.TimeoutError): await asyncio.wait_for(f.wait_for_resume(), 0.2) f.resume() f.intercept() with pytest.raises(asyncio.TimeoutError): await asyncio.wait_for(f.wait_for_resume(), 0.2) f.resume() await f.wait_for_resume() def test_resume_duplicated(self): f = tflow() f.intercept() f2 = f.copy() assert f.intercepted is f2.intercepted is True f.resume() f2.resume() assert f.intercepted is f2.intercepted is False def test_timestamp_start(self): f = tflow() assert f.timestamp_start == f.request.timestamp_start class TestHeaders: def _2host(self): return Headers(((b"Host", b"example.com"), (b"host", b"example.org"))) def test_init(self): headers = Headers() assert len(headers) == 0 headers = Headers([(b"Host", b"example.com")]) assert len(headers) == 1 assert headers["Host"] == "example.com" headers = Headers(Host="example.com") assert len(headers) == 1 assert headers["Host"] == "example.com" headers = Headers([(b"Host", b"invalid")], Host="example.com") assert len(headers) == 1 assert headers["Host"] == "example.com" headers = Headers( [(b"Host", b"invalid"), (b"Accept", b"text/plain")], Host="example.com" ) assert len(headers) == 2 assert headers["Host"] == "example.com" assert headers["Accept"] == "text/plain" with pytest.raises(TypeError): Headers([(b"Host", "not-bytes")]) def test_set(self): headers = Headers() headers["foo"] = "1" headers[b"bar"] = b"2" headers["baz"] = b"3" with pytest.raises(TypeError): headers["foobar"] = 42 assert len(headers) == 3 def test_bytes(self): headers = Headers(Host="example.com") assert bytes(headers) == b"Host: example.com\r\n" headers = Headers([(b"Host", b"example.com"), (b"Accept", b"text/plain")]) assert bytes(headers) == b"Host: example.com\r\nAccept: text/plain\r\n" headers = Headers() assert bytes(headers) == b"" def test_iter(self): headers = Headers([(b"Set-Cookie", b"foo"), (b"Set-Cookie", b"bar")]) assert list(headers) == ["Set-Cookie"] def test_insert(self): headers = Headers(Accept="text/plain") headers.insert(0, b"Host", "example.com") assert headers.fields == ((b"Host", b"example.com"), (b"Accept", b"text/plain")) def test_items(self): headers = Headers( [ (b"Set-Cookie", b"foo"), (b"Set-Cookie", b"bar"), (b"Accept", b"text/plain"), ] ) assert list(headers.items()) == [ ("Set-Cookie", "foo, bar"), ("Accept", "text/plain"), ] assert list(headers.items(multi=True)) == [ ("Set-Cookie", "foo"), ("Set-Cookie", "bar"), ("Accept", "text/plain"), ] def _test_passthrough_attr(message: Message, attr: str, value: Any = b"foo") -> None: assert getattr(message, attr) == getattr(message.data, attr) setattr(message, attr, value) assert getattr(message.data, attr) == value def _test_decoded_attr(message, attr): assert getattr(message, attr) == getattr(message.data, attr).decode("utf8") # Set str, get raw bytes setattr(message, attr, "foo") assert getattr(message.data, attr) == b"foo" # Set raw bytes, get decoded setattr( message.data, attr, b"BAR" ) # use uppercase so that we can also cover request.method assert getattr(message, attr) == "BAR" # Set bytes, get raw bytes setattr(message, attr, b"baz") assert getattr(message.data, attr) == b"baz" # Set UTF8 setattr(message, attr, "Non-Autorisé") assert getattr(message.data, attr) == b"Non-Autoris\xc3\xa9" # Don't fail on garbage setattr(message.data, attr, b"FOO\xbf\x00BAR") assert getattr(message, attr).startswith("FOO") assert getattr(message, attr).endswith("BAR") # foo.bar = foo.bar should not cause any side effects. d = getattr(message, attr) setattr(message, attr, d) assert getattr(message.data, attr) == b"FOO\xbf\x00BAR" class TestMessageData: def test_eq(self): data = tresp(timestamp_start=42, timestamp_end=42).data same = tresp(timestamp_start=42, timestamp_end=42).data assert data == same other = tresp(content=b"foo").data assert data != other assert data != 0 def test_serializable(self): data1 = tresp(timestamp_start=42, timestamp_end=42).data data1.trailers = Headers() data2 = tresp().data.from_state(data1.get_state()) # ResponseData.from_state() assert data1 == data2 class TestMessage: def test_init(self): resp = tresp() assert resp.data def test_eq_ne(self): resp = tresp(timestamp_start=42, timestamp_end=42) same = tresp(timestamp_start=42, timestamp_end=42) assert resp.data == same.data other = tresp(timestamp_start=0, timestamp_end=0) assert resp.data != other.data assert resp != 0 def test_serializable(self): resp = tresp() resp.trailers = Headers() resp2 = Response.from_state(resp.get_state()) resp3 = tresp() resp3.set_state(resp.get_state()) assert resp.data == resp2.data == resp3.data def test_content_length_update(self): resp = tresp() resp.content = b"foo" assert resp.data.content == b"foo" assert resp.headers["content-length"] == "3" resp.content = b"" assert resp.data.content == b"" assert resp.headers["content-length"] == "0" resp.raw_content = b"bar" assert resp.data.content == b"bar" assert resp.headers["content-length"] == "0" def test_content_length_not_added_for_response_with_transfer_encoding(self): headers = Headers(((b"transfer-encoding", b"chunked"),)) resp = tresp(headers=headers) resp.content = b"bar" assert "content-length" not in resp.headers def test_headers(self): _test_passthrough_attr(tresp(), "headers") def test_trailers(self): _test_passthrough_attr(tresp(), "trailers") def test_timestamp_start(self): _test_passthrough_attr(tresp(), "timestamp_start") def test_timestamp_end(self): _test_passthrough_attr(tresp(), "timestamp_end") def test_http_version(self): _test_decoded_attr(tresp(), "http_version") assert tresp(http_version=b"HTTP/1.0").is_http10 assert tresp(http_version=b"HTTP/1.1").is_http11 assert tresp(http_version=b"HTTP/2.0").is_http2 class TestMessageContentEncoding: def test_simple(self): r = tresp() assert r.raw_content == b"message" assert "content-encoding" not in r.headers r.encode("gzip") assert r.headers["content-encoding"] assert r.raw_content != b"message" assert r.content == b"message" assert r.raw_content != b"message" def test_update_content_length_header(self): r = tresp() assert int(r.headers["content-length"]) == 7 r.encode("gzip") assert int(r.headers["content-length"]) == 27 r.decode() assert int(r.headers["content-length"]) == 7 def test_modify(self): r = tresp() assert "content-encoding" not in r.headers r.encode("gzip") r.content = b"foo" assert r.raw_content != b"foo" r.decode() assert r.raw_content == b"foo" with pytest.raises(TypeError): r.content = "foo" def test_unknown_ce(self): r = tresp() r.headers["content-encoding"] = "zopfli" r.raw_content = b"foo"
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
true
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_flow.py
test/mitmproxy/test_flow.py
import io import pytest import mitmproxy.io from mitmproxy import flow from mitmproxy import flowfilter from mitmproxy import options from mitmproxy.exceptions import FlowReadException from mitmproxy.io import tnetstring from mitmproxy.proxy import layers from mitmproxy.proxy import server_hooks from mitmproxy.test import taddons from mitmproxy.test import tflow class State: def __init__(self): self.flows = [] def request(self, f): if f not in self.flows: self.flows.append(f) def response(self, f): if f not in self.flows: self.flows.append(f) def websocket_start(self, f): if f not in self.flows: self.flows.append(f) class TestSerialize: def test_roundtrip(self): sio = io.BytesIO() f = tflow.tflow() f.marked = ":default:" f.marked = True f.comment = "test comment" f.request.content = bytes(range(256)) w = mitmproxy.io.FlowWriter(sio) w.add(f) sio.seek(0) r = mitmproxy.io.FlowReader(sio) lst = list(r.stream()) assert len(lst) == 1 f2 = lst[0] assert f2.get_state() == f.get_state() assert f2.request.data == f.request.data assert f2.marked assert f2.comment == "test comment" def test_filter(self): sio = io.BytesIO() flt = flowfilter.parse("~c 200") w = mitmproxy.io.FilteredFlowWriter(sio, flt) f = tflow.tflow(resp=True) f.response.status_code = 200 w.add(f) f = tflow.tflow(resp=True) f.response.status_code = 201 w.add(f) sio.seek(0) r = mitmproxy.io.FlowReader(sio) assert len(list(r.stream())) def test_error(self): buf = io.BytesIO() buf.write(b"bogus") buf.seek(0) r = mitmproxy.io.FlowReader(buf) with pytest.raises(FlowReadException, match="Invalid data format"): list(r.stream()) buf = io.BytesIO() f = tflow.tdummyflow() w = mitmproxy.io.FlowWriter(buf) w.add(f) buf = io.BytesIO(buf.getvalue().replace(b"dummy", b"nknwn")) r = mitmproxy.io.FlowReader(buf) with pytest.raises(FlowReadException, match="Unknown flow type"): list(r.stream()) f = FlowReadException("foo") assert str(f) == "foo" def test_versioncheck(self): f = tflow.tflow() d = f.get_state() d["version"] = (0, 0) sio = io.BytesIO() tnetstring.dump(d, sio) sio.seek(0) r = mitmproxy.io.FlowReader(sio) with pytest.raises(Exception, match="version"): list(r.stream()) def test_copy(self): """ _backup may be shared across instances. That should not raise errors. """ f = tflow.tflow() f.backup() f.request.path = "/foo" f2 = f.copy() f2.revert() f.revert() class TestFlowMaster: async def test_load_http_flow_reverse(self): opts = options.Options(mode=["reverse:https://use-this-domain"]) s = State() with taddons.context(s, options=opts) as ctx: f = tflow.tflow(resp=True) await ctx.master.load_flow(f) assert s.flows[0].request.host == "use-this-domain" async def test_all(self): opts = options.Options(mode=["reverse:https://use-this-domain"]) s = State() with taddons.context(s, options=opts) as ctx: f = tflow.tflow(req=None) await ctx.master.addons.handle_lifecycle( server_hooks.ClientConnectedHook(f.client_conn) ) f.request = mitmproxy.test.tutils.treq() await ctx.master.addons.handle_lifecycle(layers.http.HttpRequestHook(f)) assert len(s.flows) == 1 f.response = mitmproxy.test.tutils.tresp() await ctx.master.addons.handle_lifecycle(layers.http.HttpResponseHook(f)) assert len(s.flows) == 1 await ctx.master.addons.handle_lifecycle( server_hooks.ClientDisconnectedHook(f.client_conn) ) f.error = flow.Error("msg") await ctx.master.addons.handle_lifecycle(layers.http.HttpErrorHook(f)) class TestError: def test_getset_state(self): e = flow.Error("Error") state = e.get_state() assert flow.Error.from_state(state).get_state() == e.get_state() assert e.copy() e2 = flow.Error("bar") assert not e == e2 e.set_state(e2.get_state()) assert e.get_state() == e2.get_state() e3 = e.copy() assert e3.get_state() == e.get_state() def test_repr(self): e = flow.Error("yay") assert repr(e) assert str(e)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_types.py
test/mitmproxy/test_types.py
import contextlib import os from collections.abc import Sequence import pytest from . import test_command import mitmproxy.exceptions import mitmproxy.types from mitmproxy import command from mitmproxy import flow from mitmproxy.test import taddons from mitmproxy.test import tflow @contextlib.contextmanager def chdir(path: str): old_dir = os.getcwd() os.chdir(path) yield os.chdir(old_dir) def test_bool(): with taddons.context() as tctx: b = mitmproxy.types._BoolType() assert b.completion(tctx.master.commands, bool, "b") == ["false", "true"] assert b.parse(tctx.master.commands, bool, "true") is True assert b.parse(tctx.master.commands, bool, "false") is False assert b.is_valid(tctx.master.commands, bool, True) is True assert b.is_valid(tctx.master.commands, bool, "foo") is False with pytest.raises(ValueError): b.parse(tctx.master.commands, bool, "foo") def test_str(): with taddons.context() as tctx: b = mitmproxy.types._StrType() assert b.is_valid(tctx.master.commands, str, "foo") is True assert b.is_valid(tctx.master.commands, str, 1) is False assert b.completion(tctx.master.commands, str, "") == [] assert b.parse(tctx.master.commands, str, "foo") == "foo" assert b.parse(tctx.master.commands, str, r"foo\nbar") == "foo\nbar" assert b.parse(tctx.master.commands, str, r"\N{BELL}") == "🔔" with pytest.raises(ValueError): b.parse(tctx.master.commands, bool, r"\N{UNKNOWN UNICODE SYMBOL!}") def test_bytes(): with taddons.context() as tctx: b = mitmproxy.types._BytesType() assert b.is_valid(tctx.master.commands, bytes, b"foo") is True assert b.is_valid(tctx.master.commands, bytes, 1) is False assert b.completion(tctx.master.commands, bytes, "") == [] assert b.parse(tctx.master.commands, bytes, "foo") == b"foo" with pytest.raises(ValueError): b.parse(tctx.master.commands, bytes, "incomplete escape sequence\\") def test_unknown(): with taddons.context() as tctx: b = mitmproxy.types._UnknownType() assert b.is_valid(tctx.master.commands, mitmproxy.types.Unknown, "foo") is False assert b.is_valid(tctx.master.commands, mitmproxy.types.Unknown, 1) is False assert b.completion(tctx.master.commands, mitmproxy.types.Unknown, "") == [] assert b.parse(tctx.master.commands, mitmproxy.types.Unknown, "foo") == "foo" def test_int(): with taddons.context() as tctx: b = mitmproxy.types._IntType() assert b.is_valid(tctx.master.commands, int, "foo") is False assert b.is_valid(tctx.master.commands, int, 1) is True assert b.completion(tctx.master.commands, int, "b") == [] assert b.parse(tctx.master.commands, int, "1") == 1 assert b.parse(tctx.master.commands, int, "999") == 999 with pytest.raises(ValueError): b.parse(tctx.master.commands, int, "foo") def test_path(tdata, monkeypatch): with taddons.context() as tctx: b = mitmproxy.types._PathType() assert b.parse(tctx.master.commands, mitmproxy.types.Path, "/foo") == "/foo" assert b.parse(tctx.master.commands, mitmproxy.types.Path, "/bar") == "/bar" monkeypatch.setenv("HOME", "/home/test") monkeypatch.setenv("USERPROFILE", "/home/test") assert ( b.parse(tctx.master.commands, mitmproxy.types.Path, "~/mitm") == "/home/test/mitm" ) assert b.is_valid(tctx.master.commands, mitmproxy.types.Path, "foo") is True assert b.is_valid(tctx.master.commands, mitmproxy.types.Path, "~/mitm") is True assert b.is_valid(tctx.master.commands, mitmproxy.types.Path, 3) is False def normPathOpts(prefix, match): ret = [] for s in b.completion(tctx.master.commands, mitmproxy.types.Path, match): s = s[len(prefix) :] s = s.replace(os.sep, "/") ret.append(s) return ret cd = os.path.normpath(tdata.path("mitmproxy/completion")) assert normPathOpts(cd, cd) == ["/aaa", "/aab", "/aac", "/bbb/"] assert normPathOpts(cd, os.path.join(cd, "a")) == ["/aaa", "/aab", "/aac"] with chdir(cd): assert normPathOpts("", "./") == ["./aaa", "./aab", "./aac", "./bbb/"] assert normPathOpts("", "") == ["./aaa", "./aab", "./aac", "./bbb/"] assert b.completion( tctx.master.commands, mitmproxy.types.Path, "nonexistent" ) == ["nonexistent"] def test_cmd(): with taddons.context() as tctx: tctx.master.addons.add(test_command.TAddon()) b = mitmproxy.types._CmdType() assert b.is_valid(tctx.master.commands, mitmproxy.types.Cmd, "foo") is False assert b.is_valid(tctx.master.commands, mitmproxy.types.Cmd, "cmd1") is True assert b.parse(tctx.master.commands, mitmproxy.types.Cmd, "cmd1") == "cmd1" with pytest.raises(ValueError): assert b.parse(tctx.master.commands, mitmproxy.types.Cmd, "foo") assert len(b.completion(tctx.master.commands, mitmproxy.types.Cmd, "")) == len( tctx.master.commands.commands.keys() ) def test_cutspec(): with taddons.context() as tctx: b = mitmproxy.types._CutSpecType() b.parse(tctx.master.commands, mitmproxy.types.CutSpec, "foo,bar") == [ "foo", "bar", ] assert b.is_valid(tctx.master.commands, mitmproxy.types.CutSpec, 1) is False assert b.is_valid(tctx.master.commands, mitmproxy.types.CutSpec, "foo") is False assert ( b.is_valid(tctx.master.commands, mitmproxy.types.CutSpec, "request.path") is True ) assert ( b.completion(tctx.master.commands, mitmproxy.types.CutSpec, "request.p") == b.valid_prefixes ) ret = b.completion( tctx.master.commands, mitmproxy.types.CutSpec, "request.port,f" ) assert ret[0].startswith("request.port,") assert len(ret) == len(b.valid_prefixes) def test_marker(): with taddons.context() as tctx: b = mitmproxy.types._MarkerType() assert ( b.parse(tctx.master.commands, mitmproxy.types.Marker, ":red_circle:") == ":red_circle:" ) assert ( b.parse(tctx.master.commands, mitmproxy.types.Marker, "true") == ":default:" ) assert b.parse(tctx.master.commands, mitmproxy.types.Marker, "false") == "" with pytest.raises(ValueError): b.parse(tctx.master.commands, mitmproxy.types.Marker, ":bogus:") assert b.is_valid(tctx.master.commands, mitmproxy.types.Marker, "true") is True assert b.is_valid(tctx.master.commands, mitmproxy.types.Marker, "false") is True assert ( b.is_valid(tctx.master.commands, mitmproxy.types.Marker, "bogus") is False ) assert b.is_valid(tctx.master.commands, mitmproxy.types.Marker, "X") is True assert ( b.is_valid(tctx.master.commands, mitmproxy.types.Marker, ":red_circle:") is True ) ret = b.completion(tctx.master.commands, mitmproxy.types.Marker, ":smil") assert len(ret) > 10 def test_arg(): with taddons.context() as tctx: b = mitmproxy.types._ArgType() assert b.completion(tctx.master.commands, mitmproxy.types.CmdArgs, "") == [] assert b.parse(tctx.master.commands, mitmproxy.types.CmdArgs, "foo") == "foo" assert b.is_valid(tctx.master.commands, mitmproxy.types.CmdArgs, 1) is False def test_strseq(): with taddons.context() as tctx: b = mitmproxy.types._StrSeqType() assert b.completion(tctx.master.commands, Sequence[str], "") == [] assert b.parse(tctx.master.commands, Sequence[str], "foo") == ["foo"] assert b.parse(tctx.master.commands, Sequence[str], "foo,bar") == ["foo", "bar"] assert b.is_valid(tctx.master.commands, Sequence[str], ["foo"]) is True assert b.is_valid(tctx.master.commands, Sequence[str], ["a", "b", 3]) is False assert b.is_valid(tctx.master.commands, Sequence[str], 1) is False assert b.is_valid(tctx.master.commands, Sequence[str], "foo") is False class DummyConsole: @command.command("view.flows.resolve") def resolve(self, spec: str) -> Sequence[flow.Flow]: if spec == "err": raise mitmproxy.exceptions.CommandError() try: n = int(spec) except ValueError: n = 1 return [tflow.tflow(resp=True)] * n @command.command("cut") def cut(self, spec: str) -> mitmproxy.types.Data: return [["test"]] @command.command("options") def options(self) -> Sequence[str]: return ["one", "two", "three"] def test_flow(): with taddons.context() as tctx: tctx.master.addons.add(DummyConsole()) b = mitmproxy.types._FlowType() assert len(b.completion(tctx.master.commands, flow.Flow, "")) == len( b.valid_prefixes ) assert b.parse(tctx.master.commands, flow.Flow, "1") assert b.parse(tctx.master.commands, flow.Flow, "has space") assert b.is_valid(tctx.master.commands, flow.Flow, tflow.tflow()) is True assert b.is_valid(tctx.master.commands, flow.Flow, "xx") is False with pytest.raises(ValueError): b.parse(tctx.master.commands, flow.Flow, "0") with pytest.raises(ValueError): b.parse(tctx.master.commands, flow.Flow, "2") with pytest.raises(ValueError): b.parse(tctx.master.commands, flow.Flow, "err") def test_flows(): with taddons.context() as tctx: tctx.master.addons.add(DummyConsole()) b = mitmproxy.types._FlowsType() assert len(b.completion(tctx.master.commands, Sequence[flow.Flow], "")) == len( b.valid_prefixes ) assert ( b.is_valid(tctx.master.commands, Sequence[flow.Flow], [tflow.tflow()]) is True ) assert b.is_valid(tctx.master.commands, Sequence[flow.Flow], "xx") is False assert b.is_valid(tctx.master.commands, Sequence[flow.Flow], 0) is False assert len(b.parse(tctx.master.commands, Sequence[flow.Flow], "0")) == 0 assert len(b.parse(tctx.master.commands, Sequence[flow.Flow], "1")) == 1 assert len(b.parse(tctx.master.commands, Sequence[flow.Flow], "2")) == 2 assert len(b.parse(tctx.master.commands, Sequence[flow.Flow], "has space")) == 1 with pytest.raises(ValueError): b.parse(tctx.master.commands, Sequence[flow.Flow], "err") def test_data(): with taddons.context() as tctx: b = mitmproxy.types._DataType() assert b.is_valid(tctx.master.commands, mitmproxy.types.Data, 0) is False assert b.is_valid(tctx.master.commands, mitmproxy.types.Data, []) is True assert b.is_valid(tctx.master.commands, mitmproxy.types.Data, [["x"]]) is True assert b.is_valid(tctx.master.commands, mitmproxy.types.Data, [[b"x"]]) is True assert b.is_valid(tctx.master.commands, mitmproxy.types.Data, [[1]]) is False with pytest.raises(ValueError): b.parse(tctx.master.commands, mitmproxy.types.Data, "foo") with pytest.raises(ValueError): b.parse(tctx.master.commands, mitmproxy.types.Data, "foo") def test_choice(): with taddons.context() as tctx: tctx.master.addons.add(DummyConsole()) b = mitmproxy.types._ChoiceType() assert ( b.is_valid( tctx.master.commands, mitmproxy.types.Choice("options"), "one", ) is True ) assert ( b.is_valid( tctx.master.commands, mitmproxy.types.Choice("options"), "invalid", ) is False ) assert ( b.is_valid( tctx.master.commands, mitmproxy.types.Choice("nonexistent"), "invalid", ) is False ) comp = b.completion(tctx.master.commands, mitmproxy.types.Choice("options"), "") assert comp == ["one", "two", "three"] assert ( b.parse(tctx.master.commands, mitmproxy.types.Choice("options"), "one") == "one" ) with pytest.raises(ValueError): b.parse(tctx.master.commands, mitmproxy.types.Choice("options"), "invalid") def test_typemanager(): assert mitmproxy.types.CommandTypes.get(bool, None) assert mitmproxy.types.CommandTypes.get(mitmproxy.types.Choice("choide"), None)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_options.py
test/mitmproxy/test_options.py
from mitmproxy import options def test_simple(): assert options.Options()
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_connection.py
test/mitmproxy/test_connection.py
import pytest 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, ) assert not c.tls_established c.timestamp_tls_setup = 1607780792 assert c.tls_established assert c.connected c.state = ConnectionState.CAN_WRITE assert not c.connected def test_eq(self): c = tclient_conn() c2 = c.copy() assert c == c assert c != c2 assert c != 42 assert hash(c) != hash(c2) c2.id = c.id assert c == c2 class TestClient: def test_basic(self): c = Client( peername=("127.0.0.1", 52314), sockname=("127.0.0.1", 8080), timestamp_start=1607780791, cipher_list=["foo", "bar"], ) assert repr(c) assert str(c) c.timestamp_tls_setup = 1607780791 assert str(c) c.alpn = b"foo" assert str(c) == "Client(127.0.0.1:52314, state=closed, alpn=foo)" def test_state(self): c = tclient_conn() assert Client.from_state(c.get_state()).get_state() == c.get_state() c2 = tclient_conn() assert c != c2 c2.timestamp_start = 42 c.set_state(c2.get_state()) assert c.timestamp_start == 42 c3 = c.copy() assert c3.get_state() != c.get_state() c.id = c3.id = "foo" assert c3.get_state() == c.get_state() class TestServer: def test_basic(self): s = Server(address=("address", 22)) assert repr(s) assert str(s) s.timestamp_tls_setup = 1607780791 assert str(s) s.alpn = b"foo" s.sockname = ("127.0.0.1", 54321) assert str(s) == "Server(address:22, state=closed, alpn=foo, src_port=54321)" def test_state(self): c = tserver_conn() c2 = c.copy() assert c2.get_state() != c.get_state() c.id = c2.id = "foo" assert c2.get_state() == c.get_state() def test_address(self): s = Server(address=("address", 22)) s.address = ("example.com", 443) s.state = ConnectionState.OPEN with pytest.raises(RuntimeError): s.address = ("example.com", 80) # No-op assignment, allowed because it might be triggered by a Server.set_state() call. s.address = ("example.com", 443)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_proxy.py
test/mitmproxy/test_proxy.py
import argparse import pytest from mitmproxy import options from mitmproxy.tools import cmdline from mitmproxy.tools import main class MockParser(argparse.ArgumentParser): """ argparse.ArgumentParser sys.exits() by default. Make it more testable by throwing an exception instead. """ def error(self, message): raise Exception(message) class TestProcessProxyOptions: def p(self, *args): parser = MockParser() opts = options.Options() cmdline.common_options(parser, opts) args = parser.parse_args(args=args) pconf = main.process_options(parser, opts, args) return parser, pconf def assert_noerr(self, *args): m, p = self.p(*args) assert p return p def test_simple(self): assert self.p() def test_certs(self, tdata): with pytest.raises(Exception, match="ambiguous option"): self.assert_noerr("--cert", tdata.path("mitmproxy/data/testkey.pem"))
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_optmanager.py
test/mitmproxy/test_optmanager.py
import argparse import copy import io from collections.abc import Sequence from pathlib import Path from typing import Optional import pytest from mitmproxy import exceptions from mitmproxy import options from mitmproxy import optmanager class TO(optmanager.OptManager): def __init__(self): super().__init__() self.add_option("one", Optional[int], None, "help") self.add_option("two", Optional[int], 2, "help") self.add_option("bool", bool, False, "help") self.add_option("required_int", int, 2, "help") class TD(optmanager.OptManager): def __init__(self): super().__init__() self.add_option("one", str, "done", "help") self.add_option("two", str, "dtwo", "help") class TD2(TD): def __init__(self): super().__init__() self.add_option("three", str, "dthree", "help") self.add_option("four", str, "dfour", "help") class TM(optmanager.OptManager): def __init__(self): super().__init__() self.add_option("two", Sequence[str], ["foo"], "help") self.add_option("one", Optional[str], None, "help") class TS(optmanager.OptManager): def __init__(self): super().__init__() self.add_option("scripts", Sequence[str], [], "help") self.add_option("not_scripts", Sequence[str], [], "help") def test_defaults(): o = TD2() defaults = { "one": "done", "two": "dtwo", "three": "dthree", "four": "dfour", } for k, v in defaults.items(): assert o.default(k) == v assert not o.has_changed("one") newvals = dict( one="xone", two="xtwo", three="xthree", four="xfour", ) o.update(**newvals) assert o.has_changed("one") for k, v in newvals.items(): assert v == getattr(o, k) o.reset() assert not o.has_changed("one") for k in o.keys(): assert not o.has_changed(k) def test_required_int(): o = TO() with pytest.raises(exceptions.OptionsError): o._parse_setval(o._options["required_int"], []) def test_deepcopy(): o = TD() copy.deepcopy(o) def test_options(): o = TO() assert o.keys() == {"bool", "one", "two", "required_int"} assert o.one is None assert o.two == 2 o.one = 1 assert o.one == 1 with pytest.raises(TypeError): TO(nonexistent="value") with pytest.raises(Exception, match="Unknown options"): o.nonexistent = "value" with pytest.raises(Exception, match="Unknown options"): o.update(nonexistent="value") assert o.update_known(nonexistent="value") == {"nonexistent": "value"} rec = [] def sub(updated): rec.append(copy.copy(o)) o.changed.connect(sub) o.one = 90 assert len(rec) == 1 assert rec[-1].one == 90 o.update(one=3) assert len(rec) == 2 assert rec[-1].one == 3 def test_setter(): o = TO() f = o.setter("two") f(99) assert o.two == 99 with pytest.raises(Exception, match="No such option"): o.setter("nonexistent") def test_toggler(): o = TO() f = o.toggler("bool") assert o.bool is False f() assert o.bool is True f() assert o.bool is False with pytest.raises(Exception, match="No such option"): o.toggler("nonexistent") with pytest.raises(Exception, match="boolean options"): o.toggler("one") class Rec: def __init__(self): self.called = None def __call__(self, *args, **kwargs): self.called = (args, kwargs) def test_subscribe(): o = TO() r = Rec() # pytest.raises keeps a reference here that interferes with the cleanup test # further down. try: o.subscribe(r, ["unknown"]) except exceptions.OptionsError: pass else: raise AssertionError assert len(o._subscriptions) == 0 o.subscribe(r, ["two"]) o.one = 2 assert not r.called o.two = 3 assert r.called assert len(o.changed.receivers) == 1 del r o.two = 4 assert len(o._subscriptions) == 0 class binder: def __init__(self): self.o = TO() self.called = False self.o.subscribe(self.bound, ["two"]) def bound(self, *args, **kwargs): self.called = True t = binder() t.o.one = 3 assert not t.called t.o.two = 3 assert t.called def test_rollback(): o = TO() rec = [] def sub(updated): rec.append(copy.copy(o)) recerr = [] def errsub(**kwargs): recerr.append(kwargs) def err(updated): if o.one == 10: raise exceptions.OptionsError() if o.bool is True: raise exceptions.OptionsError() o.changed.connect(sub) o.changed.connect(err) o.errored.connect(errsub) assert o.one is None with pytest.raises(exceptions.OptionsError): o.one = 10 assert o.one is None with pytest.raises(exceptions.OptionsError): o.bool = True assert o.bool is False assert isinstance(recerr[0]["exc"], exceptions.OptionsError) assert o.one is None assert o.bool is False assert len(rec) == 4 assert rec[0].one == 10 assert rec[1].one is None assert rec[2].bool is True assert rec[3].bool is False with pytest.raises(exceptions.OptionsError): with o.rollback({"one"}, reraise=True): raise exceptions.OptionsError() def test_simple(): o = TO() assert repr(o) assert "one" in o with pytest.raises(Exception, match="No such option"): assert o.unknown def test_items(): assert TO().items() def test_serialize(): def serialize( opts: optmanager.OptManager, text: str, defaults: bool = False ) -> str: buf = io.StringIO() optmanager.serialize(opts, buf, text, defaults) return buf.getvalue() o = TD2() o.three = "set" assert "dfour" in serialize(o, "", defaults=True) data = serialize(o, "") assert "dfour" not in data o2 = TD2() optmanager.load(o2, data) assert o2 == o assert not o == 42 t = """ unknown: foo """ data = serialize(o, t) o2 = TD2() optmanager.load(o2, data) assert o2 == o t = "invalid: foo\ninvalid" with pytest.raises(Exception, match="Config error"): optmanager.load(o2, t) t = "invalid" with pytest.raises(Exception, match="Config error"): optmanager.load(o2, t) t = "# a comment" optmanager.load(o2, t) optmanager.load(o2, "foobar: '123'") assert o2.deferred == {"foobar": "123"} t = "" optmanager.load(o2, t) optmanager.load(o2, "foobar: '123'") assert o2.deferred == {"foobar": "123"} def test_serialize_defaults(): o = options.Options() buf = io.StringIO() optmanager.serialize(o, buf, "", defaults=True) assert buf.getvalue() def test_saving(tmpdir): o = TD2() o.three = "set" dst = Path(tmpdir.join("conf")) optmanager.save(o, dst, defaults=True) o2 = TD2() optmanager.load_paths(o2, dst) o2.three = "foo" optmanager.save(o2, dst, defaults=True) optmanager.load_paths(o, dst) assert o.three == "foo" with open(dst, "a") as f: f.write("foobar: '123'") optmanager.load_paths(o, dst) assert o.deferred == {"foobar": "123"} with open(dst, "a") as f: f.write("'''") with pytest.raises(exceptions.OptionsError): optmanager.load_paths(o, dst) with open(dst, "wb") as f: f.write(b"\x01\x02\x03") with pytest.raises(exceptions.OptionsError): optmanager.load_paths(o, dst) with pytest.raises(exceptions.OptionsError): optmanager.save(o, dst) with open(dst, "wb") as f: f.write(b"\xff\xff\xff") with pytest.raises(exceptions.OptionsError): optmanager.load_paths(o, dst) with pytest.raises(exceptions.OptionsError): optmanager.save(o, dst) def test_merge(): m = TM() m.merge(dict(one="two")) assert m.one == "two" m.merge(dict(one=None)) assert m.one == "two" m.merge(dict(two=["bar"])) assert m.two == ["foo", "bar"] def test_option(): o = optmanager._Option("test", int, 1, "help", None) assert o.current() == 1 with pytest.raises(TypeError): o.set("foo") with pytest.raises(TypeError): optmanager._Option("test", str, 1, "help", None) o2 = optmanager._Option("test", int, 1, "help", None) assert o2 == o o2.set(5) assert o2 != o def test_dump_defaults(): o = TTypes() buf = io.StringIO() optmanager.dump_defaults(o, buf) assert buf.getvalue() def test_dump_dicts(): o = options.Options() assert optmanager.dump_dicts(o) assert optmanager.dump_dicts(o, ["http2", "listen_port"]) class TTypes(optmanager.OptManager): def __init__(self): super().__init__() self.add_option("str", str, "str", "help") self.add_option("choices", str, "foo", "help", ["foo", "bar", "baz"]) self.add_option("optstr", Optional[str], "optstr", "help") self.add_option("bool", bool, False, "help") self.add_option("bool_on", bool, True, "help") self.add_option("int", int, 0, "help") self.add_option("optint", Optional[int], 0, "help") self.add_option("seqstr", Sequence[str], [], "help") self.add_option("unknown", float, 0.0, "help") def test_make_parser(): parser = argparse.ArgumentParser() opts = TTypes() opts.make_parser(parser, "str", short="a") opts.make_parser(parser, "bool", short="b") opts.make_parser(parser, "int", short="c") opts.make_parser(parser, "seqstr", short="d") opts.make_parser(parser, "bool_on", short="e") with pytest.raises(ValueError): opts.make_parser(parser, "unknown") # Nonexistent options ignore opts.make_parser(parser, "nonexistentxxx") def test_set(): opts = TTypes() opts.set("str=foo") assert opts.str == "foo" with pytest.raises(exceptions.OptionsError): opts.set("str") opts.set("optstr=foo") assert opts.optstr == "foo" opts.set("optstr") assert opts.optstr is None with pytest.raises(exceptions.OptionsError, match="Received multiple values"): opts.set("optstr=foo", "optstr=bar") opts.set("bool=false") assert opts.bool is False opts.set("bool") assert opts.bool is True opts.set("bool=true") assert opts.bool is True with pytest.raises(exceptions.OptionsError, match="Failed to parse option bool: "): opts.set("bool=wobble") opts.set("bool=toggle") assert opts.bool is False opts.set("bool=toggle") assert opts.bool is True opts.set("int=1") assert opts.int == 1 with pytest.raises(exceptions.OptionsError, match="Failed to parse option int: "): opts.set("int=wobble") opts.set("optint") assert opts.optint is None assert opts.seqstr == [] opts.set("seqstr=foo") assert opts.seqstr == ["foo"] opts.set("seqstr=foo", "seqstr=bar") assert opts.seqstr == ["foo", "bar"] opts.set("seqstr") assert opts.seqstr == [] with pytest.raises(exceptions.OptionsError): opts.set("deferredoption=wobble") opts.set("deferredoption=wobble", defer=True) assert "deferredoption" in opts.deferred opts.process_deferred() assert "deferredoption" in opts.deferred opts.add_option("deferredoption", str, "default", "help") opts.process_deferred() assert "deferredoption" not in opts.deferred assert opts.deferredoption == "wobble" opts.set(*("deferredsequenceoption=a", "deferredsequenceoption=b"), defer=True) assert "deferredsequenceoption" in opts.deferred opts.process_deferred() assert "deferredsequenceoption" in opts.deferred opts.add_option("deferredsequenceoption", Sequence[str], [], "help") opts.process_deferred() assert "deferredsequenceoption" not in opts.deferred assert opts.deferredsequenceoption == ["a", "b"] def test_load_paths(tdata): opts = TS() conf_path = tdata.path("mitmproxy/data/test_config.yml") optmanager.load_paths(opts, conf_path) assert opts.scripts == [ str(Path.home().absolute().joinpath("abc")), str(Path(conf_path).parent.joinpath("abc")), str(Path(conf_path).parent.joinpath("../abc")), str(Path("/abc").absolute()), ] assert opts.not_scripts == ["~/abc", "abc", "../abc", "/abc"] @pytest.mark.parametrize( "script_path, relative_to, expected", ( ("~/abc", ".", Path.home().joinpath("abc")), ("/abc", ".", Path("/abc")), ("abc", ".", Path(".").joinpath("abc")), ("../abc", ".", Path(".").joinpath("../abc")), ("~/abc", "/tmp", Path.home().joinpath("abc")), ("/abc", "/tmp", Path("/abc")), ("abc", "/tmp", Path("/tmp").joinpath("abc")), ("../abc", "/tmp", Path("/tmp").joinpath("../abc")), ("~/abc", "foo", Path.home().joinpath("abc")), ("/abc", "foo", Path("/abc")), ("abc", "foo", Path("foo").joinpath("abc")), ("../abc", "foo", Path("foo").joinpath("../abc")), ), ) def test_relative_path(script_path, relative_to, expected): assert ( optmanager.relative_path( script_path, relative_to=relative_to, ) == expected.absolute() )
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_typemanager.py
test/mitmproxy/test_typemanager.py
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_taddons.py
test/mitmproxy/test_taddons.py
from mitmproxy.test import taddons def test_load_script(tdata): with taddons.context() as tctx: s = tctx.script(tdata.path("mitmproxy/data/addonscripts/recorder/recorder.py")) assert s
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_command_lexer.py
test/mitmproxy/test_command_lexer.py
import pyparsing import pytest from hypothesis import example from hypothesis import given from hypothesis.strategies import text from mitmproxy import command_lexer @pytest.mark.parametrize( "test_input,valid", [ ("'foo'", True), ('"foo"', True), ("'foo' bar'", False), ("'foo' 'bar'", False), ("'foo'x", False), (""""foo """, True), (""""foo 'bar' """, True), ('"foo\\', True), ], ) def test_partial_quoted_string(test_input, valid): if valid: assert ( command_lexer.PartialQuotedString.parseString(test_input, parseAll=True)[0] == test_input ) else: with pytest.raises(pyparsing.ParseException): command_lexer.PartialQuotedString.parseString(test_input, parseAll=True) @pytest.mark.parametrize( "test_input,expected", [ ("'foo'", ["'foo'"]), ('"foo"', ['"foo"']), ("'foo' 'bar'", ["'foo'", " ", "'bar'"]), ("'foo'x", ["'foo'", "x"]), (""""foo""", ['"foo']), (""""foo 'bar' """, [""""foo 'bar' """]), ('"foo\\', ['"foo\\']), ], ) def test_expr(test_input, expected): assert list(command_lexer.expr.parseString(test_input, parseAll=True)) == expected @given(text()) @example(r"foo") @example(r"'foo\''") @example(r"'foo\"'") @example(r'"foo\""') @example(r'"foo\'"') @example("'foo\\'") @example("'foo\\\\'") @example('"foo\\\'"') @example('"foo\\\\\'"') @example("'foo\\\"'") @example(r"\\\foo") @example(r"\x22") def test_quote_unquote_cycle(s): if r"\x22" in s: return # FIXME: This edge case isn't correct at the moment. assert command_lexer.unquote(command_lexer.quote(s)).replace(r"\x22", '"') == s @given(text()) @example("'foo\\'") def test_unquote_never_fails(s): command_lexer.unquote(s)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_log.py
test/mitmproxy/test_log.py
from mitmproxy import log def test_logentry(): e = log.LogEntry("foo", "info") assert repr(e) == "LogEntry(foo, info)" f = log.LogEntry("foo", "warning") assert e == e assert e != f assert e != 42 def test_dont_pick_up_mutations(): x = {"foo": "bar"} e = log.LogEntry(x, "info") x["foo"] = "baz" # this should not affect the log entry anymore. assert repr(e) == "LogEntry({'foo': 'bar'}, info)"
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_certs.py
test/mitmproxy/test_certs.py
import ipaddress import os from datetime import datetime from datetime import timezone from pathlib import Path import pytest from cryptography import x509 from cryptography.x509 import NameOID from ..conftest import skip_windows from mitmproxy import certs # class TestDNTree: # def test_simple(self): # d = certs.DNTree() # d.add("foo.com", "foo") # d.add("bar.com", "bar") # assert d.get("foo.com") == "foo" # assert d.get("bar.com") == "bar" # assert not d.get("oink.com") # assert not d.get("oink") # assert not d.get("") # assert not d.get("oink.oink") # # d.add("*.match.org", "match") # assert not d.get("match.org") # assert d.get("foo.match.org") == "match" # assert d.get("foo.foo.match.org") == "match" # # def test_wildcard(self): # d = certs.DNTree() # d.add("foo.com", "foo") # assert not d.get("*.foo.com") # d.add("*.foo.com", "wild") # # d = certs.DNTree() # d.add("*", "foo") # assert d.get("foo.com") == "foo" # assert d.get("*.foo.com") == "foo" # assert d.get("com") == "foo" @pytest.fixture() def tstore(tdata): return certs.CertStore.from_store( tdata.path("mitmproxy/data/confdir"), "mitmproxy", 2048 ) class TestCertStore: def test_create_explicit(self, tmpdir): ca = certs.CertStore.from_store(str(tmpdir), "test", 2048) assert ca.get_cert("foo", []) ca2 = certs.CertStore.from_store(str(tmpdir), "test", 2048) assert ca2.get_cert("foo", []) assert ca.default_ca.serial == ca2.default_ca.serial def test_create_no_common_name(self, tstore): assert tstore.get_cert(None, []).cert.cn is None def test_chain_file(self, tdata, tmp_path): cert = Path(tdata.path("mitmproxy/data/confdir/mitmproxy-ca.pem")).read_bytes() (tmp_path / "mitmproxy-ca.pem").write_bytes(cert) ca = certs.CertStore.from_store(tmp_path, "mitmproxy", 2048) assert ca.default_chain_file is None assert len(ca.default_chain_certs) == 1 (tmp_path / "mitmproxy-ca.pem").write_bytes(2 * cert) ca = certs.CertStore.from_store(tmp_path, "mitmproxy", 2048) assert ca.default_chain_file == (tmp_path / "mitmproxy-ca.pem") assert len(ca.default_chain_certs) == 2 def test_sans(self, tstore): c1 = tstore.get_cert("foo.com", [x509.DNSName("*.bar.com")]) tstore.get_cert("foo.bar.com", []) # assert c1 == c2 c3 = tstore.get_cert("bar.com", []) assert not c1 == c3 def test_sans_change(self, tstore): tstore.get_cert("foo.com", [x509.DNSName("*.bar.com")]) entry = tstore.get_cert("foo.bar.com", [x509.DNSName("*.baz.com")]) assert x509.DNSName("*.baz.com") in entry.cert.altnames def test_expire(self, tstore): tstore.STORE_CAP = 3 tstore.get_cert("one.com", []) tstore.get_cert("two.com", []) tstore.get_cert("three.com", []) assert ("one.com", x509.GeneralNames([])) in tstore.certs assert ("two.com", x509.GeneralNames([])) in tstore.certs assert ("three.com", x509.GeneralNames([])) in tstore.certs tstore.get_cert("one.com", []) assert ("one.com", x509.GeneralNames([])) in tstore.certs assert ("two.com", x509.GeneralNames([])) in tstore.certs assert ("three.com", x509.GeneralNames([])) in tstore.certs tstore.get_cert("four.com", []) assert ("one.com", x509.GeneralNames([])) not in tstore.certs assert ("two.com", x509.GeneralNames([])) in tstore.certs assert ("three.com", x509.GeneralNames([])) in tstore.certs assert ("four.com", x509.GeneralNames([])) in tstore.certs def test_create_dhparams(self, tmp_path): filename = tmp_path / "dhparam.pem" certs.CertStore.load_dhparam(filename) assert filename.exists() @skip_windows def test_umask_secret(self, tmpdir): filename = str(tmpdir.join("secret")) with certs.CertStore.umask_secret(), open(filename, "wb"): pass # TODO: How do we actually attempt to read that file as another user? assert os.stat(filename).st_mode & 0o77 == 0 @pytest.mark.parametrize( "input,output", [ ( "subdomain.example.com", ["subdomain.example.com", "*.example.com", "*.com"], ), ( x509.DNSName("subdomain.example.com"), ["subdomain.example.com", "*.example.com", "*.com"], ), (x509.IPAddress(ipaddress.ip_address("127.0.0.1")), ["127.0.0.1"]), ], ) def test_asterisk_forms(self, input, output): assert certs.CertStore.asterisk_forms(input) == output class TestDummyCert: def test_with_ca(self, tstore): r = certs.dummy_cert( tstore.default_privatekey, tstore.default_ca._cert, "foo.com", [ x509.DNSName("one.com"), x509.DNSName("two.com"), x509.DNSName("*.three.com"), x509.IPAddress(ipaddress.ip_address("127.0.0.1")), x509.DNSName("bücher.example".encode("idna").decode("ascii")), ], "Foo Ltd.", crl_url="https://example.com/example.crl", ) assert r.cn == "foo.com" assert r.altnames == x509.GeneralNames( [ x509.DNSName("one.com"), x509.DNSName("two.com"), x509.DNSName("*.three.com"), x509.IPAddress(ipaddress.ip_address("127.0.0.1")), x509.DNSName("xn--bcher-kva.example"), ] ) assert r.organization == "Foo Ltd." assert r.crl_distribution_points == ["https://example.com/example.crl"] r = certs.dummy_cert( tstore.default_privatekey, tstore.default_ca._cert, None, [], None, None ) assert r.cn is None assert r.organization is None assert r.altnames == x509.GeneralNames([]) assert r.crl_distribution_points == [] class TestCert: def test_simple(self, tdata): with open(tdata.path("mitmproxy/net/data/text_cert"), "rb") as f: d = f.read() c1 = certs.Cert.from_pem(d) assert c1.cn == "google.com" assert len(c1.altnames) == 436 assert c1.organization == "Google Inc" assert hash(c1) with open(tdata.path("mitmproxy/net/data/text_cert_2"), "rb") as f: d = f.read() c2 = certs.Cert.from_pem(d) assert c2.cn == "www.inode.co.nz" assert len(c2.altnames) == 2 assert c2.fingerprint() assert c2.public_key() assert c2.notbefore == datetime( year=2010, month=1, day=11, hour=19, minute=27, second=36, tzinfo=timezone.utc, ) assert c2.notafter == datetime( year=2011, month=1, day=12, hour=9, minute=14, second=55, tzinfo=timezone.utc, ) assert c2.subject assert c2.keyinfo == ("RSA", 2048) assert c2.serial assert c2.issuer assert c2.to_pem() assert c2.has_expired() is not None assert ( repr(c2) == "<Cert(cn='www.inode.co.nz', altnames=['www.inode.co.nz', 'inode.co.nz'])>" ) assert c1 != c2 def test_convert(self, tdata): with open(tdata.path("mitmproxy/net/data/text_cert"), "rb") as f: d = f.read() c = certs.Cert.from_pem(d) assert c == certs.Cert.from_pem(c.to_pem()) assert c == certs.Cert.from_state(c.get_state()) with pytest.deprecated_call(): assert c == certs.Cert.from_pyopenssl(c.to_pyopenssl()) assert c == certs.Cert(c.to_cryptography()) @pytest.mark.parametrize( "filename,name,bits", [ ("text_cert", "RSA", 1024), ("dsa_cert.pem", "DSA", 1024), ("ec_cert.pem", "EC (secp256r1)", 256), ], ) def test_keyinfo(self, tdata, filename, name, bits): with open(tdata.path(f"mitmproxy/net/data/{filename}"), "rb") as f: d = f.read() c = certs.Cert.from_pem(d) assert c.keyinfo == (name, bits) @pytest.mark.parametrize( "filename,is_ca", [ ("mitmproxy/net/data/verificationcerts/trusted-leaf.crt", False), ("mitmproxy/net/data/verificationcerts/trusted-root.crt", True), ("mitmproxy/data/invalid-subject.pem", False), # no basic constraints ], ) def test_is_ca(self, tdata, filename, is_ca): pem = Path(tdata.path(filename)).read_bytes() cert = certs.Cert.from_pem(pem) assert cert.is_ca == is_ca def test_err_broken_sans(self, tdata): with open(tdata.path("mitmproxy/net/data/text_cert_weird1"), "rb") as f: d = f.read() c = certs.Cert.from_pem(d) # This breaks unless we ignore a decoding error. assert c.altnames is not None def test_state(self, tdata): with open(tdata.path("mitmproxy/net/data/text_cert"), "rb") as f: d = f.read() c = certs.Cert.from_pem(d) c.get_state() c2 = c.copy() a = c.get_state() b = c2.get_state() assert a == b assert c == c2 assert c is not c2 c2.set_state(a) assert c == c2 def test_add_cert_overrides(self, tdata, tstore): certfile = Path( tdata.path("mitmproxy/net/data/verificationcerts/trusted-leaf.pem") ) cert = certs.Cert.from_pem(certfile.read_bytes()) tstore.add_cert_file("example.com", certfile) assert cert == tstore.get_cert("example.com", []).cert def test_from_store_with_passphrase(self, tdata, tstore): tstore.add_cert_file( "unencrypted-no-pass", Path(tdata.path("mitmproxy/data/testkey.pem")), None ) tstore.add_cert_file( "unencrypted-pass", Path(tdata.path("mitmproxy/data/testkey.pem")), b"password", ) tstore.add_cert_file( "encrypted-pass", Path(tdata.path("mitmproxy/data/mitmproxy.pem")), b"password", ) with pytest.raises(TypeError): tstore.add_cert_file( "encrypted-no-pass", Path(tdata.path("mitmproxy/data/mitmproxy.pem")), None, ) def test_add_cert_with_no_private_key(self, tdata, tstore): with pytest.raises(ValueError, match="Unable to find private key"): tstore.add_cert_file( "example.com", Path( tdata.path("mitmproxy/net/data/verificationcerts/trusted-leaf.crt") ), ) def test_add_cert_private_public_mismatch(self, tdata, tstore): with pytest.raises( ValueError, match='Private and public keys in ".+" do not match' ): tstore.add_cert_file( "example.com", Path( tdata.path( "mitmproxy/net/data/verificationcerts/private-public-mismatch.pem" ) ), ) def test_add_cert_chain(self, tdata, tstore): tstore.add_cert_file( "example.com", Path(tdata.path("mitmproxy/net/data/verificationcerts/trusted-chain.pem")), ) assert len(tstore.get_cert("example.com", []).chain_certs) == 2 def test_add_cert_chain_invalid(self, tdata, tstore, caplog): tstore.add_cert_file( "example.com", Path( tdata.path( "mitmproxy/net/data/verificationcerts/trusted-chain-invalid.pem" ) ), ) assert "Failed to read certificate chain" in caplog.text assert len(tstore.get_cert("example.com", []).chain_certs) == 1 def test_add_cert_is_ca(self, tdata, tstore, caplog): tstore.add_cert_file( "example.com", Path(tdata.path("mitmproxy/net/data/verificationcerts/trusted-root.pem")), ) assert "is a certificate authority and not a leaf certificate" in caplog.text def test_special_character(self, tdata): with open(tdata.path("mitmproxy/net/data/text_cert_with_comma"), "rb") as f: d = f.read() c = certs.Cert.from_pem(d) assert dict(c.issuer).get("O") == "DigiCert, Inc." assert dict(c.subject).get("O") == "GitHub, Inc." def test_multi_valued_rdns(self, tdata): subject = x509.Name( [ x509.RelativeDistinguishedName( [ x509.NameAttribute(NameOID.TITLE, "Test"), x509.NameAttribute(NameOID.COMMON_NAME, "Multivalue"), x509.NameAttribute(NameOID.SURNAME, "RDNs"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "TSLA"), ] ), x509.RelativeDistinguishedName( [x509.NameAttribute(NameOID.ORGANIZATION_NAME, "PyCA")] ), ] ) expected = [ ("2.5.4.12", "Test"), ("CN", "Multivalue"), ("2.5.4.4", "RDNs"), ("O", "TSLA"), ("O", "PyCA"), ] assert (certs._name_to_keyval(subject)) == expected @pytest.mark.parametrize( "filename,crls", [ pytest.param( "mitmproxy/net/data/verificationcerts/trusted-leaf.crt", ["https://trusted-root/example.crl"], id="with-crl", ), pytest.param( "mitmproxy/net/data/verificationcerts/invalid-crl.crt", ["//["], id="invalid-crl", ), pytest.param( "mitmproxy/net/data/verificationcerts/trusted-root.crt", [], id="without-crl", ), ], ) def test_crl_distribution_points(self, tdata, filename, crls): pem = Path(tdata.path(filename)).read_bytes() cert = certs.Cert.from_pem(pem) assert cert.crl_distribution_points == crls
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_command.py
test/mitmproxy/test_command.py
import inspect import io from collections.abc import Sequence import pytest import mitmproxy.types from mitmproxy import command from mitmproxy import exceptions from mitmproxy import flow from mitmproxy.flow import Flow from mitmproxy.test import taddons from mitmproxy.test import tflow class TAddon: @command.command("cmd1") def cmd1(self, foo: str) -> str: """cmd1 help""" return "ret " + foo @command.command("cmd2") def cmd2(self, foo: str) -> str: return 99 @command.command("cmd3") def cmd3(self, foo: int) -> int: return foo @command.command("cmd4") def cmd4(self, a: int, b: str, c: mitmproxy.types.Path) -> str: return "ok" @command.command("subcommand") def subcommand( self, cmd: mitmproxy.types.Cmd, *args: mitmproxy.types.CmdArgs ) -> str: return "ok" @command.command("empty") def empty(self) -> None: pass @command.command("varargs") def varargs(self, one: str, *var: str) -> Sequence[str]: return list(var) def choices(self) -> Sequence[str]: return ["one", "two", "three"] @command.argument("arg", type=mitmproxy.types.Choice("choices")) def choose(self, arg: str) -> Sequence[str]: return ["one", "two", "three"] @command.command("path") def path(self, arg: mitmproxy.types.Path) -> None: pass @command.command("flow") def flow(self, f: Flow, s: str) -> None: pass class Unsupported: pass class TypeErrAddon: @command.command("noret") def noret(self): pass @command.command("invalidret") def invalidret(self) -> Unsupported: pass @command.command("invalidarg") def invalidarg(self, u: Unsupported): pass class TestCommand: def test_typecheck(self): with taddons.context(loadcore=False) as tctx: cm = command.CommandManager(tctx.master) a = TypeErrAddon() command.Command(cm, "noret", a.noret) with pytest.raises(exceptions.CommandError): command.Command(cm, "invalidret", a.invalidret) with pytest.raises(exceptions.CommandError): assert command.Command(cm, "invalidarg", a.invalidarg) def test_varargs(self): with taddons.context() as tctx: cm = command.CommandManager(tctx.master) a = TAddon() c = command.Command(cm, "varargs", a.varargs) assert c.signature_help() == "varargs one *var -> str[]" assert c.call(["one", "two", "three"]) == ["two", "three"] def test_call(self): with taddons.context() as tctx: cm = command.CommandManager(tctx.master) a = TAddon() c = command.Command(cm, "cmd.path", a.cmd1) assert c.call(["foo"]) == "ret foo" assert c.signature_help() == "cmd.path foo -> str" c = command.Command(cm, "cmd.two", a.cmd2) with pytest.raises(exceptions.CommandError): c.call(["foo"]) c = command.Command(cm, "cmd.three", a.cmd3) assert c.call(["1"]) == 1 def test_parse_partial(self): tests = [ [ "foo bar", [ command.ParseResult( value="foo", type=mitmproxy.types.Cmd, valid=False ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value="bar", type=mitmproxy.types.Unknown, valid=False ), ], [], ], [ "cmd1 'bar", [ command.ParseResult( value="cmd1", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult(value="'bar", type=str, valid=True), ], [], ], [ "a", [command.ParseResult(value="a", type=mitmproxy.types.Cmd, valid=False)], [], ], [ "", [], [ command.CommandParameter("", mitmproxy.types.Cmd), command.CommandParameter("", mitmproxy.types.CmdArgs), ], ], [ "cmd3 1", [ command.ParseResult( value="cmd3", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult(value="1", type=int, valid=True), ], [], ], [ "cmd3 ", [ command.ParseResult( value="cmd3", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), ], [command.CommandParameter("foo", int)], ], [ "subcommand ", [ command.ParseResult( value="subcommand", type=mitmproxy.types.Cmd, valid=True, ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), ], [ command.CommandParameter("cmd", mitmproxy.types.Cmd), command.CommandParameter( "args", mitmproxy.types.CmdArgs, kind=inspect.Parameter.VAR_POSITIONAL, ), ], ], [ "varargs one", [ command.ParseResult( value="varargs", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult(value="one", type=str, valid=True), ], [ command.CommandParameter( "var", str, kind=inspect.Parameter.VAR_POSITIONAL ) ], ], [ "varargs one two three", [ command.ParseResult( value="varargs", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult(value="one", type=str, valid=True), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult(value="two", type=str, valid=True), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult(value="three", type=str, valid=True), ], [], ], [ "subcommand cmd3 ", [ command.ParseResult( value="subcommand", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value="cmd3", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), ], [command.CommandParameter("foo", int)], ], [ "cmd4", [ command.ParseResult( value="cmd4", type=mitmproxy.types.Cmd, valid=True ), ], [ command.CommandParameter("a", int), command.CommandParameter("b", str), command.CommandParameter("c", mitmproxy.types.Path), ], ], [ "cmd4 ", [ command.ParseResult( value="cmd4", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), ], [ command.CommandParameter("a", int), command.CommandParameter("b", str), command.CommandParameter("c", mitmproxy.types.Path), ], ], [ "cmd4 1", [ command.ParseResult( value="cmd4", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult(value="1", type=int, valid=True), ], [ command.CommandParameter("b", str), command.CommandParameter("c", mitmproxy.types.Path), ], ], [ "flow", [ command.ParseResult( value="flow", type=mitmproxy.types.Cmd, valid=True ), ], [ command.CommandParameter("f", flow.Flow), command.CommandParameter("s", str), ], ], [ "flow ", [ command.ParseResult( value="flow", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), ], [ command.CommandParameter("f", flow.Flow), command.CommandParameter("s", str), ], ], [ "flow x", [ command.ParseResult( value="flow", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult(value="x", type=flow.Flow, valid=False), ], [ command.CommandParameter("s", str), ], ], [ "flow x ", [ command.ParseResult( value="flow", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult(value="x", type=flow.Flow, valid=False), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), ], [ command.CommandParameter("s", str), ], ], [ 'flow "one two', [ command.ParseResult( value="flow", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult(value='"one two', type=flow.Flow, valid=False), ], [ command.CommandParameter("s", str), ], ], [ 'flow "three four"', [ command.ParseResult( value="flow", type=mitmproxy.types.Cmd, valid=True ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value='"three four"', type=flow.Flow, valid=False ), ], [ command.CommandParameter("s", str), ], ], [ "spaces ' '", [ command.ParseResult( value="spaces", type=mitmproxy.types.Cmd, valid=False ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value="' '", type=mitmproxy.types.Unknown, valid=False ), ], [], ], [ 'spaces2 " "', [ command.ParseResult( value="spaces2", type=mitmproxy.types.Cmd, valid=False ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value='" "', type=mitmproxy.types.Unknown, valid=False ), ], [], ], [ '"abc"', [ command.ParseResult( value='"abc"', type=mitmproxy.types.Cmd, valid=False ), ], [], ], [ "'def'", [ command.ParseResult( value="'def'", type=mitmproxy.types.Cmd, valid=False ), ], [], ], [ "cmd10 'a' \"b\" c", [ command.ParseResult( value="cmd10", type=mitmproxy.types.Cmd, valid=False ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value="'a'", type=mitmproxy.types.Unknown, valid=False ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value='"b"', type=mitmproxy.types.Unknown, valid=False ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value="c", type=mitmproxy.types.Unknown, valid=False ), ], [], ], [ "cmd11 'a \"b\" c'", [ command.ParseResult( value="cmd11", type=mitmproxy.types.Cmd, valid=False ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value="'a \"b\" c'", type=mitmproxy.types.Unknown, valid=False ), ], [], ], [ "cmd12 \"a 'b' c\"", [ command.ParseResult( value="cmd12", type=mitmproxy.types.Cmd, valid=False ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value="\"a 'b' c\"", type=mitmproxy.types.Unknown, valid=False ), ], [], ], [ " spaces_at_the_begining_are_not_stripped", [ command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value="spaces_at_the_begining_are_not_stripped", type=mitmproxy.types.Cmd, valid=False, ), ], [], ], [ " spaces_at_the_begining_are_not_stripped neither_at_the_end ", [ command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value="spaces_at_the_begining_are_not_stripped", type=mitmproxy.types.Cmd, valid=False, ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), command.ParseResult( value="neither_at_the_end", type=mitmproxy.types.Unknown, valid=False, ), command.ParseResult( value=" ", type=mitmproxy.types.Space, valid=True ), ], [], ], ] with taddons.context() as tctx: tctx.master.addons.add(TAddon()) for s, expected, expectedremain in tests: current, remain = tctx.master.commands.parse_partial(s) assert (s, current, expectedremain) == (s, expected, remain) def test_simple(): with taddons.context() as tctx: c = command.CommandManager(tctx.master) a = TAddon() c.add("one.two", a.cmd1) assert c.commands["one.two"].help == "cmd1 help" assert c.execute("one.two foo") == "ret foo" assert c.execute('one.two "foo"') == "ret foo" assert c.execute("one.two 'foo bar'") == "ret foo bar" assert c.call("one.two", "foo") == "ret foo" with pytest.raises(exceptions.CommandError, match="Unknown"): c.execute("nonexistent") with pytest.raises(exceptions.CommandError, match="Invalid"): c.execute("") with pytest.raises(exceptions.CommandError, match="argument mismatch"): c.execute("one.two too many args") with pytest.raises(exceptions.CommandError, match="Unknown"): c.call("nonexistent") with pytest.raises(exceptions.CommandError, match="Unknown"): c.execute("\\") c.add("empty", a.empty) c.execute("empty") fp = io.StringIO() c.dump(fp) assert fp.getvalue() def test_typename(): assert command.typename(str) == "str" assert command.typename(Sequence[flow.Flow]) == "flow[]" assert command.typename(mitmproxy.types.Data) == "data[][]" assert command.typename(mitmproxy.types.CutSpec) == "cut[]" assert command.typename(flow.Flow) == "flow" assert command.typename(Sequence[str]) == "str[]" assert command.typename(mitmproxy.types.Choice("foo")) == "choice" assert command.typename(mitmproxy.types.Path) == "path" assert command.typename(mitmproxy.types.Cmd) == "cmd" with pytest.raises(exceptions.CommandError, match="missing type annotation"): command.typename(inspect._empty) with pytest.raises(exceptions.CommandError, match="unsupported type"): command.typename(None) class DummyConsole: @command.command("view.flows.resolve") def resolve(self, spec: str) -> Sequence[flow.Flow]: n = int(spec) return [tflow.tflow(resp=True)] * n @command.command("cut") def cut(self, spec: str) -> mitmproxy.types.Data: return [["test"]] def test_parsearg(): with taddons.context() as tctx: tctx.master.addons.add(DummyConsole()) assert command.parsearg(tctx.master.commands, "foo", str) == "foo" with pytest.raises(exceptions.CommandError, match="Unsupported"): command.parsearg(tctx.master.commands, "foo", type) with pytest.raises(exceptions.CommandError): command.parsearg(tctx.master.commands, "foo", int) class TDec: @command.command("cmd1") def cmd1(self, foo: str) -> str: """cmd1 help""" return "ret " + foo @command.command("cmd2") def cmd2(self, foo: str) -> str: return 99 @command.command("empty") def empty(self) -> None: pass class TAttr: def __getattr__(self, item): raise OSError class TAttr2: def __getattr__(self, item): return TAttr2() class TCmds(TAttr): def __init__(self): self.TAttr = TAttr() self.TAttr2 = TAttr2() @command.command("empty") def empty(self) -> None: pass async def test_collect_commands(caplog): """ This tests for errors thrown by getattr() or __getattr__ implementations that return an object for .command_name. """ with taddons.context() as tctx: c = command.CommandManager(tctx.master) a = TCmds() c.collect_commands(a) assert "empty" in c.commands a = TypeErrAddon() c.collect_commands(a) assert "Could not load" in caplog.text def test_decorator(): with taddons.context() as tctx: c = command.CommandManager(tctx.master) a = TDec() c.collect_commands(a) assert "cmd1" in c.commands assert c.execute("cmd1 bar") == "ret bar" assert "empty" in c.commands assert c.execute("empty") is None with taddons.context() as tctx: tctx.master.addons.add(a) assert tctx.master.commands.execute("cmd1 bar") == "ret bar" def test_verify_arg_signature(): with pytest.raises(exceptions.CommandError): command.verify_arg_signature(lambda: None, [1, 2], {}) print("hello there") command.verify_arg_signature(lambda a, b: None, [1, 2], {})
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_version.py
test/mitmproxy/test_version.py
import pathlib import runpy import subprocess import sys from unittest import mock from mitmproxy import version def test_version(capsys): here = pathlib.Path(__file__).absolute().parent version_file = here / ".." / ".." / "mitmproxy" / "version.py" runpy.run_path(str(version_file), run_name="__main__") stdout, stderr = capsys.readouterr() assert len(stdout) > 0 assert stdout.strip() == version.VERSION def test_get_version(monkeypatch): monkeypatch.setattr(version, "VERSION", "3.0.0rc2") with mock.patch("subprocess.check_output") as m, mock.patch("subprocess.run") as m2: m2.return_value = True m.return_value = b"tag-0-cafecafe" assert version.get_dev_version() == "3.0.0rc2" sys.frozen = True assert version.get_dev_version() == "3.0.0rc2 binary" sys.frozen = False m.return_value = b"tag-2-cafecafe" assert version.get_dev_version() == "3.0.0rc2 (+2, commit cafecaf)" m.side_effect = subprocess.CalledProcessError(-1, "git describe --tags --long") assert version.get_dev_version() == "3.0.0rc2"
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_tcp.py
test/mitmproxy/test_tcp.py
import pytest from mitmproxy import flowfilter from mitmproxy import tcp from mitmproxy.test import tflow class TestTCPFlow: def test_copy(self): f = tflow.ttcpflow() f.get_state() f2 = f.copy() a = f.get_state() b = f2.get_state() del a["id"] del b["id"] assert a == b assert not f == f2 assert f is not f2 assert f.messages is not f2.messages for m in f.messages: assert m.get_state() m2 = m.copy() assert not m == m2 assert m is not m2 a = m.get_state() b = m2.get_state() assert a == b m = tcp.TCPMessage(False, "foo") m.set_state(f.messages[0].get_state()) assert m.timestamp == f.messages[0].timestamp f = tflow.ttcpflow(err=True) f2 = f.copy() assert f is not f2 assert f.error.get_state() == f2.error.get_state() assert f.error is not f2.error def test_match(self): f = tflow.ttcpflow() assert not flowfilter.match("~b nonexistent", f) assert flowfilter.match(None, f) assert not flowfilter.match("~b nonexistent", f) f = tflow.ttcpflow(err=True) assert flowfilter.match("~e", f) with pytest.raises(ValueError): flowfilter.match("~", f) def test_repr(self): f = tflow.ttcpflow() assert "TCPFlow" in repr(f) assert "-> " in repr(f.messages[0])
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/__init__.py
test/mitmproxy/__init__.py
# Silence third-party modules import logging logging.getLogger("hyper").setLevel(logging.WARNING) logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("passlib").setLevel(logging.WARNING) logging.getLogger("tornado").setLevel(logging.WARNING)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_flowfilter.py
test/mitmproxy/test_flowfilter.py
import io from unittest.mock import patch import pytest from mitmproxy import flowfilter from mitmproxy import http from mitmproxy.test import tflow class TestParsing: def _dump(self, x): c = io.StringIO() x.dump(fp=c) assert c.getvalue() def test_parse_err(self): with pytest.raises(ValueError, match="Empty filter"): flowfilter.parse("") with pytest.raises(ValueError, match="Invalid filter"): flowfilter.parse("~b") with pytest.raises(ValueError, match="Invalid filter"): flowfilter.parse("~h [") def test_simple(self): assert flowfilter.parse("~q") assert flowfilter.parse("~c 10") assert flowfilter.parse("~m foobar") assert flowfilter.parse("~u foobar") assert flowfilter.parse("~q ~c 10") assert flowfilter.parse("~replay") assert flowfilter.parse("~replayq") assert flowfilter.parse("~replays") assert flowfilter.parse("~comment .") p = flowfilter.parse("~q ~c 10") self._dump(p) assert len(p.lst) == 2 def test_non_ascii(self): assert flowfilter.parse("~s шгн") def test_naked_url(self): a = flowfilter.parse("foobar ~h rex") assert a.lst[0].expr == "foobar" assert a.lst[1].expr == "rex" self._dump(a) def test_quoting(self): a = flowfilter.parse("~u 'foo ~u bar' ~u voing") assert a.lst[0].expr == "foo ~u bar" assert a.lst[1].expr == "voing" self._dump(a) a = flowfilter.parse("~u foobar") assert a.expr == "foobar" a = flowfilter.parse(r"~u 'foobar\"\''") assert a.expr == "foobar\"'" a = flowfilter.parse(r'~u "foo \'bar"') assert a.expr == "foo 'bar" def test_nesting(self): a = flowfilter.parse("(~u foobar & ~h voing)") assert a.lst[0].expr == "foobar" self._dump(a) def test_not(self): a = flowfilter.parse("!~h test") assert a.itm.expr == "test" a = flowfilter.parse("!(~u test & ~h bar)") assert a.itm.lst[0].expr == "test" self._dump(a) def test_binaryops(self): a = flowfilter.parse("~u foobar | ~h voing") isinstance(a, flowfilter.FOr) self._dump(a) a = flowfilter.parse("~u foobar & ~h voing") isinstance(a, flowfilter.FAnd) self._dump(a) def test_wideops(self): a = flowfilter.parse("~hq 'header: qvalue'") assert isinstance(a, flowfilter.FHeadRequest) self._dump(a) class TestMatchingHTTPFlow: def req(self): return tflow.tflow() def resp(self): return tflow.tflow(resp=True) def err(self): return tflow.tflow(err=True) def q(self, q, o): return flowfilter.parse(q)(o) def test_http(self): s = self.req() assert self.q("~http", s) assert not self.q("~tcp", s) def test_asset(self): s = self.resp() assert not self.q("~a", s) s.response.headers["content-type"] = "text/javascript" assert self.q("~a", s) def test_fcontenttype(self): q = self.req() s = self.resp() assert not self.q("~t content", q) assert not self.q("~t content", s) q.request.headers["content-type"] = "text/json" assert self.q("~t json", q) assert self.q("~tq json", q) assert not self.q("~ts json", q) s.response.headers["content-type"] = "text/json" assert self.q("~t json", s) del s.response.headers["content-type"] s.request.headers["content-type"] = "text/json" assert self.q("~t json", s) assert self.q("~tq json", s) assert not self.q("~ts json", s) def test_freq_fresp(self): q = self.req() s = self.resp() assert self.q("~q", q) assert not self.q("~q", s) assert not self.q("~s", q) assert self.q("~s", s) def test_ferr(self): e = self.err() assert self.q("~e", e) def test_fmarked(self): q = self.req() assert not self.q("~marked", q) q.marked = ":default:" assert self.q("~marked", q) def test_fmarker_char(self): t = tflow.tflow() t.marked = ":default:" assert not self.q("~marker X", t) t.marked = "X" assert self.q("~marker X", t) def test_head(self): q = self.req() s = self.resp() assert not self.q("~h nonexistent", q) assert self.q("~h qvalue", q) assert self.q("~h header", q) assert self.q("~h 'header: qvalue'", q) assert self.q("~h 'header: qvalue'", s) assert self.q("~h 'header-response: svalue'", s) assert self.q("~hq 'header: qvalue'", s) assert not self.q("~hq 'header-response: svalue'", s) assert self.q("~hq 'header: qvalue'", q) assert not self.q("~hq 'header-request: svalue'", q) assert not self.q("~hs 'header: qvalue'", s) assert self.q("~hs 'header-response: svalue'", s) assert not self.q("~hs 'header: qvalue'", q) def match_body(self, q, s): assert not self.q("~b nonexistent", q) assert self.q("~b content", q) assert self.q("~b message", s) assert not self.q("~bq nomatch", s) assert self.q("~bq content", q) assert self.q("~bq content", s) assert not self.q("~bq message", q) assert not self.q("~bq message", s) s.response.text = "яч" # Cyrillic assert self.q("~bs яч", s) s.response.text = "测试" # Chinese assert self.q("~bs 测试", s) s.response.text = "ॐ" # Hindi assert self.q("~bs ॐ", s) s.response.text = "لله" # Arabic assert self.q("~bs لله", s) s.response.text = "θεός" # Greek assert self.q("~bs θεός", s) s.response.text = "לוהים" # Hebrew assert self.q("~bs לוהים", s) s.response.text = "神" # Japanese assert self.q("~bs 神", s) s.response.text = "하나님" # Korean assert self.q("~bs 하나님", s) s.response.text = "Äÿ" # Latin assert self.q("~bs Äÿ", s) assert not self.q("~bs nomatch", s) assert not self.q("~bs content", q) assert not self.q("~bs content", s) assert not self.q("~bs message", q) s.response.text = "message" assert self.q("~bs message", s) def test_body(self): q = self.req() s = self.resp() self.match_body(q, s) q.request.encode("gzip") s.request.encode("gzip") s.response.encode("gzip") self.match_body(q, s) def test_case_sensitive(self, monkeypatch): q = self.req() monkeypatch.setenv("MITMPROXY_CASE_SENSITIVE_FILTERS", "0") assert self.q("~m get", q) assert self.q("~m GET", q) assert not self.q("~m post", q) q.request.method = "oink" assert not self.q("~m get", q) monkeypatch.setenv("MITMPROXY_CASE_SENSITIVE_FILTERS", "1") assert not self.q("~m get", q) assert not self.q("~m GET", q) assert not self.q("~m post", q) q.request.method = "oink" assert not self.q("~m get", q) def test_method(self): q = self.req() assert self.q("~m get", q) assert not self.q("~m post", q) q.request.method = "oink" assert not self.q("~m get", q) def test_domain(self): q = self.req() assert self.q("~d address", q) assert not self.q("~d none", q) def test_url(self): q = self.req() s = self.resp() assert self.q("~u address", q) assert self.q("~u address:22/path", q) assert not self.q("~u moo/path", q) q.request = None assert not self.q("~u address", q) assert self.q("~u address", s) assert self.q("~u address:22/path", s) assert not self.q("~u moo/path", s) def test_code(self): q = self.req() s = self.resp() assert not self.q("~c 200", q) assert self.q("~c 200", s) assert not self.q("~c 201", s) def test_src(self): q = self.req() assert self.q("~src 127.0.0.1", q) assert not self.q("~src foobar", q) assert self.q("~src :22", q) assert not self.q("~src :99", q) assert self.q("~src 127.0.0.1:22", q) q.client_conn.peername = None assert not self.q("~src address:22", q) q.client_conn = None assert not self.q("~src address:22", q) def test_dst(self): q = self.req() q.server_conn = tflow.tserver_conn() assert self.q("~dst address", q) assert not self.q("~dst foobar", q) assert self.q("~dst :22", q) assert not self.q("~dst :99", q) assert self.q("~dst address:22", q) q.server_conn.address = None assert not self.q("~dst address:22", q) q.server_conn = None assert not self.q("~dst address:22", q) def test_and(self): s = self.resp() assert self.q("~c 200 & ~h head", s) assert self.q("~c 200 & ~h head", s) assert not self.q("~c 200 & ~h nohead", s) assert self.q("(~c 200 & ~h head) & ~b content", s) assert not self.q("(~c 200 & ~h head) & ~b nonexistent", s) assert not self.q("(~c 200 & ~h nohead) & ~b content", s) def test_or(self): s = self.resp() assert self.q("~c 200 | ~h nohead", s) assert self.q("~c 201 | ~h head", s) assert not self.q("~c 201 | ~h nohead", s) assert self.q("(~c 201 | ~h nohead) | ~s", s) def test_not(self): s = self.resp() assert not self.q("! ~c 200", s) assert self.q("! ~c 201", s) assert self.q("!~c 201 !~c 202", s) assert not self.q("!~c 201 !~c 200", s) def test_replay(self): f = tflow.tflow() assert not self.q("~replay", f) f.is_replay = "request" assert self.q("~replay", f) assert self.q("~replayq", f) assert not self.q("~replays", f) f.is_replay = "response" assert self.q("~replay", f) assert not self.q("~replayq", f) assert self.q("~replays", f) def test_metadata(self): f = tflow.tflow() f.metadata["a"] = 1 f.metadata["b"] = "string" f.metadata["c"] = {"key": "value"} assert self.q("~meta a", f) assert not self.q("~meta no", f) assert self.q("~meta string", f) assert self.q("~meta key", f) assert self.q("~meta value", f) assert self.q('~meta "b: string"', f) assert self.q("~meta \"'key': 'value'\"", f) class TestMatchingDNSFlow: def req(self): return tflow.tdnsflow() def resp(self): return tflow.tdnsflow(resp=True) def err(self): return tflow.tdnsflow(err=True) def q(self, q, o): return flowfilter.parse(q)(o) def test_dns(self): s = self.req() assert self.q("~dns", s) assert not self.q("~http", s) assert not self.q("~tcp", s) def test_freq_fresp(self): q = self.req() s = self.resp() assert self.q("~q", q) assert not self.q("~q", s) assert not self.q("~s", q) assert self.q("~s", s) def test_ferr(self): e = self.err() assert self.q("~e", e) def test_body(self): q = self.req() s = self.resp() assert not self.q("~b nonexistent", q) assert self.q("~b dns.google", q) assert self.q("~b 8.8.8.8", s) assert not self.q("~bq 8.8.8.8", s) assert self.q("~bq dns.google", q) assert self.q("~bq dns.google", s) assert not self.q("~bs dns.google", q) assert self.q("~bs dns.google", s) assert self.q("~bs 8.8.8.8", s) def test_url(self): f = self.req() assert not self.q("~u whatever", f) assert self.q("~u dns.google", f) class TestMatchingTCPFlow: def flow(self): return tflow.ttcpflow() def err(self): return tflow.ttcpflow(err=True) def q(self, q, o): return flowfilter.parse(q)(o) def test_tcp(self): f = self.flow() assert self.q("~tcp", f) assert not self.q("~udp", f) assert not self.q("~http", f) assert not self.q("~websocket", f) def test_ferr(self): e = self.err() assert self.q("~e", e) def test_body(self): f = self.flow() # Messages sent by client or server assert self.q("~b hello", f) assert self.q("~b me", f) assert not self.q("~b nonexistent", f) # Messages sent by client assert self.q("~bq hello", f) assert not self.q("~bq me", f) assert not self.q("~bq nonexistent", f) # Messages sent by server assert self.q("~bs me", f) assert not self.q("~bs hello", f) assert not self.q("~bs nonexistent", f) def test_src(self): f = self.flow() assert self.q("~src 127.0.0.1", f) assert not self.q("~src foobar", f) assert self.q("~src :22", f) assert not self.q("~src :99", f) assert self.q("~src 127.0.0.1:22", f) def test_dst(self): f = self.flow() f.server_conn = tflow.tserver_conn() assert self.q("~dst address", f) assert not self.q("~dst foobar", f) assert self.q("~dst :22", f) assert not self.q("~dst :99", f) assert self.q("~dst address:22", f) def test_and(self): f = self.flow() f.server_conn = tflow.tserver_conn() assert self.q("~b hello & ~b me", f) assert not self.q("~src wrongaddress & ~b hello", f) assert self.q("(~src :22 & ~dst :22) & ~b hello", f) assert not self.q("(~src address:22 & ~dst :22) & ~b nonexistent", f) assert not self.q("(~src address:22 & ~dst :99) & ~b hello", f) def test_or(self): f = self.flow() f.server_conn = tflow.tserver_conn() assert self.q("~b hello | ~b me", f) assert self.q("~src :22 | ~b me", f) assert not self.q("~src :99 | ~dst :99", f) assert self.q("(~src :22 | ~dst :22) | ~b me", f) def test_not(self): f = self.flow() assert not self.q("! ~src :22", f) assert self.q("! ~src :99", f) assert self.q("!~src :99 !~src :99", f) assert not self.q("!~src :99 !~src :22", f) def test_request(self): f = self.flow() assert not self.q("~q", f) def test_response(self): f = self.flow() assert not self.q("~s", f) def test_headers(self): f = self.flow() assert not self.q("~h whatever", f) # Request headers assert not self.q("~hq whatever", f) # Response headers assert not self.q("~hs whatever", f) def test_content_type(self): f = self.flow() assert not self.q("~t whatever", f) # Request content-type assert not self.q("~tq whatever", f) # Response content-type assert not self.q("~ts whatever", f) def test_code(self): f = self.flow() assert not self.q("~c 200", f) def test_domain(self): f = self.flow() assert not self.q("~d whatever", f) def test_method(self): f = self.flow() assert not self.q("~m whatever", f) def test_url(self): f = self.flow() assert not self.q("~u whatever", f) class TestMatchingUDPFlow: def flow(self): return tflow.tudpflow() def err(self): return tflow.tudpflow(err=True) def q(self, q, o): return flowfilter.parse(q)(o) def test_udp(self): f = self.flow() assert self.q("~udp", f) assert not self.q("~tcp", f) assert not self.q("~http", f) assert not self.q("~websocket", f) def test_ferr(self): e = self.err() assert self.q("~e", e) def test_body(self): f = self.flow() # Messages sent by client or server assert self.q("~b hello", f) assert self.q("~b me", f) assert not self.q("~b nonexistent", f) # Messages sent by client assert self.q("~bq hello", f) assert not self.q("~bq me", f) assert not self.q("~bq nonexistent", f) # Messages sent by server assert self.q("~bs me", f) assert not self.q("~bs hello", f) assert not self.q("~bs nonexistent", f) def test_src(self): f = self.flow() assert self.q("~src 127.0.0.1", f) assert not self.q("~src foobar", f) assert self.q("~src :22", f) assert not self.q("~src :99", f) assert self.q("~src 127.0.0.1:22", f) def test_dst(self): f = self.flow() f.server_conn = tflow.tserver_conn() assert self.q("~dst address", f) assert not self.q("~dst foobar", f) assert self.q("~dst :22", f) assert not self.q("~dst :99", f) assert self.q("~dst address:22", f) def test_and(self): f = self.flow() f.server_conn = tflow.tserver_conn() assert self.q("~b hello & ~b me", f) assert not self.q("~src wrongaddress & ~b hello", f) assert self.q("(~src :22 & ~dst :22) & ~b hello", f) assert not self.q("(~src address:22 & ~dst :22) & ~b nonexistent", f) assert not self.q("(~src address:22 & ~dst :99) & ~b hello", f) def test_or(self): f = self.flow() f.server_conn = tflow.tserver_conn() assert self.q("~b hello | ~b me", f) assert self.q("~src :22 | ~b me", f) assert not self.q("~src :99 | ~dst :99", f) assert self.q("(~src :22 | ~dst :22) | ~b me", f) def test_not(self): f = self.flow() assert not self.q("! ~src :22", f) assert self.q("! ~src :99", f) assert self.q("!~src :99 !~src :99", f) assert not self.q("!~src :99 !~src :22", f) def test_request(self): f = self.flow() assert not self.q("~q", f) def test_response(self): f = self.flow() assert not self.q("~s", f) def test_headers(self): f = self.flow() assert not self.q("~h whatever", f) # Request headers assert not self.q("~hq whatever", f) # Response headers assert not self.q("~hs whatever", f) def test_content_type(self): f = self.flow() assert not self.q("~t whatever", f) # Request content-type assert not self.q("~tq whatever", f) # Response content-type assert not self.q("~ts whatever", f) def test_code(self): f = self.flow() assert not self.q("~c 200", f) def test_domain(self): f = self.flow() assert not self.q("~d whatever", f) def test_method(self): f = self.flow() assert not self.q("~m whatever", f) def test_url(self): f = self.flow() assert not self.q("~u whatever", f) class TestMatchingWebSocketFlow: def flow(self) -> http.HTTPFlow: return tflow.twebsocketflow() def q(self, q, o): return flowfilter.parse(q)(o) def test_websocket(self): f = self.flow() assert self.q("~websocket", f) assert not self.q("~tcp", f) assert self.q("~http", f) def test_handshake(self): f = self.flow() assert self.q("~websocket", f) assert not self.q("~tcp", f) assert self.q("~http", f) f = tflow.tflow() assert not self.q("~websocket", f) f = tflow.tflow(resp=True) assert not self.q("~websocket", f) def test_domain(self): q = self.flow() assert self.q("~d example.com", q) assert not self.q("~d none", q) def test_url(self): q = self.flow() assert self.q("~u example.com", q) assert self.q("~u example.com/ws", q) assert not self.q("~u moo/path", q) def test_body(self): f = self.flow() # Messages sent by client or server assert self.q("~b hello", f) assert self.q("~b me", f) assert not self.q("~b nonexistent", f) # Messages sent by client assert self.q("~bq hello", f) assert not self.q("~bq me", f) assert not self.q("~bq nonexistent", f) # Messages sent by server assert self.q("~bs me", f) assert not self.q("~bs hello", f) assert not self.q("~bs nonexistent", f) def test_src(self): f = self.flow() assert self.q("~src 127.0.0.1", f) assert not self.q("~src foobar", f) assert self.q("~src :22", f) assert not self.q("~src :99", f) assert self.q("~src 127.0.0.1:22", f) def test_dst(self): f = self.flow() f.server_conn = tflow.tserver_conn() assert self.q("~dst address", f) assert not self.q("~dst foobar", f) assert self.q("~dst :22", f) assert not self.q("~dst :99", f) assert self.q("~dst address:22", f) def test_and(self): f = self.flow() f.server_conn = tflow.tserver_conn() assert self.q("~b hello & ~b me", f) assert not self.q("~src wrongaddress & ~b hello", f) assert self.q("(~src :22 & ~dst :22) & ~b hello", f) assert not self.q("(~src address:22 & ~dst :22) & ~b nonexistent", f) assert not self.q("(~src address:22 & ~dst :99) & ~b hello", f) def test_or(self): f = self.flow() f.server_conn = tflow.tserver_conn() assert self.q("~b hello | ~b me", f) assert self.q("~src :22 | ~b me", f) assert not self.q("~src :99 | ~dst :99", f) assert self.q("(~src :22 | ~dst :22) | ~b me", f) def test_not(self): f = self.flow() assert not self.q("! ~src :22", f) assert self.q("! ~src :99", f) assert self.q("!~src :99 !~src :99", f) assert not self.q("!~src :99 !~src :22", f) class TestMatchingDummyFlow: def flow(self): return tflow.tdummyflow() def err(self): return tflow.tdummyflow(err=True) def q(self, q, o): return flowfilter.parse(q)(o) def test_filters(self): e = self.err() f = self.flow() f.server_conn = tflow.tserver_conn() assert self.q("~all", f) assert not self.q("~a", f) assert not self.q("~b whatever", f) assert not self.q("~bq whatever", f) assert not self.q("~bs whatever", f) assert not self.q("~c 0", f) assert not self.q("~d whatever", f) assert self.q("~dst address", f) assert not self.q("~dst nonexistent", f) assert self.q("~e", e) assert not self.q("~e", f) assert not self.q("~http", f) assert not self.q("~tcp", f) assert not self.q("~websocket", f) assert not self.q("~h whatever", f) assert not self.q("~hq whatever", f) assert not self.q("~hs whatever", f) assert not self.q("~m whatever", f) assert not self.q("~s", f) assert self.q("~src 127.0.0.1", f) assert not self.q("~src nonexistent", f) assert not self.q("~tcp", f) assert not self.q("~t whatever", f) assert not self.q("~tq whatever", f) assert not self.q("~ts whatever", f) assert not self.q("~u whatever", f) assert not self.q("~q", f) assert not self.q("~comment .", f) f.comment = "comment" assert self.q("~comment .", f) @patch("traceback.extract_tb") def test_pyparsing_bug(extract_tb): """https://github.com/mitmproxy/mitmproxy/issues/1087""" # The text is a string with leading and trailing whitespace stripped; if the source is not available it is None. extract_tb.return_value = [("", 1, "test", None)] assert flowfilter.parse("test") def test_match(): with pytest.raises(ValueError): flowfilter.match("[foobar", None) assert flowfilter.match(None, None) assert not flowfilter.match("foobar", None)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_websocket.py
test/mitmproxy/test_websocket.py
import pytest from wsproto.frame_protocol import Opcode from mitmproxy import http from mitmproxy import websocket from mitmproxy.test import tflow class TestWebSocketData: def test_repr(self): assert repr(tflow.twebsocketflow().websocket) == "<WebSocketData (3 messages)>" def test_state(self): f = tflow.twebsocketflow() f2 = http.HTTPFlow.from_state(f.get_state()) f2.set_state(f.get_state()) def test_formatting(self): tf = tflow.twebsocketflow().websocket formatted_messages = tf._get_formatted_messages() assert b"[OUTGOING] hello binary" in formatted_messages assert b"[OUTGOING] hello text" in formatted_messages assert b"[INCOMING] it's me" in formatted_messages class TestWebSocketMessage: def test_basic(self): m = websocket.WebSocketMessage(Opcode.TEXT, True, b"foo") m.set_state(m.get_state()) assert m.content == b"foo" assert repr(m) == "'foo'" m.type = Opcode.BINARY assert repr(m) == "b'foo'" assert not m.dropped m.drop() assert m.dropped def test_text(self): txt = websocket.WebSocketMessage(Opcode.TEXT, True, b"foo") bin = websocket.WebSocketMessage(Opcode.BINARY, True, b"foo") assert txt.is_text assert txt.text == "foo" txt.text = "bar" assert txt.content == b"bar" assert not bin.is_text with pytest.raises(AttributeError, match="do not have a 'text' attribute."): _ = bin.text with pytest.raises(AttributeError, match="do not have a 'text' attribute."): bin.text = "bar" def test_message_formatting(self): incoming_message = websocket.WebSocketMessage( Opcode.BINARY, False, b"Test Incoming" ) outgoing_message = websocket.WebSocketMessage( Opcode.BINARY, True, b"Test OutGoing" ) assert incoming_message._format_ws_message() == b"[INCOMING] Test Incoming" assert outgoing_message._format_ws_message() == b"[OUTGOING] Test OutGoing"
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_exceptions.py
test/mitmproxy/test_exceptions.py
# TODO: write tests
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_master.py
test/mitmproxy/test_master.py
import asyncio import gc from mitmproxy.master import Master async def err(): raise RuntimeError async def test_exception_handler(caplog_async): caplog_async.set_level("ERROR") # start proxy master and let it initialize its exception handler master = Master(None) running = asyncio.create_task(master.run()) await asyncio.sleep(0) # create a task with an unhandled exception... task = asyncio.create_task(err()) # make sure said task is run... await asyncio.sleep(0) # and garbage-collected... assert task del task gc.collect() # and ensure that this triggered a log entry. await caplog_async.await_log("Traceback") master.shutdown() await running
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/test_tls.py
test/mitmproxy/test_tls.py
from mitmproxy import tls CLIENT_HELLO_NO_EXTENSIONS = bytes.fromhex( "03015658a756ab2c2bff55f636814deac086b7ca56b65058c7893ffc6074f5245f70205658a75475103a152637" "78e1bb6d22e8bbd5b6b0a3a59760ad354e91ba20d353001a0035002f000a000500040009000300060008006000" "61006200640100" ) FULL_CLIENT_HELLO_NO_EXTENSIONS = ( b"\x16\x03\x03\x00\x65" # record layer b"\x01\x00\x00\x61" + CLIENT_HELLO_NO_EXTENSIONS # handshake header ) class TestClientHello: def test_no_extensions(self): c = tls.ClientHello(CLIENT_HELLO_NO_EXTENSIONS) assert repr(c) assert c.sni is None assert c.cipher_suites == [53, 47, 10, 5, 4, 9, 3, 6, 8, 96, 97, 98, 100] assert c.alpn_protocols == [] assert c.extensions == [] assert c.raw_bytes(False) == CLIENT_HELLO_NO_EXTENSIONS assert c.raw_bytes(True) == FULL_CLIENT_HELLO_NO_EXTENSIONS def test_extensions(self): data = bytes.fromhex( "03033b70638d2523e1cba15f8364868295305e9c52aceabda4b5147210abc783e6e1000022c02bc02fc02cc030" "cca9cca8cc14cc13c009c013c00ac014009c009d002f0035000a0100006cff0100010000000010000e00000b65" "78616d706c652e636f6d0017000000230000000d00120010060106030501050304010403020102030005000501" "00000000001200000010000e000c02683208687474702f312e3175500000000b00020100000a00080006001d00" "170018" ) c = tls.ClientHello(data) assert repr(c) assert c.sni == "example.com" assert c.cipher_suites == [ 49195, 49199, 49196, 49200, 52393, 52392, 52244, 52243, 49161, 49171, 49162, 49172, 156, 157, 47, 53, 10, ] assert c.alpn_protocols == [b"h2", b"http/1.1"] assert c.extensions == [ (65281, b"\x00"), (0, b"\x00\x0e\x00\x00\x0bexample.com"), (23, b""), (35, b""), ( 13, b"\x00\x10\x06\x01\x06\x03\x05\x01\x05\x03\x04\x01\x04\x03\x02\x01\x02\x03", ), (5, b"\x01\x00\x00\x00\x00"), (18, b""), (16, b"\x00\x0c\x02h2\x08http/1.1"), (30032, b""), (11, b"\x01\x00"), (10, b"\x00\x06\x00\x1d\x00\x17\x00\x18"), ] DTLS_CLIENT_HELLO_NO_EXTENSIONS = bytes.fromhex( # No Record or Handshake layer header "fefd62bf5560a83b2525186d38fb6459837656d7f11" "fb630cd44683bb9d9681204c50000000c00020003000a00050004000901000000" ) class TestDTLSClientHello: def test_no_extensions(self): c = tls.ClientHello(DTLS_CLIENT_HELLO_NO_EXTENSIONS, dtls=True) assert repr(c) assert c.sni is None assert c.cipher_suites == [2, 3, 10, 5, 4, 9] assert c.alpn_protocols == [] assert c.extensions == [] def test_extensions(self): # No Record or Handshake layer header data = bytes.fromhex( "fefd62bf60ba96532f63c4e53196174ff5016d949420d7f970a6b08a9e2a5a8209af0000" "000c00020003000a000500040009" "01000055000d0010000e0403050306030401050106010807ff01000100000a00080006001d" "00170018000b000201000017000000000010000e00000b6578616d706c652e636f6d0010000e" "000c02683208687474702f312e31" ) c = tls.ClientHello(data, dtls=True) assert repr(c) assert c.sni == "example.com" 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"), ]
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/test_cmdline.py
test/mitmproxy/tools/test_cmdline.py
import argparse from mitmproxy import options from mitmproxy.tools import cmdline from mitmproxy.tools import main def test_common(): parser = argparse.ArgumentParser() opts = options.Options() cmdline.common_options(parser, opts) args = parser.parse_args(args=[]) main.process_options(parser, opts, args) def test_mitmproxy(): opts = options.Options() ap = cmdline.mitmproxy(opts) assert ap def test_mitmdump(): opts = options.Options() ap = cmdline.mitmdump(opts) assert ap def test_mitmweb(): opts = options.Options() ap = cmdline.mitmweb(opts) assert ap
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/test_main.py
test/mitmproxy/tools/test_main.py
from mitmproxy.tools import main shutdown_script = "mitmproxy/data/addonscripts/shutdown.py" def test_mitmweb(tdata): main.mitmweb( [ "--no-web-open-browser", "-s", tdata.path(shutdown_script), "-q", "-p", "0", "--web-port", "0", ] ) def test_mitmdump(tdata): main.mitmdump( [ "-s", tdata.path(shutdown_script), "-q", "-p", "0", ] )
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/test_dump.py
test/mitmproxy/tools/test_dump.py
import pytest from mitmproxy import options from mitmproxy.tools import dump class TestDumpMaster: @pytest.mark.parametrize("termlog", [False, True]) async def test_addons_termlog(self, capsys, termlog): o = options.Options() m = dump.DumpMaster(o, with_termlog=termlog) assert (m.addons.get("termlog") is not None) == termlog await m.done() @pytest.mark.parametrize("dumper", [False, True]) async def test_addons_dumper(self, capsys, dumper): o = options.Options() m = dump.DumpMaster(o, with_dumper=dumper, with_termlog=False) assert (m.addons.get("dumper") is not None) == dumper await m.done()
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/__init__.py
test/mitmproxy/tools/__init__.py
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_keymap.py
test/mitmproxy/tools/console/test_keymap.py
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"], "") assert b.keyspec() == " " def test_bind(): with taddons.context() as tctx: km = keymap.Keymap(tctx.master) km.executor = mock.Mock() with pytest.raises(ValueError): km.add("foo", "bar", ["unsupported"]) km.add("key", "str", ["options", "commands"]) assert km.get("options", "key") assert km.get("commands", "key") assert not km.get("flowlist", "key") assert len(km.list("commands")) == 1 km.handle("unknown", "unknown") assert not km.executor.called km.handle("options", "key") assert km.executor.called km.add("glob", "str", ["global"]) km.executor = mock.Mock() km.handle("options", "glob") assert km.executor.called assert len(km.list("global")) == 1 def test_join(): with taddons.context() as tctx: km = keymap.Keymap(tctx.master) km.add("key", "str", ["options"], "help1") km.add("key", "str", ["commands"]) assert len(km.bindings) == 1 assert len(km.bindings[0].contexts) == 2 assert km.bindings[0].help == "help1" km.add("key", "str", ["commands"], "help2") assert len(km.bindings) == 1 assert len(km.bindings[0].contexts) == 2 assert km.bindings[0].help == "help2" assert km.get("commands", "key") km.unbind(km.bindings[0]) assert len(km.bindings) == 0 assert not km.get("commands", "key") def test_remove(): with taddons.context() as tctx: km = keymap.Keymap(tctx.master) km.add("key", "str", ["options", "commands"], "help1") assert len(km.bindings) == 1 assert "options" in km.bindings[0].contexts km.remove("key", ["options"]) assert len(km.bindings) == 1 assert "options" not in km.bindings[0].contexts km.remove("key", ["commands"]) assert len(km.bindings) == 0 def test_load_path(tmpdir): dst = str(tmpdir.join("conf")) with taddons.context() as tctx: kmc = keymap.KeymapConfig(tctx.master) km = keymap.Keymap(tctx.master) tctx.master.keymap = km with open(dst, "wb") as f: f.write(b"\xff\xff\xff") with pytest.raises(keymap.KeyBindingError, match="expected UTF8"): kmc.load_path(km, dst) with open(dst, "w") as f: f.write("'''") with pytest.raises(keymap.KeyBindingError): kmc.load_path(km, dst) with open(dst, "w") as f: f.write( """ - key: key1 ctx: [unknown] cmd: > foo bar foo bar """ ) with pytest.raises(keymap.KeyBindingError): kmc.load_path(km, dst) with open(dst, "w") as f: f.write( """ - key: key1 ctx: [chooser] help: one cmd: > foo bar foo bar """ ) kmc.load_path(km, dst) assert km.get("chooser", "key1") with open(dst, "w") as f: f.write( """ - key: key2 ctx: [flowlist] cmd: foo - key: key2 ctx: [flowview] cmd: bar """ ) kmc.load_path(km, dst) assert km.get("flowlist", "key2") assert km.get("flowview", "key2") km.add("key123", "str", ["flowlist", "flowview"]) with open(dst, "w") as f: f.write( """ - key: key123 ctx: [options] cmd: foo """ ) kmc.load_path(km, dst) assert km.get("flowlist", "key123") assert km.get("flowview", "key123") assert km.get("options", "key123") def test_parse(): with taddons.context() as tctx: kmc = keymap.KeymapConfig(tctx.master) assert kmc.parse("") == [] assert kmc.parse("\n\n\n \n") == [] with pytest.raises(keymap.KeyBindingError, match="expected a list of keys"): kmc.parse("key: val") with pytest.raises(keymap.KeyBindingError, match="expected a list of keys"): kmc.parse("val") with pytest.raises(keymap.KeyBindingError, match="Unknown key attributes"): kmc.parse( """ - key: key1 nonexistent: bar """ ) with pytest.raises( keymap.KeyBindingError, match="Missing required key attributes" ): kmc.parse( """ - help: key1 """ ) with pytest.raises(keymap.KeyBindingError, match="Invalid type for cmd"): kmc.parse( """ - key: key1 cmd: [ cmd ] """ ) with pytest.raises(keymap.KeyBindingError, match="Invalid type for ctx"): kmc.parse( """ - key: key1 ctx: foo cmd: cmd """ ) assert kmc.parse( """ - key: key1 ctx: [one, two] help: one cmd: > foo bar foo bar """ ) == [ { "key": "key1", "ctx": ["one", "two"], "help": "one", "cmd": "foo bar foo bar\n", } ]
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_flowview.py
test/mitmproxy/tools/console/test_flowview.py
import sys from unittest import mock from mitmproxy import http from mitmproxy.test import tflow from mitmproxy.tools.console.flowview import FlowDetails async def test_flowview(console): for f in tflow.tflows(): console.commands.call("view.clear") await console.load_flow(f) console.type("<enter><tab><tab>") def _edit(data: str) -> str: assert data == "hello: true\n" return "hello: false" async def test_edit(console, monkeypatch, caplog): MSGPACK_WITH_TRUE = b"\x81\xa5hello\xc3" MSGPACK_WITH_FALSE = b"\x81\xa5hello\xc2" f = tflow.tflow( req=http.Request.make( "POST", "http://example.com", MSGPACK_WITH_TRUE, headers={"Content-Type": "application/msgpack"}, ) ) await console.load_flow(f) monkeypatch.setattr(console, "spawn_editor", _edit) console.type(':console.edit.focus "request-body (MsgPack)"<enter><enter>') assert "hello: false" in console.screen_contents() assert f.request.content == MSGPACK_WITH_FALSE async def test_content_missing_returns_error(console): # message.raw_content is None -> expect "[content missing]" error text f_missing = tflow.tflow( req=http.Request.make("GET", "http://example.com", b"initial"), ) f_missing.request.raw_content = None await console.load_flow(f_missing) fd = FlowDetails(console) title, txt_objs = fd.content_view("default", f_missing.request) assert title == "" first_text = txt_objs[0].get_text()[0] assert "[content missing]" == first_text async def test_empty_content_request_and_response(console): fd = FlowDetails(console) # 1) Request with empty body and no query -> "No request content" f_req_empty = tflow.tflow( req=http.Request.make("GET", "http://example.com", b""), ) f_req_empty.request.raw_content = b"" await console.load_flow(f_req_empty) title_req, txt_objs_req = fd.content_view("default", f_req_empty.request) assert title_req == "" req_text = txt_objs_req[0].get_text()[0] assert "No request content" == req_text # 2) Response with empty body -> "No content" f_resp_empty = tflow.tflow( req=http.Request.make("GET", "http://example.com", b""), resp=http.Response.make(200, b"", {}), ) f_resp_empty.response.raw_content = b"" await console.load_flow(f_resp_empty) title_resp, txt_objs_resp = fd.content_view("default", f_resp_empty.response) assert title_resp == "" resp_text = txt_objs_resp[0].get_text()[0] assert "No content" == resp_text async def test_content_view_fullcontents_true_uses_unlimited_limit(console): f = tflow.tflow(req=http.Request.make("POST", "http://example.com", b"non-empty")) await console.load_flow(f) fd = FlowDetails(console) console.commands.execute("view.settings.setval @focus fullcontents true") fd._get_content_view = mock.MagicMock() fd.content_view("default", f.request) fd._get_content_view.assert_called_with("default", sys.maxsize, mock.ANY)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_contentview.py
test/mitmproxy/tools/console/test_contentview.py
from mitmproxy import contentviews from mitmproxy.contentviews import Metadata from mitmproxy.contentviews import raw from mitmproxy.test import tflow class ConsoleTestContentView(contentviews.Contentview): def __init__(self, content: str): self.content = content def prettify(self, data: bytes, metadata: Metadata) -> str: return self.content def render_priority( self, data: bytes, metadata: Metadata, ) -> float: return 2 async def test_contentview_flowview(console, monkeypatch): monkeypatch.setattr(contentviews.registry, "_by_name", {"raw": raw}) assert "Flows" in console.screen_contents() await console.load_flow(tflow.tflow()) assert ">>" in console.screen_contents() console.type("<enter>") assert "Raw" in console.screen_contents() view = ConsoleTestContentView("test1") contentviews.add(view) assert "test1" in console.screen_contents() console.type("q") assert "Flows" in console.screen_contents() contentviews.add(ConsoleTestContentView("test2")) console.type("<enter>") assert "test2" in console.screen_contents()
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_common.py
test/mitmproxy/tools/console/test_common.py
import urwid from mitmproxy.test import tflow from mitmproxy.tools.console import common from mitmproxy.tools.console.common import format_duration def test_format_flow(): for f in tflow.tflows(): for render_mode in common.RenderMode: assert common.format_flow(f, render_mode=render_mode) assert common.format_flow( f, render_mode=render_mode, hostheader=True, focused=False ) def test_format_durations(): assert format_duration(-0.1) == ("-100ms", "gradient_99") assert format_duration(0) == ("0ms", "gradient_99") assert format_duration(0.1) == ("100ms", "gradient_43") assert format_duration(100) == ("100s", "gradient_00") def test_format_keyvals(): assert common.format_keyvals( [ ("aa", "bb"), ("cc", "dd"), ("ee", None), ] ) wrapped = urwid.Pile( urwid.SimpleFocusListWalker(common.format_keyvals([("foo", "bar")])) ) assert wrapped.render((30,)) assert common.format_keyvals([("aa", wrapped)]) def test_truncated_text(): urwid.set_encoding("utf8") half_width_text = common.TruncatedText("Half-width", []) full_width_text = common.TruncatedText("FULL-WIDTH", []) assert half_width_text.render((10,)) assert full_width_text.render((10,))
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_statusbar.py
test/mitmproxy/tools/console/test_statusbar.py
import pytest from mitmproxy.tools.console import statusbar async def test_statusbar(console, monkeypatch): console.options.update( modify_headers=[":~q:foo:bar"], modify_body=[":~q:foo:bar"], ignore_hosts=["example.com", "example.org"], tcp_hosts=["example.tcp"], intercept="~q", view_filter="~dst example.com", stickycookie="~dst example.com", stickyauth="~dst example.com", console_default_contentview="javascript", anticache=True, anticomp=True, showhost=True, server_replay_refresh=False, server_replay_extra="kill", upstream_cert=False, stream_large_bodies="3m", mode=["transparent"], ) console.options.update(view_order="url", console_focus_follow=True) monkeypatch.setattr(console.addons.get("clientplayback"), "count", lambda: 42) monkeypatch.setattr(console.addons.get("serverplayback"), "count", lambda: 42) monkeypatch.setattr(statusbar.StatusBar, "refresh", lambda x: None) bar = statusbar.StatusBar(console) # this already causes a redraw assert bar.ib._w @pytest.mark.parametrize( "message,ready_message", [ ("", [("", ""), ("warn", "")]), ( ("info", "Line fits into statusbar"), [("info", "Line fits into statusbar"), ("warn", "")], ), ( "Line doesn't fit into statusbar", [("", "Line doesn'\u2026"), ("warn", "(more in eventlog)")], ), ( ("alert", "Two lines.\nFirst fits"), [("alert", "Two lines."), ("warn", "(more in eventlog)")], ), ( "Two long lines\nFirst doesn't fit", [("", "Two long li\u2026"), ("warn", "(more in eventlog)")], ), ], ) def test_shorten_message(message, ready_message): assert statusbar.shorten_message(message, max_width=30) == ready_message def test_shorten_message_narrow(): shorten_msg = statusbar.shorten_message("error", max_width=4) assert shorten_msg == [("", "\u2026"), ("warn", "(more in eventlog)")]
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_palettes.py
test/mitmproxy/tools/console/test_palettes.py
import mitmproxy_rs from mitmproxy.tools.console import palettes class TestPalette: def test_helptext(self): for i in palettes.palettes.values(): assert i.palette(False) for i in palettes.palettes.values(): assert i.palette(True) def test_has_tags(self): missing = set(mitmproxy_rs.syntax_highlight.tags()) - set( palettes.Palette._fields ) assert not missing, f"Missing styles for tags: {missing}"
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/conftest.py
test/mitmproxy/tools/console/conftest.py
import re import sys import pytest from mitmproxy import options from mitmproxy.tools.console import signals from mitmproxy.tools.console import window from mitmproxy.tools.console.master import ConsoleMaster from mitmproxy.utils.signals import _SignalMixin def tokenize(input: str) -> list[str]: keys = [] for i, k in enumerate(re.split("[<>]", input)): if i % 2: keys.append(k) else: keys.extend(k) return keys class ConsoleTestMaster(ConsoleMaster): def __init__(self, opts: options.Options) -> None: super().__init__(opts) self.addons.remove(self.addons.get("tlsconfig")) def type(self, input: str) -> None: for key in tokenize(input): self.window.keypress(self.ui.get_cols_rows(), key) def screen_contents(self) -> str: return b"\n".join(self.window.render((80, 24), True).text).decode() @pytest.fixture async def console(monkeypatch) -> ConsoleTestMaster: # noqa # monkeypatch.setattr(window.Screen, "get_cols_rows", lambda self: (120, 120)) monkeypatch.setattr(window.Screen, "start", lambda *_: True) monkeypatch.setattr(ConsoleTestMaster, "sig_call_in", lambda *_, **__: True) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) # extremely hacky: the console UI heavily depends on global signals # that are unfortunately shared across tests # Here we clear all existing signals so that we don't interact with previous instantiations. for sig in signals.__dict__.values(): if isinstance(sig, _SignalMixin): sig.receivers.clear() opts = options.Options() m = ConsoleTestMaster(opts) opts.server = False opts.console_mouse = False await m.running() yield m await m.done()
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_commander.py
test/mitmproxy/tools/console/test_commander.py
import pytest from mitmproxy import options from mitmproxy.addons import command_history from mitmproxy.test import taddons from mitmproxy.tools.console.commander import commander @pytest.fixture(autouse=True) def commander_tctx(tmpdir): # This runs before each test dir_name = tmpdir.mkdir("mitmproxy").dirname confdir = dir_name opts = options.Options() opts.set(*[f"{confdir=!s}"]) commander_tctx = taddons.context(options=opts) ch = command_history.CommandHistory() commander_tctx.master.addons.add(ch) ch.configure("command_history") yield commander_tctx # This runs after each test ch.clear_history() class TestListCompleter: def test_cycle(self): tests = [ [ "", ["a", "b", "c"], ["a", "b", "c", "a"], ["c", "b", "a", "c"], ["a", "c", "a", "c"], ], [ "xxx", ["a", "b", "c"], ["xxx", "xxx", "xxx"], ["xxx", "xxx", "xxx"], ["xxx", "xxx", "xxx"], ], [ "b", ["a", "b", "ba", "bb", "c"], ["b", "ba", "bb", "b"], ["bb", "ba", "b", "bb"], ["b", "bb", "b", "bb"], ], ] for start, opts, cycle, cycle_reverse, cycle_mix in tests: c = commander.ListCompleter(start, opts) for expected in cycle: assert c.cycle() == expected for expected in cycle_reverse: assert c.cycle(False) == expected forward = True for expected in cycle_mix: assert c.cycle(forward) == expected forward = not forward class TestCommandEdit: def test_open_command_bar(self, commander_tctx): edit = commander.CommandEdit(commander_tctx.master, "") try: edit.update() except IndexError: pytest.faied("Unexpected IndexError") def test_insert(self, commander_tctx): edit = commander.CommandEdit(commander_tctx.master, "") edit.keypress(1, "a") assert edit.get_edit_text() == "a" # Don't let users type a space before starting a command # as a usability feature edit = commander.CommandEdit(commander_tctx.master, "") edit.keypress(1, " ") assert edit.get_edit_text() == "" def test_backspace(self, commander_tctx): edit = commander.CommandEdit(commander_tctx.master, "") edit.keypress(1, "a") edit.keypress(1, "b") assert edit.get_edit_text() == "ab" edit.keypress(1, "backspace") assert edit.get_edit_text() == "a" def test_left(self, commander_tctx): edit = commander.CommandEdit(commander_tctx.master, "") edit.keypress(1, "a") assert edit.cbuf.cursor == 1 edit.keypress(1, "left") assert edit.cbuf.cursor == 0 # Do it again to make sure it won't go negative edit.keypress(1, "left") assert edit.cbuf.cursor == 0 def test_right(self, commander_tctx): edit = commander.CommandEdit(commander_tctx.master, "") edit.keypress(1, "a") assert edit.cbuf.cursor == 1 # Make sure cursor won't go past the text edit.keypress(1, "right") assert edit.cbuf.cursor == 1 # Make sure cursor goes left and then back right edit.keypress(1, "left") assert edit.cbuf.cursor == 0 edit.keypress(1, "right") assert edit.cbuf.cursor == 1 def test_up_and_down(self, commander_tctx): edit = commander.CommandEdit(commander_tctx.master, "") commander_tctx.master.commands.execute("commands.history.clear") commander_tctx.master.commands.execute('commands.history.add "cmd1"') edit.keypress(1, "up") assert edit.get_edit_text() == "cmd1" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd1" edit.keypress(1, "down") assert edit.get_edit_text() == "" edit.keypress(1, "down") assert edit.get_edit_text() == "" edit = commander.CommandEdit(commander_tctx.master, "") commander_tctx.master.commands.execute("commands.history.clear") commander_tctx.master.commands.execute('commands.history.add "cmd1"') commander_tctx.master.commands.execute('commands.history.add "cmd2"') edit.keypress(1, "up") assert edit.get_edit_text() == "cmd2" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd1" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd1" edit.keypress(1, "down") assert edit.get_edit_text() == "cmd2" edit.keypress(1, "down") assert edit.get_edit_text() == "" edit.keypress(1, "a") edit.keypress(1, "b") edit.keypress(1, "c") assert edit.get_edit_text() == "abc" edit.keypress(1, "up") assert edit.get_edit_text() == "abc" edit.keypress(1, "down") assert edit.get_edit_text() == "abc" edit.keypress(1, "down") assert edit.get_edit_text() == "abc" edit.keypress(1, "up") assert edit.get_edit_text() == "abc" edit = commander.CommandEdit(commander_tctx.master, "") commander_tctx.master.commands.execute('commands.history.add "cmd3"') edit.keypress(1, "z") edit.keypress(1, "up") assert edit.get_edit_text() == "z" edit.keypress(1, "down") assert edit.get_edit_text() == "z" edit.keypress(1, "down") assert edit.get_edit_text() == "z" edit.keypress(1, "backspace") assert edit.get_edit_text() == "" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd3" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd2" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd1" edit.keypress(1, "down") assert edit.get_edit_text() == "cmd2" edit.keypress(1, "down") assert edit.get_edit_text() == "cmd3" edit.keypress(1, "down") assert edit.get_edit_text() == "" edit.keypress(1, "c") assert edit.get_edit_text() == "c" edit.keypress(1, "down") assert edit.get_edit_text() == "" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd3" edit.keypress(1, "down") assert edit.get_edit_text() == "" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd3" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd2" edit.keypress(1, "down") assert edit.get_edit_text() == "cmd3" edit.keypress(1, "down") assert edit.get_edit_text() == "" edit.keypress(1, "down") assert edit.get_edit_text() == "" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd3" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd2" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd1" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd1" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd1" edit.keypress(1, "down") assert edit.get_edit_text() == "cmd2" edit.keypress(1, "down") assert edit.get_edit_text() == "cmd3" edit.keypress(1, "down") assert edit.get_edit_text() == "" edit.keypress(1, "down") assert edit.get_edit_text() == "" edit.keypress(1, "backspace") assert edit.get_edit_text() == "" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd3" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd2" edit.keypress(1, "up") assert edit.get_edit_text() == "cmd1" edit.keypress(1, "down") assert edit.get_edit_text() == "cmd2" edit.keypress(1, "down") assert edit.get_edit_text() == "cmd3" edit.keypress(1, "down") assert edit.get_edit_text() == "" class TestCommandBuffer: def test_backspace(self): tests = [ [("", 0), ("", 0)], [("1", 0), ("1", 0)], [("1", 1), ("", 0)], [("123", 3), ("12", 2)], [("123", 2), ("13", 1)], [("123", 0), ("123", 0)], ] with taddons.context() as commander_tctx: for start, output in tests: cb = commander.CommandBuffer(commander_tctx.master) cb.text, cb.cursor = start[0], start[1] cb.backspace() assert cb.text == output[0] assert cb.cursor == output[1] def test_left(self): cursors = [3, 2, 1, 0, 0] with taddons.context() as commander_tctx: cb = commander.CommandBuffer(commander_tctx.master) cb.text, cb.cursor = "abcd", 4 for c in cursors: cb.left() assert cb.cursor == c def test_right(self): cursors = [1, 2, 3, 4, 4] with taddons.context() as commander_tctx: cb = commander.CommandBuffer(commander_tctx.master) cb.text, cb.cursor = "abcd", 0 for c in cursors: cb.right() assert cb.cursor == c def test_insert(self): tests = [ [("", 0), ("x", 1)], [("a", 0), ("xa", 1)], [("xa", 2), ("xax", 3)], ] with taddons.context() as commander_tctx: for start, output in tests: cb = commander.CommandBuffer(commander_tctx.master) cb.text, cb.cursor = start[0], start[1] cb.insert("x") assert cb.text == output[0] assert cb.cursor == output[1] def test_cycle_completion(self): with taddons.context() as commander_tctx: cb = commander.CommandBuffer(commander_tctx.master) cb.text = "foo bar" cb.cursor = len(cb.text) cb.cycle_completion() ce = commander.CommandEdit(commander_tctx.master, "se") ce.keypress(1, "tab") ce.update() ret = ce.cbuf.render() assert ret == [ ("commander_command", "set"), ("text", " "), ("commander_hint", "option "), ("commander_hint", "*value "), ] def test_render(self): with taddons.context() as commander_tctx: cb = commander.CommandBuffer(commander_tctx.master) cb.text = "foo" assert cb.render() cb.text = "set view_filter '~bq test'" ret = cb.render() assert ret == [ ("commander_command", "set"), ("text", " "), ("text", "view_filter"), ("text", " "), ("text", "'~bq test'"), ] cb.text = "set" ret = cb.render() assert ret == [ ("commander_command", "set"), ("text", " "), ("commander_hint", "option "), ("commander_hint", "*value "), ]
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/__init__.py
test/mitmproxy/tools/console/__init__.py
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_defaultkeys.py
test/mitmproxy/tools/console/test_defaultkeys.py
import mitmproxy.types from mitmproxy.test.tflow import tflow async def test_commands_exist(console): await console.load_flow(tflow()) for binding in console.keymap.bindings: try: parsed, _ = console.commands.parse_partial(binding.command.strip()) cmd = parsed[0].value args = [a.value for a in parsed[1:] if a.type != mitmproxy.types.Space] assert cmd in console.commands.commands cmd_obj = console.commands.commands[cmd] cmd_obj.prepare_args(args) except Exception as e: raise ValueError(f"Invalid binding: {binding.command}") from e
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_quickhelp.py
test/mitmproxy/tools/console/test_quickhelp.py
import pytest from mitmproxy.test.tflow import tflow 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 from mitmproxy.tools.console.grideditor import PathEditor from mitmproxy.tools.console.help import HelpView from mitmproxy.tools.console.keybindings import KeyBindings from mitmproxy.tools.console.keymap import Keymap from mitmproxy.tools.console.options import Options from mitmproxy.tools.console.overlay import SimpleOverlay @pytest.fixture(scope="module") def keymap() -> Keymap: km = Keymap(None) defaultkeys.map(km) return km tflow2 = tflow() tflow2.intercept() tflow2.backup() tflow2.marked = "x" @pytest.mark.parametrize( "widget, flow, is_root_widget", [ (FlowListBox, None, False), (FlowListBox, tflow(), False), (FlowView, tflow2, True), (KeyBindings, None, True), (Options, None, True), (HelpView, None, False), (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) for row in [qh.top_items, qh.bottom_items]: for title, v in row.items(): if isinstance(v, quickhelp.BasicKeyHelp): key_short = v.key else: b = keymap.binding_for_help(v) if b is None: raise AssertionError(f"No binding found for help text: {v}") key_short = b.key_short() assert len(key_short) + len(title) < 14 def test_make_rows(): keymap = Keymap(None) defaultkeys.map(keymap) # make sure that we don't crash if a default binding is missing. keymap.unbind(keymap.binding_for_help("View event log")) qh = quickhelp.make(HelpView, None, True) assert qh.make_rows(keymap)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_master.py
test/mitmproxy/tools/console/test_master.py
from unittest.mock import Mock def test_spawn_editor(monkeypatch, console): text_data = "text" binary_data = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09" console.get_editor = Mock() console.get_editor.return_value = "editor" console.get_hex_editor = Mock() console.get_hex_editor.return_value = "editor" monkeypatch.setattr("subprocess.call", (lambda _: None)) console.loop = Mock() console.loop.stop = Mock() console.loop.start = Mock() console.loop.draw_screen = Mock() console.spawn_editor(text_data) console.get_editor.assert_called_once() console.spawn_editor(binary_data) console.get_hex_editor.assert_called_once() def test_get_hex_editor(monkeypatch, console): test_editor = "hexedit" monkeypatch.setattr("shutil.which", lambda x: x == test_editor) editor = console.get_hex_editor() assert editor == test_editor
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/console/test_integration.py
test/mitmproxy/tools/console/test_integration.py
def test_integration(tdata, console): console.type( f":view.flows.load {tdata.path('mitmproxy/data/dumpfile-7.mitm')}<enter>" ) console.type("<enter><tab><tab>") console.type("<space><tab><tab>") # view second flow assert "http://example.com/" in console.screen_contents() def test_options_home_end(console): console.type("O<home><end>") assert "Options" in console.screen_contents() def test_keybindings_home_end(console): console.type("K<home><end>") assert "Key Binding" in console.screen_contents() def test_replay_count(console): console.type(":replay.server.count<enter>") assert "Data viewer" in console.screen_contents()
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/web/test_app.py
test/mitmproxy/tools/web/test_app.py
import gzip import importlib import json import logging from pathlib import Path from unittest import mock import pytest import tornado.testing from tornado import httpclient from tornado import websocket from tornado.web import create_signed_value import mitmproxy_rs from mitmproxy import log from mitmproxy import options from mitmproxy.test import tflow from mitmproxy.tools.web import app from mitmproxy.tools.web import master as webmaster here = Path(__file__).parent.absolute() @pytest.fixture(scope="module") def no_tornado_logging(): logging.getLogger("tornado.access").disabled = True logging.getLogger("tornado.application").disabled = True logging.getLogger("tornado.general").disabled = True yield logging.getLogger("tornado.access").disabled = False logging.getLogger("tornado.application").disabled = False logging.getLogger("tornado.general").disabled = False def get_json(resp: httpclient.HTTPResponse): return json.loads(resp.body.decode()) @pytest.mark.parametrize("filename", list((here / "../../../../web/gen").glob("*.py"))) async def test_generated_files(filename): mod = importlib.import_module(f"web.gen.{filename.stem}") expected = await mod.make() actual = mod.filename.read_text().replace("\r\n", "\n") assert actual == expected, ( f"{mod.filename} must be regenerated by running {filename.resolve()}." ) def test_all_handlers_have_auth(): for _, handler in app.handlers: assert issubclass(handler, app.AuthRequestHandler) @pytest.mark.usefixtures("no_tornado_logging", "tdata") class TestApp(tornado.testing.AsyncHTTPTestCase): def get_app(self): async def make_master() -> webmaster.WebMaster: 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() ) f = tflow.tflow(resp=True) f.id = "42" f.request.content = b"foo\nbar" f2 = tflow.tflow(ws=True, resp=True) f2.request.content = None f2.response.content = None f2.id = "43" m.view.add([f, f2]) m.view.add([tflow.tflow(err=True)]) m.events._add_log(log.LogEntry("test log", "info")) m.events.done() self.master = m self.view = m.view self.events = m.events webapp = app.Application(m, None) webapp.settings["xsrf_cookies"] = False return webapp @property def auth_cookie(self) -> str: auth_cookie = create_signed_value( secret=self._app.settings["cookie_secret"], name=self._app.settings["auth_cookie_name"](), value=app.AuthRequestHandler.AUTH_COOKIE_VALUE, ).decode() return f"{self._app.settings['auth_cookie_name']()}={auth_cookie}" def fetch(self, *args, **kwargs) -> httpclient.HTTPResponse: kwargs.setdefault("headers", {}).setdefault("Cookie", self.auth_cookie) # tornado disallows POST without content by default. return super().fetch(*args, **kwargs, allow_nonstandard_methods=True) def put_json(self, url, data: dict) -> httpclient.HTTPResponse: return self.fetch( url, method="PUT", body=json.dumps(data), headers={"Content-Type": "application/json"}, ) def test_index(self): response = self.fetch("/") assert response.code == 200 assert b'="/' not in response.body, ( "HTML content should not contain root-relative paths" ) def test_filter_help(self): assert self.fetch("/filter-help").code == 200 def test_flows(self): resp = self.fetch("/flows") assert resp.code == 200 assert get_json(resp)[0]["request"]["contentHash"] assert get_json(resp)[2]["error"] def test_flows_dump(self): resp = self.fetch("/flows/dump") assert b"address" in resp.body def test_flows_dump_filter(self): resp = self.fetch("/flows/dump?filter=foo") assert b"" == resp.body def test_flows_dump_filter_error(self): resp = self.fetch("/flows/dump?filter=[") assert resp.code == 400 def test_clear(self): events = self.events.data.copy() flows = list(self.view) assert self.fetch("/clear", method="POST").code == 200 assert not len(self.view) assert not len(self.events.data) # restore for f in flows: self.view.add([f]) self.events.data = events def test_resume(self): for f in self.view: f.intercept() assert self.fetch("/flows/42/resume", method="POST").code == 200 assert sum(f.intercepted for f in self.view) >= 1 assert self.fetch("/flows/resume", method="POST").code == 200 assert all(not f.intercepted for f in self.view) def test_kill(self): for f in self.view: f.backup() f.intercept() assert self.fetch("/flows/42/kill", method="POST").code == 200 assert sum(f.killable for f in self.view) >= 1 assert self.fetch("/flows/kill", method="POST").code == 200 assert all(not f.killable for f in self.view) for f in self.view: f.revert() def test_flow_delete(self): f = self.view.get_by_id("42") assert f assert self.fetch("/flows/42", method="DELETE").code == 200 assert not self.view.get_by_id("42") self.view.add([f]) assert self.fetch("/flows/1234", method="DELETE").code == 404 def test_flow_update(self): f = self.view.get_by_id("42") assert f.request.method == "GET" f.backup() upd = { "request": { "method": "PATCH", "port": 123, "headers": [("foo", "bar")], "trailers": [("foo", "bar")], "content": "req", }, "response": { "msg": "Non-Authorisé", "code": 404, "headers": [("bar", "baz")], "trailers": [("foo", "bar")], "content": "resp", }, "marked": ":red_circle:", "comment": "I'm a modified comment!", } assert self.put_json("/flows/42", upd).code == 200 assert f.request.method == "PATCH" assert f.request.port == 123 assert f.request.headers["foo"] == "bar" assert f.request.text == "req" assert f.response.msg == "Non-Authorisé" assert f.response.status_code == 404 assert f.response.headers["bar"] == "baz" assert f.response.text == "resp" assert f.comment == "I'm a modified comment!" upd = { "request": { "trailers": [("foo", "baz")], }, "response": { "trailers": [("foo", "baz")], }, } assert self.put_json("/flows/42", upd).code == 200 assert f.request.trailers["foo"] == "baz" f.revert() assert self.put_json("/flows/42", {"foo": 42}).code == 400 assert self.put_json("/flows/42", {"request": {"foo": 42}}).code == 400 assert self.put_json("/flows/42", {"response": {"foo": 42}}).code == 400 assert self.fetch("/flows/42", method="PUT", body="{}").code == 400 assert ( self.fetch( "/flows/42", method="PUT", headers={"Content-Type": "application/json"}, body="!!", ).code == 400 ) def test_flow_duplicate(self): resp = self.fetch("/flows/42/duplicate", method="POST") assert resp.code == 200 f = self.view.get_by_id(resp.body.decode()) assert f assert f.id != "42" self.view.remove([f]) def test_flow_revert(self): f = self.view.get_by_id("42") f.backup() f.request.method = "PATCH" self.fetch("/flows/42/revert", method="POST") assert not f._backup def test_flow_replay(self): with mock.patch("mitmproxy.command.CommandManager.call") as replay_call: assert self.fetch("/flows/42/replay", method="POST").code == 200 assert replay_call.called def test_flow_content(self): f = self.view.get_by_id("42") f.backup() f.response.headers["Content-Disposition"] = 'inline; filename="filename.jpg"' r = self.fetch("/flows/42/response/content.data") assert r.body == b"message" assert r.headers["Content-Disposition"] == 'attachment; filename="filename.jpg"' del f.response.headers["Content-Disposition"] f.request.path = "/foo/bar.jpg" assert ( self.fetch("/flows/42/response/content.data").headers["Content-Disposition"] == "attachment; filename=bar.jpg" ) f.response.content = b"" r = self.fetch("/flows/42/response/content.data") assert r.code == 200 assert r.body == b"" f.revert() def test_flow_content_returns_raw_content_when_decoding_fails(self): f = self.view.get_by_id("42") f.backup() f.response.headers["Content-Encoding"] = "gzip" # replace gzip magic number with garbage invalid_encoded_content = gzip.compress(b"Hello world!").replace( b"\x1f\x8b", b"\xff\xff" ) f.response.raw_content = invalid_encoded_content r = self.fetch("/flows/42/response/content.data") assert r.body == invalid_encoded_content assert r.code == 200 f.revert() def test_update_flow_content(self): assert ( self.fetch("/flows/42/request/content.data", method="POST", body="new").code == 200 ) f = self.view.get_by_id("42") assert f.request.content == b"new" assert f.modified() f.revert() def test_update_flow_content_multipart(self): body = ( b"--somefancyboundary\r\n" b'Content-Disposition: form-data; name="a"; filename="a.txt"\r\n' b"\r\n" b"such multipart. very wow.\r\n" b"--somefancyboundary--\r\n" ) assert ( self.fetch( "/flows/42/request/content.data", method="POST", headers={ "Content-Type": 'multipart/form-data; boundary="somefancyboundary"' }, body=body, ).code == 200 ) f = self.view.get_by_id("42") assert f.request.content == b"such multipart. very wow." assert f.modified() f.revert() def test_flow_contentview(self): assert get_json(self.fetch("/flows/42/request/content/raw")) == { "description": "", "syntax_highlight": "none", "text": "foo\nbar", "view_name": "Raw", } assert get_json(self.fetch("/flows/42/request/content/raw?lines=1")) == { "description": "", "syntax_highlight": "none", "text": "foo\n", "view_name": "Raw", } assert self.fetch("/flows/42/messages/content/raw").code == 400 def test_flow_contentview_websocket(self): assert get_json(self.fetch("/flows/43/messages/content/raw?lines=2")) == [ { "text": "hello binary", "view_name": "Raw", "syntax_highlight": "none", "description": "", "from_client": True, "timestamp": 946681203, }, { "text": "hello text", "view_name": "Raw", "syntax_highlight": "none", "description": "", "from_client": True, "timestamp": 946681204, }, ] def test_commands(self): resp = self.fetch("/commands") assert resp.code == 200 assert get_json(resp)["set"]["help"] def test_command_execute(self): resp = self.fetch("/commands/unknown", method="POST") assert resp.code == 200 assert get_json(resp) == {"error": "Unknown command: unknown"} resp = self.fetch("/commands/commands.history.get", method="POST") assert resp.code == 200 assert get_json(resp) == {"value": []} def test_events(self): resp = self.fetch("/events") assert resp.code == 200 assert get_json(resp)[0]["level"] == "info" def test_options(self): j = get_json(self.fetch("/options")) assert isinstance(j, dict) assert isinstance(j["anticache"], dict) def test_option_update(self): assert self.put_json("/options", {"anticache": True}).code == 200 assert self.put_json("/options", {"wtf": True}).code == 400 assert self.put_json("/options", {"anticache": "foo"}).code == 400 def test_option_save(self): assert self.fetch("/options/save", method="POST").code == 200 def test_err(self): with mock.patch("mitmproxy.tools.web.app.IndexHandler.get") as f: f.side_effect = RuntimeError assert self.fetch("/").code == 500 @tornado.testing.gen_test def test_websocket(self): ws_req = httpclient.HTTPRequest( f"ws://localhost:{self.get_http_port()}/updates", headers={"Cookie": self.auth_cookie}, ) ws_client = yield websocket.websocket_connect(ws_req) self.master.options.anticomp = True r1 = yield ws_client.read_message() response = json.loads(r1) assert response == { "type": "options/update", "payload": { "anticomp": { "value": True, "choices": None, "default": False, "help": "Try to convince servers to send us un-compressed data.", "type": "bool", } }, } ws_client.close() # trigger on_close by opening a second connection. ws_client2 = yield websocket.websocket_connect(ws_req) ws_client2.close() @tornado.testing.gen_test def test_websocket_filter_application(self): ws_req = httpclient.HTTPRequest( f"ws://localhost:{self.get_http_port()}/updates", headers={"Cookie": self.auth_cookie}, ) ws_client = yield tornado.websocket.websocket_connect(ws_req) # test update filter message message = json.dumps( { "type": "flows/updateFilter", "payload": { "name": "search", "expr": "~bq foo", }, } ).encode() yield ws_client.write_message(message) response = yield ws_client.read_message() response = json.loads(response) assert response == { "type": "flows/filterUpdate", "payload": { "name": "search", "matching_flow_ids": ["42"], }, } # test add flow f = tflow.tflow(resp=True) f.id = "41" f.request.content = b"foo\nbarbar" app.ClientConnection.broadcast_flow("flows/add", f) response = yield ws_client.read_message() response = json.loads(response) assert response["type"] == "flows/add" assert response["payload"]["matching_filters"] == {"search": True} assert response["payload"]["flow"]["id"] == "41" # test update flow f.request.content = b"bar" app.ClientConnection.broadcast_flow("flows/update", f) response = yield ws_client.read_message() response = json.loads(response) assert response["type"] == "flows/update" assert response["payload"]["matching_filters"] == {"search": False} assert response["payload"]["flow"]["id"] == "41" # test filter removal message = json.dumps( { "type": "flows/updateFilter", "payload": { "name": "search", "expr": "", }, } ).encode() yield ws_client.write_message(message) response = yield ws_client.read_message() response = json.loads(response) assert response == { "type": "flows/filterUpdate", "payload": { "name": "search", "matching_flow_ids": None, }, } ws_client.close() @tornado.testing.gen_test def test_websocket_filter_command_error(self): # can't do pytest.parametrize, so we do this. for data in [ """{"type": "flows/updateFilter"}""", """{"type": "unknownCommand"}""", "invalid json", ]: ws_req = httpclient.HTTPRequest( f"ws://localhost:{self.get_http_port()}/updates", headers={"Cookie": self.auth_cookie}, ) ws_client = yield tornado.websocket.websocket_connect(ws_req) yield ws_client.write_message(data) response = yield ws_client.read_message() # Connection should be closed self.assertIsNone(response) self.assertEqual(ws_client.close_code, 1011) self.assertEqual(ws_client.close_reason, "Internal server error.") def test_process_list(self): try: mitmproxy_rs.process_info.active_executables() except NotImplementedError: pytest.skip( "mitmproxy_rs.process_info.active_executables not available on this platform." ) resp = self.fetch("/processes") assert resp.code == 200 assert get_json(resp) def test_process_icon(self): try: mitmproxy_rs.process_info.executable_icon("invalid") except NotImplementedError: pytest.skip( "mitmproxy_rs.process_info.executable_icon not available on this platform." ) except Exception: pass resp = self.fetch("/executable-icon") assert resp.code == 400 assert "Missing 'path' parameter." in resp.body.decode() resp = self.fetch("/executable-icon?path=invalid_path") assert resp.code == 200 assert resp.headers["Content-Type"] == "image/png" assert resp.body == app.TRANSPARENT_PNG def test_login_with_token_header(self): web_password = self.master.addons.get("webauth")._password headers = {"Cookie": "", "Authorization": f"Bearer {web_password}"} assert self.fetch("/", headers=headers).code == 200 def test_login_with_token_param(self): web_password = self.master.addons.get("webauth")._password headers = {"Cookie": ""} assert self.fetch(f"/?token={web_password}", headers=headers).code == 200 def test_login_with_malformed_auth_header(self): headers = {"Cookie": "", "Authorization": f"Bearer"} assert self.fetch("/", headers=headers).code == 403 def test_login_with_invalid_auth_header(self): headers = {"Cookie": "", "Authorization": f"Bearer invalid_token"} assert self.fetch("/", headers=headers).code == 403 def test_unauthorized_api(self): headers = {"Cookie": ""} assert self.fetch("/", headers=headers).code == 403 @tornado.testing.gen_test def test_unauthorized_websocket(self): try: yield websocket.websocket_connect( f"ws://localhost:{self.get_http_port()}/updates" ) except httpclient.HTTPClientError as e: assert e.code == 403 else: assert False def test_auth_cookie_port_suffix_modification(self): opts = self.master.options old_port = opts.web_port new_port = 8082 opts.web_port = new_port try: assert self._app.settings["auth_cookie_name"]().endswith(str(new_port)) finally: opts.web_port = old_port
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/web/test_webaddons.py
test/mitmproxy/tools/web/test_webaddons.py
import pytest from mitmproxy.exceptions import OptionsError from mitmproxy.test import taddons from mitmproxy.tools.web import webaddons class TestWebAuth: def test_token_auth(self): a = webaddons.WebAuth() with taddons.context(webaddons.WebAddon(), a) as tctx: assert not a.is_valid_password("") assert not a.is_valid_password("invalid") assert not a.is_valid_password("test") tctx.options.web_password = "" assert not a.is_valid_password("") assert not a.is_valid_password("invalid") assert not a.is_valid_password("test") assert a.is_valid_password(a._password) assert "token" in a.web_url def test_plaintext_auth(self, caplog): a = webaddons.WebAuth() with taddons.context(webaddons.WebAddon(), a) as tctx: tctx.options.web_password = "test" assert "Consider using an argon2 hash" in caplog.text assert not a.is_valid_password("") assert not a.is_valid_password("invalid") assert a.is_valid_password("test") assert "token" not in a.web_url def test_argon2_auth(self, caplog): a = webaddons.WebAuth() with taddons.context(webaddons.WebAddon(), a) as tctx: tctx.options.web_password = ( "$argon2id$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$ieVgG5ysTJFx4k/KvmC9aQ" ) assert not a.is_valid_password("") assert not a.is_valid_password("invalid") assert a.is_valid_password("test") assert "token" not in a.web_url def test_invalid_hash(self, caplog): a = webaddons.WebAuth() with taddons.context(webaddons.WebAddon(), a) as tctx: with pytest.raises(OptionsError): tctx.options.web_password = "$argon2id$" assert not a.is_valid_password("") assert not a.is_valid_password("test") @pytest.mark.parametrize( "web_host,web_port,expected_web_url", [ ("example.com", 8080, "http://example.com:8080/"), ("127.0.0.1", 8080, "http://127.0.0.1:8080/"), ("::1", 8080, "http://[::1]:8080/"), ("example.com", 80, "http://example.com:80/?"), ("127.0.0.1", 80, "http://127.0.0.1:80/?"), ("::1", 80, "http://[::1]:80/?"), ], ) def test_web_url(self, caplog, web_host, web_port, expected_web_url): a = webaddons.WebAuth() with taddons.context(webaddons.WebAddon(), a) as tctx: tctx.options.web_host = web_host tctx.options.web_port = web_port assert a.web_url.startswith(expected_web_url), a.web_url
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/web/test_static_viewer.py
test/mitmproxy/tools/web/test_static_viewer.py
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.tools.web import static_viewer from mitmproxy.tools.web.app import flow_to_json def test_save_static(tmpdir): tmpdir.mkdir("static") static_viewer.save_static(tmpdir) assert len(tmpdir.listdir()) == 2 assert tmpdir.join("index.html").check(file=1) assert tmpdir.join("static/static.js").read() == "MITMWEB_STATIC = true;" def test_save_filter_help(tmpdir): static_viewer.save_filter_help(tmpdir) f = tmpdir.join("/filter-help.json") assert f.check(file=1) assert f.read() == json.dumps(dict(commands=flowfilter.help)) def test_save_settings(tmpdir): static_viewer.save_settings(tmpdir) f = tmpdir.join("/settings.json") assert f.check(file=1) def test_save_flows(tmpdir): flows = [tflow.tflow(resp=False), tflow.tflow(resp=True)] static_viewer.save_flows(tmpdir, flows) assert tmpdir.join("flows.json").check(file=1) assert tmpdir.join("flows.json").read() == json.dumps( [flow_to_json(f) for f in flows] ) def test_save_flows_content(tmpdir): with taddons.context(): flows = [tflow.tflow(resp=False), tflow.tflow(resp=True)] with mock.patch("time.time", mock.Mock(side_effect=[1, 2, 2] * 4)): static_viewer.save_flows_content(tmpdir, flows) flows_path = tmpdir.join("flows") assert len(flows_path.listdir()) == len(flows) for p in flows_path.listdir(): assert p.join("request").check(dir=1) assert p.join("response").check(dir=1) assert p.join("request/content.data").check(file=1) assert p.join("request/content").check(dir=1) assert p.join("response/content.data").check(file=1) assert p.join("response/content").check(dir=1) assert p.join("request/content/Auto.json").check(file=1) assert p.join("response/content/Auto.json").check(file=1) async def test_static_viewer(tmpdir): s = static_viewer.StaticViewer() rf = readfile.ReadFile() sa = save.Save() with taddons.context(rf) as tctx: sa.save([tflow.tflow(resp=True)], str(tmpdir.join("foo"))) tctx.master.addons.add(s) tctx.configure(s, web_static_viewer=str(tmpdir), rfile=str(tmpdir.join("foo"))) assert tmpdir.join("index.html").check(file=1) assert tmpdir.join("static").check(dir=1) assert tmpdir.join("flows").check(dir=1)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/web/__init__.py
test/mitmproxy/tools/web/__init__.py
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/web/test_web_columns.py
test/mitmproxy/tools/web/test_web_columns.py
from mitmproxy.tools.web.web_columns import AVAILABLE_WEB_COLUMNS def test_web_columns(): assert isinstance(AVAILABLE_WEB_COLUMNS, list)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/tools/web/test_master.py
test/mitmproxy/tools/web/test_master.py
import asyncio import pytest from mitmproxy.options import Options from mitmproxy.tools.web.master import WebMaster async def test_reuse(): async def handler(r, w): pass server = await asyncio.start_server( handler, 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" master.options.web_port = port with pytest.raises(OSError, match=f"--set web_port={port + 2}"): await master.running() server.close() # tornado registers some callbacks, # we want to run them to avoid fatal warnings. await asyncio.sleep(0)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/test_mode_specs.py
test/mitmproxy/proxy/test_mode_specs.py
import dataclasses import pytest from mitmproxy.proxy.mode_specs import ProxyMode from mitmproxy.proxy.mode_specs import Socks5Mode def test_parse(): m = ProxyMode.parse("reverse:https://example.com/@127.0.0.1:443") m = ProxyMode.from_state(m.get_state()) assert m.type_name == "reverse" assert m.full_spec == "reverse:https://example.com/@127.0.0.1:443" assert m.data == "https://example.com/" assert m.custom_listen_host == "127.0.0.1" assert m.custom_listen_port == 443 assert repr(m) == "ProxyMode.parse('reverse:https://example.com/@127.0.0.1:443')" with pytest.raises(ValueError, match="unknown mode"): ProxyMode.parse("flibbel") with pytest.raises(ValueError, match="invalid port"): ProxyMode.parse("regular@invalid-port") with pytest.raises(ValueError, match="invalid port"): ProxyMode.parse("regular@99999") m.set_state(m.get_state()) with pytest.raises(dataclasses.FrozenInstanceError): m.set_state("regular") def test_parse_subclass(): assert Socks5Mode.parse("socks5") with pytest.raises(ValueError, match="'regular' is not a spec for a socks5 mode"): Socks5Mode.parse("regular") def test_listen_addr(): assert ProxyMode.parse("regular").listen_port() == 8080 assert ProxyMode.parse("regular@1234").listen_port() == 1234 assert ProxyMode.parse("regular").listen_port(default=4424) == 4424 assert ProxyMode.parse("regular@1234").listen_port(default=4424) == 1234 assert ProxyMode.parse("local").listen_port() is None 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("reverse:https://1.2.3.4").listen_port() == 8080 assert ProxyMode.parse("reverse:dns://8.8.8.8").listen_port() == 53 def test_parse_specific_modes(): assert ProxyMode.parse("regular") # assert ProxyMode.parse("http3") assert ProxyMode.parse("transparent") assert ProxyMode.parse("upstream:https://proxy") assert ProxyMode.parse("reverse:https://host@443") assert ProxyMode.parse("reverse:http3://host@443") assert ProxyMode.parse("socks5") assert ProxyMode.parse("dns") assert ProxyMode.parse("reverse:dns://8.8.8.8") assert ProxyMode.parse("reverse:dtls://127.0.0.1:8004") assert ProxyMode.parse("wireguard") assert ProxyMode.parse("wireguard:foo.conf").data == "foo.conf" assert ProxyMode.parse("wireguard@51821").listen_port() == 51821 assert ProxyMode.parse("tun") assert ProxyMode.parse("tun:utun42") assert ProxyMode.parse("local") with pytest.raises(ValueError, match="invalid port"): ProxyMode.parse("regular@invalid-port") with pytest.raises(ValueError, match="takes no arguments"): ProxyMode.parse("regular:configuration") # with pytest.raises(ValueError, match="takes no arguments"): # ProxyMode.parse("http3:configuration") with pytest.raises(ValueError, match="invalid upstream proxy scheme"): ProxyMode.parse("upstream:dns://example.com") with pytest.raises(ValueError, match="takes no arguments"): ProxyMode.parse("dns:invalid") with pytest.raises(ValueError, match="Port specification missing."): ProxyMode.parse("reverse:dtls://127.0.0.1") with pytest.raises(ValueError, match="invalid intercept spec"): ProxyMode.parse("local:,,,")
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/test_mode_servers.py
test/mitmproxy/proxy/test_mode_servers.py
import asyncio import platform import socket from unittest.mock import AsyncMock from unittest.mock import MagicMock from unittest.mock import Mock import pytest from ...conftest import no_ipv6 from ...conftest import skip_not_linux import mitmproxy.platform import mitmproxy_rs from mitmproxy.addons.proxyserver import Proxyserver from mitmproxy.proxy.mode_servers import LocalRedirectorInstance from mitmproxy.proxy.mode_servers import ServerInstance from mitmproxy.proxy.mode_servers import TunInstance from mitmproxy.proxy.mode_servers import WireGuardServerInstance from mitmproxy.proxy.server import ConnectionHandler from mitmproxy.test import taddons def test_make(): manager = Mock() context = MagicMock() assert ServerInstance.make("regular", manager) 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." ): WireGuardServerInstance.make("regular", manager) async def test_last_exception_and_running(monkeypatch): manager = MagicMock() err = ValueError("something else") def _raise(*_): nonlocal err raise err async def _raise_async(*_): nonlocal err raise err with taddons.context(): inst1 = ServerInstance.make("regular@127.0.0.1:0", manager) await inst1.start() assert inst1.last_exception is None assert inst1.is_running monkeypatch.setattr(inst1._servers[0], "close", _raise) with pytest.raises(type(err), match=str(err)): await inst1.stop() assert inst1.last_exception is err monkeypatch.setattr(asyncio, "start_server", _raise_async) inst2 = ServerInstance.make("regular@127.0.0.1:0", manager) assert inst2.last_exception is None with pytest.raises(type(err), match=str(err)): await inst2.start() assert inst2.last_exception is err assert not inst1.is_running async def test_tcp_start_stop(caplog_async): caplog_async.set_level("INFO") manager = MagicMock() with taddons.context(): inst = ServerInstance.make("regular@127.0.0.1:0", manager) await inst.start() assert inst.last_exception is None assert await caplog_async.await_log("proxy listening") host, port, *_ = inst.listen_addrs[0] reader, writer = await asyncio.open_connection(host, port) assert await caplog_async.await_log("client connect") writer.close() await writer.wait_closed() assert await caplog_async.await_log("client disconnect") await inst.stop() assert await caplog_async.await_log("stopped") async def test_tcp_timeout(caplog_async): """Test that TCP connections are closed after the configured timeout period.""" caplog_async.set_level("INFO") manager = MagicMock() with taddons.context() as tctx: # Set timeout to 0 for immediate timeout (fastest test) tctx.options.tcp_timeout = 0 inst = ServerInstance.make("regular@127.0.0.1:0", manager) await inst.start() assert await caplog_async.await_log("proxy listening") host, port, *_ = inst.listen_addrs[0] reader, writer = await asyncio.open_connection(host, port) assert await caplog_async.await_log("client connect") # Keep connection open but inactive - it should timeout after 1s # The await_log below will wait for the timeout to trigger async with asyncio.timeout(30): # Verify the connection was closed due to inactivity in <60s assert await caplog_async.await_log("Closing connection due to inactivity") assert await caplog_async.await_log("client disconnect") # Try to read from the closed connection to confirm it's really closed data = await reader.read(1) assert data == b"" # EOF indicates connection is closed writer.close() await writer.wait_closed() await inst.stop() assert await caplog_async.await_log("stopped") @pytest.mark.parametrize("failure", [True, False]) async def test_transparent(failure, monkeypatch, caplog_async): caplog_async.set_level("INFO") manager = MagicMock() if failure: monkeypatch.setattr(mitmproxy.platform, "original_addr", None) else: monkeypatch.setattr( mitmproxy.platform, "original_addr", lambda s: ("address", 42) ) with taddons.context(Proxyserver()) as tctx: tctx.options.connection_strategy = "lazy" inst = ServerInstance.make("transparent@127.0.0.1:0", manager) await inst.start() await caplog_async.await_log("listening") host, port, *_ = inst.listen_addrs[0] reader, writer = await asyncio.open_connection(host, port) if failure: assert await caplog_async.await_log("Transparent mode failure") writer.close() await writer.wait_closed() else: assert await caplog_async.await_log("client connect") writer.close() await writer.wait_closed() assert await caplog_async.await_log("client disconnect") await inst.stop() assert await caplog_async.await_log("stopped") async def _echo_server(self: ConnectionHandler): t = self.transports[self.client] data = await t.reader.read(65535) t.writer.write(data.upper()) await t.writer.drain() t.writer.close() async def test_wireguard(tdata, monkeypatch, caplog): caplog.set_level("DEBUG") monkeypatch.setattr(ConnectionHandler, "handle_client", _echo_server) system = platform.system() if system == "Linux": test_client_name = "linux-x86_64" elif system == "Darwin": test_client_name = "macos-x86_64" elif system == "Windows": test_client_name = "windows-x86_64.exe" else: return pytest.skip("Unsupported platform for wg-test-client.") arch = platform.machine() if arch != "AMD64" and arch != "x86_64": return pytest.skip("Unsupported architecture for wg-test-client.") test_client_path = tdata.path(f"wg-test-client/{test_client_name}") test_conf = tdata.path(f"wg-test-client/test.conf") with taddons.context(Proxyserver()): inst = WireGuardServerInstance.make(f"wireguard:{test_conf}@0", MagicMock()) await inst.start() assert "WireGuard server listening" in caplog.text _, port = inst.listen_addrs[0] assert inst.is_running proc = await asyncio.create_subprocess_exec( test_client_path, str(port), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await proc.communicate() try: assert proc.returncode == 0 except AssertionError: print(stdout) print(stderr) raise await inst.stop() assert "stopped" in caplog.text @pytest.mark.parametrize("host", ["127.0.0.1", "::1"]) async def test_wireguard_dual_stack(host, caplog_async): caplog_async.set_level("DEBUG") system = platform.system() if system not in ("Linux", "Darwin", "Windows"): return pytest.skip("Unsupported platform for wg-test-client.") arch = platform.machine() if arch != "AMD64" and arch != "x86_64": return pytest.skip("Unsupported architecture for wg-test-client.") with taddons.context(Proxyserver()): inst = WireGuardServerInstance.make(f"wireguard@0", MagicMock()) await inst.start() assert await caplog_async.await_log("WireGuard server listening") _, port = inst.listen_addrs[0] assert inst.is_running stream = await mitmproxy_rs.udp.open_udp_connection(host, port) stream.write(b"\x00\x00\x01") assert await caplog_async.await_log("Received invalid WireGuard packet") stream.close() await stream.wait_closed() await inst.stop() assert await caplog_async.await_log("stopped") async def test_wireguard_generate_conf(tmp_path): with taddons.context(Proxyserver()) as tctx: tctx.options.confdir = str(tmp_path) inst = WireGuardServerInstance.make(f"wireguard@0", MagicMock()) assert not inst.client_conf() # should not error. await inst.start() assert (tmp_path / "wireguard.conf").exists() assert inst.client_conf() assert inst.to_json()["wireguard_conf"] k = inst.server_key inst2 = WireGuardServerInstance.make(f"wireguard@0", MagicMock()) await inst2.start() assert k == inst2.server_key await inst.stop() await inst2.stop() async def test_wireguard_invalid_conf(tmp_path): with taddons.context(Proxyserver()): # directory instead of filename inst = WireGuardServerInstance.make(f"wireguard:{tmp_path}", MagicMock()) with pytest.raises(ValueError, match="Invalid configuration file"): await inst.start() assert "Invalid configuration file" in repr(inst.last_exception) async def test_tcp_start_error(): manager = MagicMock() 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}" ): await inst.start() tctx.options.listen_host = "127.0.0.1" tctx.options.listen_port = port inst3 = ServerInstance.make(f"regular", manager) with pytest.raises(OSError): await inst3.start() async def test_invalid_protocol(monkeypatch): manager = MagicMock() with taddons.context(): inst = ServerInstance.make(f"regular@127.0.0.1:0", manager) monkeypatch.setattr(inst.mode, "transport_protocol", "invalid_proto") with pytest.raises(AssertionError, match=f"invalid_proto"): await inst.start() async def test_udp_start_stop(caplog_async): caplog_async.set_level("INFO") manager = MagicMock() manager.connections = {} with taddons.context(): inst = ServerInstance.make("dns@127.0.0.1:0", manager) await inst.start() assert await caplog_async.await_log("server listening") host, port, *_ = inst.listen_addrs[0] stream = await mitmproxy_rs.udp.open_udp_connection(host, port) stream.write(b"\x00\x00\x01") assert await caplog_async.await_log("sent an invalid message") stream.close() await stream.wait_closed() await inst.stop() assert await caplog_async.await_log("stopped") async def test_udp_start_error(): manager = MagicMock() with taddons.context(): inst = ServerInstance.make("reverse:udp://127.0.0.1:1234@127.0.0.1:0", manager) await inst.start() port = inst.listen_addrs[0][1] inst2 = ServerInstance.make( f"reverse:udp://127.0.0.1:1234@127.0.0.1:{port}", manager ) with pytest.raises( Exception, match=f"Failed to bind UDP socket to 127.0.0.1:{port}" ): await inst2.start() await inst.stop() @pytest.mark.parametrize("ip_version", ["v4", "v6"]) @pytest.mark.parametrize("protocol", ["tcp", "udp"]) async def test_dual_stack(ip_version, protocol, caplog_async): """Test that a server bound to "" binds on both IPv4 and IPv6 for both TCP and UDP.""" if ip_version == "v6" and no_ipv6: pytest.skip("Skipped because IPv6 is unavailable.") if ip_version == "v4": addr = "127.0.0.1" else: addr = "::1" caplog_async.set_level("DEBUG") manager = MagicMock() manager.connections = {} with taddons.context(): inst = ServerInstance.make("dns@0", manager) await inst.start() assert await caplog_async.await_log("server listening") _, port, *_ = inst.listen_addrs[0] if protocol == "tcp": _, stream = await asyncio.open_connection(addr, port) else: stream = await mitmproxy_rs.udp.open_udp_connection(addr, port) stream.write(b"\x00\x00\x01") assert await caplog_async.await_log("sent an invalid message") stream.close() await stream.wait_closed() await inst.stop() assert await caplog_async.await_log("stopped") @pytest.mark.parametrize("transport_protocol", ["udp", "tcp"]) async def test_dns_start_stop(caplog_async, transport_protocol): caplog_async.set_level("INFO") manager = MagicMock() manager.connections = {} with taddons.context(): inst = ServerInstance.make("dns@127.0.0.1:0", manager) await inst.start() assert await caplog_async.await_log("server listening") host, port, *_ = inst.listen_addrs[0] if transport_protocol == "tcp": _, stream = await asyncio.open_connection("127.0.0.1", port) elif transport_protocol == "udp": stream = await mitmproxy_rs.udp.open_udp_connection("127.0.0.1", port) stream.write(b"\x00\x00\x01") assert await caplog_async.await_log("sent an invalid message") stream.close() await stream.wait_closed() await inst.stop() assert await caplog_async.await_log("stopped") @skip_not_linux async def test_tun_mode(monkeypatch, caplog): monkeypatch.setattr(ConnectionHandler, "handle_client", _echo_server) with taddons.context(Proxyserver()): inst = TunInstance.make(f"tun", MagicMock()) assert inst.tun_name is None try: await inst.start() except RuntimeError as e: if "Operation not permitted" in str(e): return pytest.skip("tun mode test must be run as root") raise assert inst.tun_name assert inst.is_running assert "tun_name" in inst.to_json() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, inst.tun_name.encode()) await asyncio.get_running_loop().sock_connect(s, ("192.0.2.1", 1234)) reader, writer = await asyncio.open_connection(sock=s) writer.write(b"hello") await writer.drain() assert await reader.readexactly(5) == b"HELLO" writer.close() await writer.wait_closed() await inst.stop() async def test_tun_mode_mocked(monkeypatch): tun_interface = Mock() tun_interface.tun_name = lambda: "tun0" tun_interface.wait_closed = AsyncMock() create_tun_interface = AsyncMock(return_value=tun_interface) monkeypatch.setattr(mitmproxy_rs.tun, "create_tun_interface", create_tun_interface) inst = TunInstance.make(f"tun", MagicMock()) assert not inst.is_running assert inst.tun_name is None await inst.start() assert inst.is_running assert inst.tun_name == "tun0" assert inst.to_json()["tun_name"] == "tun0" await inst.stop() assert not inst.is_running assert inst.tun_name is None @pytest.fixture() def patched_local_redirector(monkeypatch): start_local_redirector = AsyncMock(return_value=Mock()) monkeypatch.setattr( mitmproxy_rs.local, "start_local_redirector", start_local_redirector ) # make sure _server and _instance are restored after this test monkeypatch.setattr(LocalRedirectorInstance, "_server", None) monkeypatch.setattr(LocalRedirectorInstance, "_instance", None) return start_local_redirector async def test_local_redirector(patched_local_redirector, caplog_async): caplog_async.set_level("INFO") with taddons.context(): inst = ServerInstance.make(f"local", MagicMock()) assert not inst.is_running await inst.start() assert patched_local_redirector.called assert await caplog_async.await_log("Local redirector started.") assert inst.is_running await inst.stop() assert await caplog_async.await_log("Local redirector stopped") assert not inst.is_running # just called for coverage inst.make_top_layer(MagicMock()) async def test_local_redirector_startup_err(patched_local_redirector): patched_local_redirector.side_effect = RuntimeError( "Local redirector startup error" ) with taddons.context(): inst = ServerInstance.make(f"local:!curl", MagicMock()) with pytest.raises(RuntimeError): await inst.start() assert not inst.is_running async def test_multiple_local_redirectors(patched_local_redirector): manager = MagicMock() with taddons.context(): inst1 = ServerInstance.make(f"local:curl", manager) await inst1.start() inst2 = ServerInstance.make(f"local:wget", manager) with pytest.raises( RuntimeError, match="Cannot spawn more than one local redirector" ): await inst2.start() async def test_always_uses_current_instance(patched_local_redirector, monkeypatch): manager = MagicMock() with taddons.context(): inst1 = LocalRedirectorInstance.make(f"local:curl", manager) await inst1.start() await inst1.stop() handle_stream, _ = patched_local_redirector.await_args[0] inst2 = LocalRedirectorInstance.make(f"local:wget", manager) await inst2.start() monkeypatch.setattr(inst2, "handle_stream", handler := AsyncMock()) await handle_stream(Mock()) assert handler.await_count
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/test_tutils.py
test/mitmproxy/proxy/test_tutils.py
from collections.abc import Iterable from dataclasses import dataclass from typing import Any import pytest from . import tutils from mitmproxy.proxy import commands from mitmproxy.proxy import events from mitmproxy.proxy import layer class TEvent(events.Event): commands: Iterable[Any] def __init__(self, cmds=(None,)): self.commands = cmds class TCommand(commands.Command): x: Any def __init__(self, x=None): self.x = x @dataclass class TCommandCompleted(events.CommandCompleted): command: TCommand class TLayer(layer.Layer): """ Simple echo layer """ def _handle_event(self, event: events.Event) -> layer.CommandGenerator[None]: if isinstance(event, TEvent): for x in event.commands: yield TCommand(x) @pytest.fixture def tplaybook(tctx): return tutils.Playbook(TLayer(tctx), expected=[]) def test_simple(tplaybook): tplaybook >> TEvent() tplaybook << TCommand() tplaybook >> TEvent([]) tplaybook << None assert tplaybook def test_mismatch(tplaybook): with pytest.raises(AssertionError, match="Playbook mismatch"): tplaybook >> TEvent([]) tplaybook << TCommand() assert tplaybook def test_partial_assert(tplaybook): """Developers can assert parts of a playbook and the continue later on.""" tplaybook >> TEvent() tplaybook << TCommand() assert tplaybook tplaybook >> TEvent() tplaybook << TCommand() assert tplaybook assert len(tplaybook.actual) == len(tplaybook.expected) == 4 @pytest.mark.parametrize("typed", [True, False]) def test_placeholder(tplaybook, typed): """Developers can specify placeholders for yet unknown attributes.""" if typed: f = tutils.Placeholder(int) else: f = tutils.Placeholder() tplaybook >> TEvent([42]) tplaybook << TCommand(f) assert tplaybook assert f() == 42 def test_placeholder_type_mismatch(tplaybook): """Developers can specify placeholders for yet unknown attributes.""" f = tutils.Placeholder(str) with pytest.raises( TypeError, match="Placeholder type error for TCommand.x: expected str, got int." ): tplaybook >> TEvent([42]) tplaybook << TCommand(f) assert tplaybook def test_unfinished(tplaybook): """We show a warning when playbooks aren't asserted.""" tplaybook >> TEvent() with pytest.raises(RuntimeError, match="Unfinished playbook"): tplaybook.__del__() tplaybook._errored = True tplaybook.__del__() def test_command_reply(tplaybook): """CommandReplies can use relative offsets to point to the matching command.""" tplaybook >> TEvent() tplaybook << TCommand() tplaybook >> tutils.reply() assert tplaybook assert tplaybook.actual[1] == tplaybook.actual[2].command tplaybook >> TEvent((42,)) tplaybook << TCommand(42) tplaybook >> tutils.reply(to=TCommand) assert tplaybook assert tplaybook.actual[4] == tplaybook.actual[5].command def test_default_playbook(tctx): p = tutils.Playbook(TLayer(tctx)) assert p assert len(p.actual) == 1 assert isinstance(p.actual[0], events.Start) def test_eq_blocking(): """_eq should not consider differences in .blocking""" a = TCommand() a.blocking = True b = TCommand() b.blocking = False assert tutils._eq(a, b) def test_eq_placeholder(): """_eq should assign placeholders.""" a = TCommand() a.foo = 42 a.bar = tutils.Placeholder() b = TCommand() b.foo = tutils.Placeholder() b.bar = 43 assert tutils._eq(a, b) assert a.foo == b.foo() == 42 assert a.bar() == b.bar == 43 b.foo._obj = 44 assert not tutils._eq(a, b) @pytest.mark.parametrize("swap", [False, True]) def test_command_multiple_replies(tplaybook, swap): a = tutils.Placeholder(int) b = tutils.Placeholder(int) command1 = TCommand(a) command2 = TCommand(b) tplaybook >> TEvent([1]) tplaybook << command1 tplaybook >> TEvent([2]) tplaybook << command2 if swap: tplaybook >> tutils.reply(to=command1) tplaybook >> tutils.reply(to=command2) else: tplaybook >> tutils.reply(to=command2) tplaybook >> tutils.reply(to=command1) assert tplaybook assert a() == 1 assert b() == 2
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/test_utils.py
test/mitmproxy/proxy/test_utils.py
import pytest from mitmproxy.proxy.utils import expect from mitmproxy.proxy.utils import ReceiveBuffer def test_expect(): class Foo: @expect(str, int) def foo(self, x): return "".join(reversed(x)) @expect(str) def bar(self, x): yield "".join(reversed(x)) f = Foo() assert f.foo("foo") == "oof" assert list(f.bar("bar")) == ["rab"] with pytest.raises(AssertionError, match=r"Expected str\|int, got None."): f.foo(None) def test_receive_buffer(): buf = ReceiveBuffer() assert len(buf) == 0 assert bytes(buf) == b"" assert not buf buf += b"foo" assert len(buf) == 3 assert bytes(buf) == b"foo" assert buf buf += b"bar" assert len(buf) == 6 assert bytes(buf) == b"foobar" assert buf buf.clear() assert len(buf) == 0 assert bytes(buf) == b"" assert not buf
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/test_server.py
test/mitmproxy/proxy/test_server.py
import asyncio import collections import textwrap from dataclasses import dataclass from typing import Callable from unittest import mock import pytest from mitmproxy import options from mitmproxy.connection import Server from mitmproxy.proxy import commands from mitmproxy.proxy import layer from mitmproxy.proxy import server from mitmproxy.proxy import server_hooks from mitmproxy.proxy.events import Event from mitmproxy.proxy.events import HookCompleted from mitmproxy.proxy.events import Start from mitmproxy.proxy.mode_specs import ProxyMode class MockConnectionHandler(server.SimpleConnectionHandler): hook_handlers: dict[str, mock.Mock | Callable] def __init__(self): super().__init__( reader=mock.Mock(), writer=mock.Mock(), options=options.Options(), mode=ProxyMode.parse("regular"), hook_handlers=collections.defaultdict(lambda: mock.Mock()), ) @pytest.mark.parametrize("result", ("success", "killed", "failed")) async def test_open_connection(result, monkeypatch): handler = MockConnectionHandler() server_connect = handler.hook_handlers["server_connect"] server_connected = handler.hook_handlers["server_connected"] server_connect_error = handler.hook_handlers["server_connect_error"] server_disconnected = handler.hook_handlers["server_disconnected"] match result: case "success": monkeypatch.setattr( asyncio, "open_connection", mock.AsyncMock(return_value=(mock.MagicMock(), mock.MagicMock())), ) monkeypatch.setattr( MockConnectionHandler, "handle_connection", mock.AsyncMock() ) case "failed": monkeypatch.setattr( asyncio, "open_connection", mock.AsyncMock(side_effect=OSError) ) case "killed": def _kill(d: server_hooks.ServerConnectionHookData) -> None: d.server.error = "do not connect" server_connect.side_effect = _kill await handler.open_connection( commands.OpenConnection(connection=Server(address=("server", 1234))) ) assert server_connect.call_args[0][0].server.address == ("server", 1234) assert server_connected.called == (result == "success") assert server_connect_error.called == (result != "success") assert server_disconnected.called == (result == "success") async def test_no_reentrancy(capsys): class ReentrancyTestLayer(layer.Layer): def handle_event(self, event: Event) -> layer.CommandGenerator[None]: if isinstance(event, Start): print("Starting...") yield FastHook() print("Start completed.") elif isinstance(event, HookCompleted): print(f"Hook completed (must not happen before start is completed).") def _handle_event(self, event: Event) -> layer.CommandGenerator[None]: raise NotImplementedError @dataclass class FastHook(commands.StartHook): pass handler = MockConnectionHandler() handler.layer = ReentrancyTestLayer(handler.layer.context) # This instead would fail: handler._server_event(Start()) await handler.server_event(Start()) await asyncio.sleep(0) assert capsys.readouterr().out == textwrap.dedent( """\ Starting... Start completed. Hook completed (must not happen before start is completed). """ )
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/tutils.py
test/mitmproxy/proxy/tutils.py
import collections.abc import difflib import itertools import logging import re import textwrap import traceback 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 TypeVar from typing import Union 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 PlaybookEntry = Union[commands.Command, events.Event] PlaybookEntryList = list[PlaybookEntry] def _eq(a: PlaybookEntry, b: PlaybookEntry) -> bool: """Compare two commands/events, and possibly update placeholders.""" if type(a) is not type(b): return False a_dict = a.__dict__ b_dict = b.__dict__ # we can assume a.keys() == b.keys() for k in a_dict: if k == "blocking": continue x = a_dict[k] y = b_dict[k] # if there's a placeholder, make it x. if isinstance(y, _Placeholder): x, y = y, x if isinstance(x, _Placeholder): try: x = x.setdefault(y) except TypeError as e: raise TypeError( f"Placeholder type error for {type(a).__name__}.{k}: {e}" ) if x != y: return False return True def eq( a: PlaybookEntry | Iterable[PlaybookEntry], b: PlaybookEntry | Iterable[PlaybookEntry], ): """ Compare an indiviual event/command or a list of events/commands. """ if isinstance(a, collections.abc.Iterable) and isinstance( b, collections.abc.Iterable ): return all(_eq(x, y) for x, y in itertools.zip_longest(a, b)) return _eq(a, b) def _fmt_entry(x: PlaybookEntry): arrow = ">>" if isinstance(x, events.Event) else "<<" x = str(x) x = re.sub("Placeholder:None", "<unset placeholder>", x, flags=re.IGNORECASE) x = re.sub("Placeholder:", "", x, flags=re.IGNORECASE) x = textwrap.indent(x, " ")[5:] return f"{arrow} {x}" def _merge_sends( lst: list[commands.Command], ignore_hooks: bool, ignore_logs: bool ) -> PlaybookEntryList: current_send = None for x in lst: if isinstance(x, commands.SendData): if current_send is None or current_send.connection != x.connection: current_send = x yield x else: current_send.data += x.data else: ignore = (ignore_hooks and isinstance(x, commands.StartHook)) or ( ignore_logs and isinstance(x, commands.Log) ) if not ignore: current_send = None yield x class _TracebackInPlaybook(commands.Command): def __init__(self, exc): self.e = exc def __repr__(self): return self.e class Playbook: """ Assert that a layer emits the expected commands in reaction to a given sequence of events. For example, the following code asserts that the TCP layer emits an OpenConnection command immediately after starting and does not yield any further commands as a reaction to successful connection establishment. assert playbook(tcp.TCPLayer(tctx)) \ << commands.OpenConnection(tctx.server) >> reply(None) << None # this line is optional. This is syntactic sugar for the following: t = tcp.TCPLayer(tctx) x1 = list(t.handle_event(events.Start())) assert x1 == [commands.OpenConnection(tctx.server)] x2 = list(t.handle_event(events.OpenConnectionReply(x1[-1]))) assert x2 == [] """ layer: Layer """The base layer""" expected: PlaybookEntryList """expected command/event sequence""" actual: PlaybookEntryList """actual command/event sequence""" _errored: bool """used to check if playbook as been fully asserted""" logs: bool """If False, the playbook specification doesn't contain log commands.""" hooks: bool """If False, the playbook specification doesn't include hooks or hook replies. They are automatically replied to.""" def __init__( self, layer: Layer, hooks: bool = True, logs: bool = False, expected: PlaybookEntryList | None = None, ): if expected is None: expected = [events.Start()] self.layer = layer self.expected = expected self.actual = [] self._errored = False self.logs = logs self.hooks = hooks def __rshift__(self, e): """Add an event to send""" if isinstance(e, collections.abc.Iterable): for ev in e: self.__rshift__(ev) return self assert isinstance(e, events.Event) self.expected.append(e) return self def __lshift__(self, c): """Add an expected command""" if c is None: return self if isinstance(c, collections.abc.Iterable): for cmd in c: self.__lshift__(cmd) return self assert isinstance(c, commands.Command) prev = self.expected[-1] two_subsequent_sends_to_the_same_remote = ( isinstance(c, commands.SendData) and isinstance(prev, commands.SendData) and prev.connection is c.connection ) if two_subsequent_sends_to_the_same_remote: prev.data += c.data else: self.expected.append(c) return self def __bool__(self): """Determine if playbook is correct.""" already_asserted = len(self.actual) i = already_asserted while i < len(self.expected): x = self.expected[i] if isinstance(x, commands.Command): pass else: if hasattr(x, "playbook_eval"): try: x = self.expected[i] = x.playbook_eval(self) except Exception: self.actual.append(_TracebackInPlaybook(traceback.format_exc())) break for name, value in vars(x).items(): if isinstance(value, _Placeholder): setattr(x, name, value()) if isinstance(x, events.OpenConnectionCompleted) and not x.reply: x.command.connection.state = ConnectionState.OPEN x.command.connection.timestamp_start = 1624544785 elif isinstance(x, events.ConnectionClosed): x.connection.state &= ~ConnectionState.CAN_READ x.connection.timestamp_end = 1624544787 self.actual.append(x) cmds: list[commands.Command] = [] try: # consume them one by one so that we can extend the log with all commands until traceback. for cmd in self.layer.handle_event(x): cmds.append(cmd) except Exception: self.actual.extend(cmds) self.actual.append(_TracebackInPlaybook(traceback.format_exc())) break cmds = list( _merge_sends( cmds, ignore_hooks=not self.hooks, ignore_logs=not self.logs ) ) self.actual.extend(cmds) pos = len(self.actual) - len(cmds) - 1 hook_replies = [] for cmd in cmds: pos += 1 assert self.actual[pos] == cmd if isinstance(cmd, commands.CloseTcpConnection) and cmd.half_close: cmd.connection.state &= ~ConnectionState.CAN_WRITE elif isinstance(cmd, commands.CloseConnection): cmd.connection.state = ConnectionState.CLOSED elif isinstance(cmd, commands.Log): need_to_emulate_log = ( not self.logs and cmd.level in (logging.DEBUG, logging.INFO) and ( pos >= len(self.expected) or not isinstance(self.expected[pos], commands.Log) ) ) if need_to_emulate_log: self.expected.insert(pos, cmd) elif isinstance(cmd, commands.StartHook) and not self.hooks: need_to_emulate_hook = not self.hooks and ( pos >= len(self.expected) or ( not ( isinstance(self.expected[pos], commands.StartHook) and self.expected[pos].name == cmd.name ) ) ) if need_to_emulate_hook: self.expected.insert(pos, cmd) if cmd.blocking: # the current event may still have yielded more events, so we need to insert # the reply *after* those additional events. hook_replies.append(events.HookCompleted(cmd)) self.expected = ( self.expected[: pos + 1] + hook_replies + self.expected[pos + 1 :] ) eq( self.expected[i:], self.actual[i:] ) # compare now already to set placeholders i += 1 if not eq(self.expected, self.actual): self._errored = True diffs = list( difflib.ndiff( [_fmt_entry(x) for x in self.expected], [_fmt_entry(x) for x in self.actual], ) ) if already_asserted: diffs.insert(already_asserted, "==== asserted until here ====") diff = "\n".join(diffs) raise AssertionError(f"Playbook mismatch!\n{diff}") else: return True def __del__(self): # Playbooks are only executed on assert (which signals that the playbook is partially # complete), so we need to signal if someone forgets to assert and playbooks aren't # evaluated. is_final_destruct = not hasattr(self, "_errored") if is_final_destruct or ( not self._errored and len(self.actual) < len(self.expected) ): raise RuntimeError("Unfinished playbook!") class reply(events.Event): args: tuple[Any, ...] to: commands.Command | type[commands.Command] | int side_effect: Callable[[Any], Any] def __init__( self, *args, to: commands.Command | type[commands.Command] | int = -1, side_effect: Callable[[Any], None] = lambda x: None, ): """Utility method to reply to the latest hook in playbooks.""" assert not args or not isinstance(args[0], commands.Command) self.args = args self.to = to self.side_effect = side_effect def playbook_eval(self, playbook: Playbook) -> events.CommandCompleted: if isinstance(self.to, int): expected = playbook.expected[: playbook.expected.index(self)] assert abs(self.to) < len(expected) to = expected[self.to] if not isinstance(to, commands.Command): raise AssertionError(f"There is no command at offset {self.to}: {to}") else: self.to = to elif isinstance(self.to, type): for cmd in reversed(playbook.actual): if isinstance(cmd, self.to): assert isinstance(cmd, commands.Command) self.to = cmd break else: raise AssertionError(f"There is no command of type {self.to}.") for cmd in reversed(playbook.actual): if eq(self.to, cmd): self.to = cmd break else: raise AssertionError(f"Expected command {self.to} did not occur.") assert isinstance(self.to, commands.Command) if isinstance(self.to, commands.StartHook): self.side_effect(*self.to.args()) reply_cls = events.HookCompleted else: self.side_effect(self.to) reply_cls = command_reply_subclasses[type(self.to)] try: inst = reply_cls(self.to, *self.args) except TypeError as e: raise ValueError(f"Cannot instantiate {reply_cls.__name__}: {e}") return inst T = TypeVar("T") class _Placeholder(Generic[T]): """ Placeholder value in playbooks, so that objects (flows in particular) can be referenced before they are known. Example: f = Placeholder(TCPFlow) assert ( playbook(tcp.TCPLayer(tctx)) << TcpStartHook(f) # the flow object returned here is generated by the layer. ) # We can obtain the flow object now using f(): assert f().messages == 0 """ def __init__(self, cls: type[T]): self._obj = None self._cls = cls def __call__(self) -> T: """Get the actual object""" return self._obj def setdefault(self, value: T) -> T: if self._obj is None: if self._cls is not Any and not isinstance(value, self._cls): raise TypeError( f"expected {self._cls.__name__}, got {type(value).__name__}." ) self._obj = value return self._obj def __repr__(self): return f"Placeholder:{self._obj!r}" def __str__(self): return f"Placeholder:{self._obj}" # noinspection PyPep8Naming def Placeholder(cls: type[T] = Any) -> T | _Placeholder[T]: return _Placeholder(cls) class _AnyStrPlaceholder(_Placeholder[AnyStr]): def __init__(self, match: AnyStr): super().__init__(type(match)) self._match = match def setdefault(self, value: AnyStr) -> AnyStr: if self._obj is None: super().setdefault(value) if not re.search(self._match, self._obj, re.DOTALL): # type: ignore raise ValueError(f"{self._obj!r} does not match {self._match!r}.") return self._obj # noinspection PyPep8Naming def BytesMatching(match: bytes) -> bytes | _AnyStrPlaceholder[bytes]: return _AnyStrPlaceholder(match) # noinspection PyPep8Naming def StrMatching(match: str) -> str | _AnyStrPlaceholder[str]: return _AnyStrPlaceholder(match) class EchoLayer(Layer): """Echo layer that sends all data back to the client in lowercase.""" def _handle_event(self, event: events.Event) -> layer.CommandGenerator[None]: if isinstance(event, events.DataReceived): yield commands.SendData(event.connection, event.data.lower()) if isinstance(event, events.ConnectionClosed): yield commands.CloseConnection(event.connection) class RecordLayer(Layer): """Layer that records all events but does nothing.""" event_log: list[events.Event] def __init__(self, context: context.Context) -> None: super().__init__(context) self.event_log = [] def _handle_event(self, event: events.Event) -> layer.CommandGenerator[None]: self.event_log.append(event) yield from () def reply_next_layer( child_layer: type[Layer] | Callable[[context.Context], Layer], *args, **kwargs ) -> reply: """Helper function to simplify the syntax for next_layer events to this: << NextLayerHook(nl) >> reply_next_layer(tutils.EchoLayer) """ def set_layer(next_layer: layer.NextLayer) -> None: next_layer.layer = child_layer(next_layer.context) return reply(*args, side_effect=set_layer, **kwargs)
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/test_context.py
test/mitmproxy/proxy/test_context.py
from mitmproxy.proxy import context from mitmproxy.test import taddons from mitmproxy.test import tflow def test_context(): with taddons.context() as tctx: c = context.Context(tflow.tclient_conn(), tctx.options) assert repr(c) c.layers.append(1) assert repr(c) c2 = c.fork() c.layers.append(2) c2.layers.append(3) assert c.layers == [1, 2] assert c2.layers == [1, 3]
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/conftest.py
test/mitmproxy/proxy/conftest.py
import os import pytest from hypothesis import settings from mitmproxy import connection from mitmproxy import options from mitmproxy.addons.proxyserver import Proxyserver from mitmproxy.proxy import context @pytest.fixture def tctx() -> 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, ) settings.register_profile("fast", max_examples=10, deadline=None) settings.register_profile("deep", max_examples=100_000, deadline=None) settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", "fast"))
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/test_tunnel.py
test/mitmproxy/proxy/test_tunnel.py
import pytest 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 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): child_layer: layer.Layer | None = None def _handle_event(self, event: Event) -> layer.CommandGenerator[None]: if isinstance(event, Start): yield Log(f"Got start. Server state: {self.context.server.state.name}") elif isinstance(event, DataReceived) and event.data == b"client-hello": yield SendData(self.context.client, b"client-hello-reply") elif isinstance(event, DataReceived) and event.data == b"server-hello": yield SendData(self.context.server, b"server-hello-reply") elif isinstance(event, DataReceived) and event.data == b"open": err = yield OpenConnection(self.context.server) yield Log(f"Opened: {err=}. Server state: {self.context.server.state.name}") elif isinstance(event, DataReceived) and event.data == b"half-close": err = yield CloseTcpConnection(event.connection, half_close=True) elif isinstance(event, ConnectionClosed): yield Log(f"Got {event.connection.__class__.__name__.lower()} close.") yield CloseConnection(event.connection) else: raise AssertionError class TTunnelLayer(tunnel.TunnelLayer): def start_handshake(self) -> layer.CommandGenerator[None]: yield SendData(self.tunnel_connection, b"handshake-hello") def receive_handshake_data( self, data: bytes ) -> layer.CommandGenerator[tuple[bool, str | None]]: yield SendData(self.tunnel_connection, data) if data == b"handshake-success": return True, None else: return False, "handshake error" def send_data(self, data: bytes) -> layer.CommandGenerator[None]: yield SendData(self.tunnel_connection, b"tunneled-" + data) def receive_data(self, data: bytes) -> layer.CommandGenerator[None]: yield from self.event_to_child( DataReceived(self.conn, data.replace(b"tunneled-", b"")) ) @pytest.mark.parametrize("success", ["success", "fail"]) def test_tunnel_handshake_start(tctx: Context, success): server = Server(address=("proxy", 1234)) server.state = ConnectionState.OPEN tl = TTunnelLayer(tctx, server, tctx.server) tl.child_layer = TChildLayer(tctx) assert repr(tl) playbook = Playbook(tl, logs=True) ( playbook << SendData(server, b"handshake-hello") >> DataReceived(tctx.client, b"client-hello") >> DataReceived(server, b"handshake-" + success.encode()) << SendData(server, b"handshake-" + success.encode()) ) if success == "success": playbook << Log("Got start. Server state: OPEN") else: playbook << CloseConnection(server) playbook << Log("Got start. Server state: CLOSED") playbook << SendData(tctx.client, b"client-hello-reply") if success == "success": playbook >> DataReceived(server, b"tunneled-server-hello") playbook << SendData(server, b"tunneled-server-hello-reply") assert playbook @pytest.mark.parametrize("success", ["success", "fail"]) def test_tunnel_handshake_command(tctx: Context, success): server = Server(address=("proxy", 1234)) tl = TTunnelLayer(tctx, server, tctx.server) tl.child_layer = TChildLayer(tctx) playbook = Playbook(tl, logs=True) ( playbook << Log("Got start. Server state: CLOSED") >> DataReceived(tctx.client, b"client-hello") << SendData(tctx.client, b"client-hello-reply") >> DataReceived(tctx.client, b"open") << OpenConnection(server) >> reply(None) << SendData(server, b"handshake-hello") >> DataReceived(server, b"handshake-" + success.encode()) << SendData(server, b"handshake-" + success.encode()) ) if success == "success": assert ( playbook << Log(f"Opened: err=None. Server state: OPEN") >> DataReceived(server, b"tunneled-server-hello") << SendData(server, b"tunneled-server-hello-reply") >> ConnectionClosed(tctx.client) << Log("Got client close.") << CloseConnection(tctx.client) ) assert tl.tunnel_state is tunnel.TunnelState.OPEN assert ( playbook >> ConnectionClosed(server) << Log("Got server close.") << CloseConnection(server) ) assert tl.tunnel_state is tunnel.TunnelState.CLOSED else: assert ( playbook << CloseConnection(server) << Log("Opened: err='handshake error'. Server state: CLOSED") ) assert tl.tunnel_state is tunnel.TunnelState.CLOSED def test_tunnel_default_impls(tctx: Context): """ Some tunnels don't need certain features, so the default behaviour should be to be transparent. """ server = Server(address=None) server.state = ConnectionState.OPEN tl = tunnel.TunnelLayer(tctx, server, tctx.server) tl.child_layer = TChildLayer(tctx) playbook = Playbook(tl, logs=True) assert ( playbook << Log("Got start. Server state: OPEN") >> DataReceived(server, b"server-hello") << SendData(server, b"server-hello-reply") ) assert tl.tunnel_state is tunnel.TunnelState.OPEN assert ( playbook >> ConnectionClosed(server) << Log("Got server close.") << CloseConnection(server) ) assert tl.tunnel_state is tunnel.TunnelState.CLOSED assert ( playbook >> DataReceived(tctx.client, b"open") << OpenConnection(server) >> reply(None) << Log("Opened: err=None. Server state: OPEN") >> DataReceived(server, b"half-close") << CloseTcpConnection(server, half_close=True) ) def test_tunnel_openconnection_error(tctx: Context): server = Server(address=("proxy", 1234)) tl = TTunnelLayer(tctx, server, tctx.server) tl.child_layer = TChildLayer(tctx) playbook = Playbook(tl, logs=True) assert ( playbook << Log("Got start. Server state: CLOSED") >> DataReceived(tctx.client, b"open") << OpenConnection(server) ) assert tl.tunnel_state is tunnel.TunnelState.ESTABLISHING assert ( playbook >> reply("IPoAC packet dropped.") << Log("Opened: err='IPoAC packet dropped.'. Server state: CLOSED") ) assert tl.tunnel_state is tunnel.TunnelState.CLOSED @pytest.mark.parametrize("disconnect", ["client", "server"]) def test_disconnect_during_handshake_start(tctx: Context, disconnect): server = Server(address=("proxy", 1234)) server.state = ConnectionState.OPEN tl = TTunnelLayer(tctx, server, tctx.server) tl.child_layer = TChildLayer(tctx) playbook = Playbook(tl, logs=True) assert playbook << SendData(server, b"handshake-hello") if disconnect == "client": assert ( playbook >> ConnectionClosed(tctx.client) >> ConnectionClosed( server ) # proxyserver will cancel all other connections as well. << CloseConnection(server) << Log("Got start. Server state: CLOSED") << Log("Got client close.") << CloseConnection(tctx.client) ) else: assert ( playbook >> ConnectionClosed(server) << CloseConnection(server) << Log("Got start. Server state: CLOSED") ) @pytest.mark.parametrize("disconnect", ["client", "server"]) def test_disconnect_during_handshake_command(tctx: Context, disconnect): server = Server(address=("proxy", 1234)) tl = TTunnelLayer(tctx, server, tctx.server) tl.child_layer = TChildLayer(tctx) playbook = Playbook(tl, logs=True) assert ( playbook << Log("Got start. Server state: CLOSED") >> DataReceived(tctx.client, b"client-hello") << SendData(tctx.client, b"client-hello-reply") >> DataReceived(tctx.client, b"open") << OpenConnection(server) >> reply(None) << SendData(server, b"handshake-hello") ) if disconnect == "client": assert ( playbook >> ConnectionClosed(tctx.client) >> ConnectionClosed( server ) # proxyserver will cancel all other connections as well. << CloseConnection(server) << Log("Opened: err='connection closed'. Server state: CLOSED") << Log("Got client close.") << CloseConnection(tctx.client) ) else: assert ( playbook >> ConnectionClosed(server) << CloseConnection(server) << Log("Opened: err='connection closed'. Server state: CLOSED") ) def test_layer_stack(tctx): stack = tunnel.LayerStack() a = TChildLayer(tctx) b = TChildLayer(tctx) stack /= a stack /= b assert stack[0] == a assert a.child_layer is b stack2 = tunnel.LayerStack() stack2 /= TChildLayer(tctx) stack2 /= stack assert stack2[0].child_layer is a # type: ignore
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/bench.py
test/mitmproxy/proxy/bench.py
""" Usage: - pip install pytest-benchmark - pytest bench.py See also: - https://github.com/mitmproxy/proxybench """ import copy from .layers import test_tcp from .layers import test_tls from .layers.http import test_http from .layers.http import test_http2 def test_bench_http_roundtrip(tctx, benchmark): # benchmark something benchmark(test_http.test_http_proxy, tctx) def test_bench_http2_roundtrip(tctx, benchmark): # benchmark something benchmark(test_http2.test_simple, tctx) def test_bench_tcp_roundtrip(tctx, benchmark): # benchmark something benchmark(lambda: test_tcp.test_simple(copy.deepcopy(tctx))) def test_bench_server_tls(tctx, benchmark): t = test_tls.TestServerTLS().test_simple benchmark(lambda: t(copy.deepcopy(tctx))) def test_bench_client_tls(tctx, benchmark): t = test_tls.TestClientTLS().test_client_only benchmark(lambda: t(copy.deepcopy(tctx))) def test_bench_tls_both(tctx, benchmark): t = test_tls.TestClientTLS().test_server_required benchmark(lambda: t(copy.deepcopy(tctx)))
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/__init__.py
test/mitmproxy/proxy/__init__.py
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/test_server_hooks.py
test/mitmproxy/proxy/test_server_hooks.py
from mitmproxy.proxy import server_hooks def test_noop(): assert server_hooks
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false
mitmproxy/mitmproxy
https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/proxy/test_layer.py
test/mitmproxy/proxy/test_layer.py
from logging import DEBUG import pytest 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 class TestLayer: def test_continue(self, tctx: Context): class TLayer(layer.Layer): def _handle_event( self, event: events.Event ) -> layer.CommandGenerator[None]: yield commands.OpenConnection(self.context.server) yield commands.OpenConnection(self.context.server) assert ( tutils.Playbook(TLayer(tctx)) << commands.OpenConnection(tctx.server) >> tutils.reply(None) << commands.OpenConnection(tctx.server) >> tutils.reply(None) ) def test_debug_messages(self, tctx: Context): tctx.server.id = "serverid" class TLayer(layer.Layer): debug = " " def _handle_event( self, event: events.Event ) -> layer.CommandGenerator[None]: yield from self.state(event) def state_foo(self, event: events.Event) -> layer.CommandGenerator[None]: assert isinstance(event, events.Start) yield commands.OpenConnection(self.context.server) self.state = self.state_bar state = state_foo def state_bar(self, event: events.Event) -> layer.CommandGenerator[None]: assert isinstance(event, events.DataReceived) yield commands.Log("baz") tlayer = TLayer(tctx) assert ( tutils.Playbook(tlayer, hooks=True, logs=True) << commands.Log(" >> Start({})", DEBUG) << commands.Log( " << OpenConnection({'connection': Server({'id': '…rverid', 'address': None})})", DEBUG, ) << commands.OpenConnection(tctx.server) >> events.DataReceived(tctx.client, b"foo") << commands.Log(" >! DataReceived(client, b'foo')", DEBUG) >> tutils.reply(None, to=-3) << commands.Log( " >> Reply(OpenConnection({'connection': Server({'id': '…rverid', 'address': None, " "'state': <ConnectionState.OPEN: 3>, 'timestamp_start': 1624544785})}), None)", DEBUG, ) << commands.Log(" !> DataReceived(client, b'foo')", DEBUG) << commands.Log("baz") ) assert repr(tlayer) == "TLayer(state: bar)" def test_debug_shorten(self, tctx): t = layer.Layer(tctx) t.debug = " " assert t._Layer__debug("x" * 4096).message == " " + "x" * 2048 + "…" assert t._Layer__debug("x" * 4096).message == " " + "x" * 256 + "…" assert t._Layer__debug("foo").message == " foo" class TestNextLayer: def test_simple(self, tctx: Context): nl = layer.NextLayer(tctx, ask_on_start=True) nl.debug = " " playbook = tutils.Playbook(nl, hooks=True) assert ( playbook << layer.NextLayerHook(nl) >> tutils.reply() >> events.DataReceived(tctx.client, b"foo") << layer.NextLayerHook(nl) >> tutils.reply() >> events.DataReceived(tctx.client, b"bar") << layer.NextLayerHook(nl) ) assert nl.data_client() == b"foobar" assert nl.data_server() == b"" nl.layer = tutils.EchoLayer(tctx) assert ( playbook >> tutils.reply() << commands.SendData(tctx.client, b"foo") << commands.SendData(tctx.client, b"bar") ) def test_late_hook_reply(self, tctx: Context): """ Properly handle case where we receive an additional event while we are waiting for a reply from the proxy core. """ nl = layer.NextLayer(tctx) playbook = tutils.Playbook(nl) assert ( playbook >> events.DataReceived(tctx.client, b"foo") << layer.NextLayerHook(nl) >> events.DataReceived(tctx.client, b"bar") ) assert nl.data_client() == b"foo" # "bar" is paused. nl.layer = tutils.EchoLayer(tctx) assert ( playbook >> tutils.reply(to=-2) << commands.SendData(tctx.client, b"foo") << commands.SendData(tctx.client, b"bar") ) @pytest.mark.parametrize("layer_found", [True, False]) def test_receive_close(self, tctx: Context, layer_found: bool): """Test that we abort a client connection which has disconnected without any layer being found.""" nl = layer.NextLayer(tctx) playbook = tutils.Playbook(nl) assert ( playbook >> events.DataReceived(tctx.client, b"foo") << layer.NextLayerHook(nl) >> events.ConnectionClosed(tctx.client) ) if layer_found: nl.layer = tutils.RecordLayer(tctx) assert playbook >> tutils.reply(to=-2) assert isinstance(nl.layer.event_log[-1], events.ConnectionClosed) else: assert ( playbook >> tutils.reply(to=-2) << commands.CloseConnection(tctx.client) << None ) def test_func_references(self, tctx: Context): nl = layer.NextLayer(tctx) playbook = tutils.Playbook(nl) assert ( playbook >> events.DataReceived(tctx.client, b"foo") << layer.NextLayerHook(nl) ) nl.layer = tutils.EchoLayer(tctx) handle = nl.handle_event playbook >> tutils.reply() playbook << commands.SendData(tctx.client, b"foo") assert playbook (sd,) = handle(events.DataReceived(tctx.client, b"bar")) assert isinstance(sd, commands.SendData) def test_repr(self, tctx: Context): nl = layer.NextLayer(tctx) nl.layer = tutils.EchoLayer(tctx) assert repr(nl) assert nl.stack_pos assert nl.layer.stack_pos
python
MIT
e6aa924bb411a9687b91920b8d094af37bc02b90
2026-01-04T14:40:00.086164Z
false