From a68ea5116272569221610cc2d8bd6e9f56eac26f Mon Sep 17 00:00:00 2001 From: "Kirill.T" Date: Sun, 26 Jan 2025 17:34:38 +0100 Subject: [PATCH 1/5] Test autofix.ci --- CONTRIBUTING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c1dc150096..b0b1426e5a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,6 +3,7 @@ Please contribute upstream--we follow mitmproxy, but they are the source of truth for the proxy in general. + ---------------------------------- As an open source project, mitmproxy welcomes contributions of all forms. If you would like to bring the project forward, please consider contributing in the following areas: From c1089db7247135188215ae5827b61af3040f3c29 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sun, 26 Jan 2025 16:36:31 +0000 Subject: [PATCH 2/5] [autofix.ci] apply automated fixes --- clients/examples/python/docs/conf.py | 64 +- clients/examples/python/setup.py | 50 +- .../test_browserup_mitmproxy_python_client.py | 13 +- .../BrowserUpMitmProxyClient/__init__.py | 41 +- .../BrowserUpMitmProxyClient/api/__init__.py | 1 - .../api/browser_up_proxy_api.py | 894 +++++++++++------- .../BrowserUpMitmProxyClient/api_client.py | 520 +++++----- .../BrowserUpMitmProxyClient/api_response.py | 25 +- .../BrowserUpMitmProxyClient/configuration.py | 126 +-- .../BrowserUpMitmProxyClient/exceptions.py | 31 +- .../models/__init__.py | 41 +- .../BrowserUpMitmProxyClient/models/action.py | 64 +- .../models/counter.py | 47 +- .../BrowserUpMitmProxyClient/models/error.py | 40 +- .../BrowserUpMitmProxyClient/models/har.py | 45 +- .../models/har_entry.py | 106 ++- .../models/har_entry_cache.py | 72 +- .../models/har_entry_cache_before_request.py | 48 +- .../models/har_entry_request.py | 118 ++- .../models/har_entry_request_cookies_inner.py | 65 +- .../models/har_entry_request_post_data.py | 56 +- ...ar_entry_request_post_data_params_inner.py | 47 +- .../har_entry_request_query_string_inner.py | 43 +- .../models/har_entry_response.py | 103 +- .../models/har_entry_response_content.py | 132 ++- .../models/har_entry_timings.py | 65 +- .../models/har_log.py | 67 +- .../models/har_log_creator.py | 43 +- .../BrowserUpMitmProxyClient/models/header.py | 43 +- .../models/largest_contentful_paint.py | 57 +- .../models/match_criteria.py | 118 ++- .../models/name_value_pair.py | 38 +- .../BrowserUpMitmProxyClient/models/page.py | 90 +- .../models/page_timing.py | 137 ++- .../models/page_timings.py | 136 ++- .../models/verify_result.py | 44 +- .../models/web_socket_message.py | 47 +- .../python/BrowserUpMitmProxyClient/rest.py | 313 +++--- clients/python/setup.py | 20 +- clients/python/test/test_action.py | 26 +- .../python/test/test_browser_up_proxy_api.py | 57 +- clients/python/test/test_counter.py | 26 +- clients/python/test/test_error.py | 26 +- clients/python/test/test_har.py | 26 +- clients/python/test/test_har_entry.py | 26 +- clients/python/test/test_har_entry_cache.py | 26 +- .../test_har_entry_cache_before_request.py | 26 +- clients/python/test/test_har_entry_request.py | 26 +- .../test_har_entry_request_cookies_inner.py | 26 +- .../test/test_har_entry_request_post_data.py | 26 +- ...ar_entry_request_post_data_params_inner.py | 26 +- ...st_har_entry_request_query_string_inner.py | 26 +- .../python/test/test_har_entry_response.py | 26 +- .../test/test_har_entry_response_content.py | 26 +- clients/python/test/test_har_entry_timings.py | 26 +- clients/python/test/test_har_log.py | 26 +- clients/python/test/test_har_log_creator.py | 26 +- clients/python/test/test_header.py | 26 +- .../test/test_largest_contentful_paint.py | 26 +- clients/python/test/test_match_criteria.py | 26 +- clients/python/test/test_name_value_pair.py | 26 +- clients/python/test/test_page.py | 26 +- clients/python/test/test_page_timing.py | 26 +- clients/python/test/test_page_timings.py | 26 +- clients/python/test/test_verify_result.py | 26 +- .../python/test/test_web_socket_message.py | 26 +- .../addons/browserup/browser_data_addon.py | 83 +- .../browserup/browserup_addons_manager.py | 83 +- .../addons/browserup/har/flow_capture.py | 201 ++-- .../browserup/har/flow_har_entry_patch.py | 8 +- mitmproxy/addons/browserup/har/har_builder.py | 44 +- .../addons/browserup/har/har_capture_types.py | 35 +- mitmproxy/addons/browserup/har/har_manager.py | 165 ++-- .../addons/browserup/har/har_resources.py | 101 +- mitmproxy/addons/browserup/har/har_schemas.py | 237 ++++- .../addons/browserup/har/har_verifications.py | 123 ++- .../addons/browserup/har_capture_addon.py | 52 +- mitmproxy/addons/browserup/latency_addon.py | 6 +- .../addons/browserup/schemas/__init__.py | 33 +- mitmproxy/tools/browserup_proxy.py | 36 +- release/cibuild.py | 304 +++--- .../hook-mitmproxy.addons.onboardingapp.py | 2 +- release/hooks/hook-mitmproxy.py | 7 +- release/hooks/hook-mitmproxy.tools.web.py | 2 +- test/mitmproxy/addons/browserup/test_api.py | 52 +- .../addons/browserup/test_counters.py | 67 +- .../mitmproxy/addons/browserup/test_errors.py | 67 +- .../addons/browserup/test_har_capture.py | 194 ++-- .../browserup/test_har_verifications.py | 113 ++- 89 files changed, 3994 insertions(+), 2764 deletions(-) diff --git a/clients/examples/python/docs/conf.py b/clients/examples/python/docs/conf.py index 7555c7ccca..bf4267a836 100755 --- a/clients/examples/python/docs/conf.py +++ b/clients/examples/python/docs/conf.py @@ -19,7 +19,8 @@ # import os import sys -sys.path.insert(0, os.path.abspath('..')) + +sys.path.insert(0, os.path.abspath("..")) import browserup_mitmproxy_python_client_usage_example @@ -31,22 +32,22 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] +extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = 'Browserup MitmProxy Python Client Usage Example' +project = "Browserup MitmProxy Python Client Usage Example" copyright = "2021, Browserup Inc." author = "Browserup Inc." @@ -69,10 +70,10 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -83,7 +84,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'alabaster' +html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the @@ -94,13 +95,13 @@ # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # -- Options for HTMLHelp output --------------------------------------- # Output file base name for HTML help builder. -htmlhelp_basename = 'browserup_mitmproxy_python_client_usage_exampledoc' +htmlhelp_basename = "browserup_mitmproxy_python_client_usage_exampledoc" # -- Options for LaTeX output ------------------------------------------ @@ -109,15 +110,12 @@ # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. # # 'preamble': '', - # Latex figure (float) alignment # # 'figure_align': 'htbp', @@ -127,9 +125,13 @@ # (source start file, target name, title, author, documentclass # [howto, manual, or own class]). latex_documents = [ - (master_doc, 'browserup_mitmproxy_python_client_usage_example.tex', - 'Browserup MitmProxy Python Client Usage Example Documentation', - 'Browserup Inc.', 'manual'), + ( + master_doc, + "browserup_mitmproxy_python_client_usage_example.tex", + "Browserup MitmProxy Python Client Usage Example Documentation", + "Browserup Inc.", + "manual", + ), ] @@ -138,9 +140,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'browserup_mitmproxy_python_client_usage_example', - 'Browserup MitmProxy Python Client Usage Example Documentation', - [author], 1) + ( + master_doc, + "browserup_mitmproxy_python_client_usage_example", + "Browserup MitmProxy Python Client Usage Example Documentation", + [author], + 1, + ) ] @@ -150,13 +156,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'browserup_mitmproxy_python_client_usage_example', - 'Browserup MitmProxy Python Client Usage Example Documentation', - author, - 'browserup_mitmproxy_python_client_usage_example', - 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "browserup_mitmproxy_python_client_usage_example", + "Browserup MitmProxy Python Client Usage Example Documentation", + author, + "browserup_mitmproxy_python_client_usage_example", + "One line description of project.", + "Miscellaneous", + ), ] - - - diff --git a/clients/examples/python/setup.py b/clients/examples/python/setup.py index b04b4cb961..22437b93ba 100644 --- a/clients/examples/python/setup.py +++ b/clients/examples/python/setup.py @@ -2,43 +2,49 @@ """The setup script.""" -from setuptools import setup, find_packages +from setuptools import find_packages +from setuptools import setup -with open('README.rst') as readme_file: +with open("README.rst") as readme_file: readme = readme_file.read() -with open('HISTORY.rst') as history_file: +with open("HISTORY.rst") as history_file: history = history_file.read() -requirements = [ ] +requirements = [] -test_requirements = [ ] +test_requirements = [] setup( author="Browserup Inc.", - author_email='developers@browserup.com', - python_requires='>=3.6', + author_email="developers@browserup.com", + python_requires=">=3.6", classifiers=[ - 'Development Status :: 2 - Pre-Alpha', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: Apache Software License', - 'Natural Language :: English', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', + "Development Status :: 2 - Pre-Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Natural Language :: English", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", ], description="Browserup MitmProxy Python Client Usage Example", install_requires=requirements, license="Apache Software License 2.0", - long_description=readme + '\n\n' + history, + long_description=readme + "\n\n" + history, include_package_data=True, - keywords='browserup_mitmproxy_python_client_usage_example', - name='browserup_mitmproxy_python_client_usage_example', - packages=find_packages(include=['browserup_mitmproxy_python_client_usage_example', 'browserup_mitmproxy_python_client_usage_example.*']), - test_suite='tests', + keywords="browserup_mitmproxy_python_client_usage_example", + name="browserup_mitmproxy_python_client_usage_example", + packages=find_packages( + include=[ + "browserup_mitmproxy_python_client_usage_example", + "browserup_mitmproxy_python_client_usage_example.*", + ] + ), + test_suite="tests", tests_require=test_requirements, - url='https://github.com/browserup/browserup_mitmproxy_python_client_usage_example', - version='0.1.0', + url="https://github.com/browserup/browserup_mitmproxy_python_client_usage_example", + version="0.1.0", zip_safe=False, ) diff --git a/clients/examples/python/tests/test_browserup_mitmproxy_python_client.py b/clients/examples/python/tests/test_browserup_mitmproxy_python_client.py index 033254be42..5fefbecd38 100644 --- a/clients/examples/python/tests/test_browserup_mitmproxy_python_client.py +++ b/clients/examples/python/tests/test_browserup_mitmproxy_python_client.py @@ -5,18 +5,11 @@ import unittest import BrowserUpMitmProxyClient - -from pprint import pprint from BrowserUpMitmProxyClient.api import browser_up_proxy_api from BrowserUpMitmProxyClient.model.counter import Counter -from BrowserUpMitmProxyClient.model.error import Error -from BrowserUpMitmProxyClient.model.har import Har -from BrowserUpMitmProxyClient.model.match_criteria import MatchCriteria -from BrowserUpMitmProxyClient.model.verify_result import VerifyResult class TestBrowserupMitmProxyPythonClient(unittest.TestCase): - def setUp(self): """Configure client""" self.configuration = BrowserUpMitmProxyClient.Configuration( @@ -63,4 +56,8 @@ def test_adding_counter_using_client(self): har = self.api_instance.get_har_log() self.assertTrue( - any(item.name == counter.name and item.value == counter.value for item in har.log.pages[0].counters)) + any( + item.name == counter.name and item.value == counter.value + for item in har.log.pages[0].counters + ) + ) diff --git a/clients/python/BrowserUpMitmProxyClient/__init__.py b/clients/python/BrowserUpMitmProxyClient/__init__.py index 2675324b56..c96a7de418 100644 --- a/clients/python/BrowserUpMitmProxyClient/__init__.py +++ b/clients/python/BrowserUpMitmProxyClient/__init__.py @@ -3,18 +3,17 @@ # flake8: noqa """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - __version__ = "1.0.1" # import apis into sdk package @@ -38,19 +37,33 @@ from BrowserUpMitmProxyClient.models.har import Har from BrowserUpMitmProxyClient.models.har_entry import HarEntry from BrowserUpMitmProxyClient.models.har_entry_cache import HarEntryCache -from BrowserUpMitmProxyClient.models.har_entry_cache_before_request import HarEntryCacheBeforeRequest +from BrowserUpMitmProxyClient.models.har_entry_cache_before_request import ( + HarEntryCacheBeforeRequest, +) from BrowserUpMitmProxyClient.models.har_entry_request import HarEntryRequest -from BrowserUpMitmProxyClient.models.har_entry_request_cookies_inner import HarEntryRequestCookiesInner -from BrowserUpMitmProxyClient.models.har_entry_request_post_data import HarEntryRequestPostData -from BrowserUpMitmProxyClient.models.har_entry_request_post_data_params_inner import HarEntryRequestPostDataParamsInner -from BrowserUpMitmProxyClient.models.har_entry_request_query_string_inner import HarEntryRequestQueryStringInner +from BrowserUpMitmProxyClient.models.har_entry_request_cookies_inner import ( + HarEntryRequestCookiesInner, +) +from BrowserUpMitmProxyClient.models.har_entry_request_post_data import ( + HarEntryRequestPostData, +) +from BrowserUpMitmProxyClient.models.har_entry_request_post_data_params_inner import ( + HarEntryRequestPostDataParamsInner, +) +from BrowserUpMitmProxyClient.models.har_entry_request_query_string_inner import ( + HarEntryRequestQueryStringInner, +) from BrowserUpMitmProxyClient.models.har_entry_response import HarEntryResponse -from BrowserUpMitmProxyClient.models.har_entry_response_content import HarEntryResponseContent +from BrowserUpMitmProxyClient.models.har_entry_response_content import ( + HarEntryResponseContent, +) from BrowserUpMitmProxyClient.models.har_entry_timings import HarEntryTimings from BrowserUpMitmProxyClient.models.har_log import HarLog from BrowserUpMitmProxyClient.models.har_log_creator import HarLogCreator from BrowserUpMitmProxyClient.models.header import Header -from BrowserUpMitmProxyClient.models.largest_contentful_paint import LargestContentfulPaint +from BrowserUpMitmProxyClient.models.largest_contentful_paint import ( + LargestContentfulPaint, +) from BrowserUpMitmProxyClient.models.match_criteria import MatchCriteria from BrowserUpMitmProxyClient.models.name_value_pair import NameValuePair from BrowserUpMitmProxyClient.models.page import Page diff --git a/clients/python/BrowserUpMitmProxyClient/api/__init__.py b/clients/python/BrowserUpMitmProxyClient/api/__init__.py index a800597d12..5d2d67bfb5 100644 --- a/clients/python/BrowserUpMitmProxyClient/api/__init__.py +++ b/clients/python/BrowserUpMitmProxyClient/api/__init__.py @@ -2,4 +2,3 @@ # import apis into api package from BrowserUpMitmProxyClient.api.browser_up_proxy_api import BrowserUpProxyApi - diff --git a/clients/python/BrowserUpMitmProxyClient/api/browser_up_proxy_api.py b/clients/python/BrowserUpMitmProxyClient/api/browser_up_proxy_api.py index 10aadbb202..85ad934305 100644 --- a/clients/python/BrowserUpMitmProxyClient/api/browser_up_proxy_api.py +++ b/clients/python/BrowserUpMitmProxyClient/api/browser_up_proxy_api.py @@ -1,40 +1,35 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import re # noqa: F401 -import io -import warnings -from pydantic import validate_arguments, ValidationError +from pydantic import conint +from pydantic import constr +from pydantic import Field +from pydantic import validate_arguments from typing_extensions import Annotated -from pydantic import Field, conint, constr, validator - +from BrowserUpMitmProxyClient.api_client import ApiClient +from BrowserUpMitmProxyClient.api_response import ApiResponse +from BrowserUpMitmProxyClient.exceptions import ApiTypeError # noqa: F401 +from BrowserUpMitmProxyClient.exceptions import ApiValueError # noqa: F401 from BrowserUpMitmProxyClient.models.counter import Counter from BrowserUpMitmProxyClient.models.error import Error from BrowserUpMitmProxyClient.models.har import Har from BrowserUpMitmProxyClient.models.match_criteria import MatchCriteria from BrowserUpMitmProxyClient.models.verify_result import VerifyResult -from BrowserUpMitmProxyClient.api_client import ApiClient -from BrowserUpMitmProxyClient.api_response import ApiResponse -from BrowserUpMitmProxyClient.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - class BrowserUpProxyApi(object): """NOTE: This class is auto generated by OpenAPI Generator @@ -49,7 +44,17 @@ def __init__(self, api_client=None): self.api_client = api_client @validate_arguments - def add_counter(self, counter : Annotated[Counter, Field(..., description="Receives a new counter to add. The counter is stored, under the hood, in an array in the har under the _counters key")], **kwargs) -> None: # noqa: E501 + def add_counter( + self, + counter: Annotated[ + Counter, + Field( + ..., + description="Receives a new counter to add. The counter is stored, under the hood, in an array in the har under the _counters key", + ), + ], + **kwargs, + ) -> None: # noqa: E501 """add_counter # noqa: E501 Add Custom Counter to the captured traffic har # noqa: E501 @@ -72,13 +77,25 @@ def add_counter(self, counter : Annotated[Counter, Field(..., description="Recei returns the request thread. :rtype: None """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the add_counter_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + raise ValueError( + "Error! Please call the add_counter_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" + ) return self.add_counter_with_http_info(counter, **kwargs) # noqa: E501 @validate_arguments - def add_counter_with_http_info(self, counter : Annotated[Counter, Field(..., description="Receives a new counter to add. The counter is stored, under the hood, in an array in the har under the _counters key")], **kwargs) -> ApiResponse: # noqa: E501 + def add_counter_with_http_info( + self, + counter: Annotated[ + Counter, + Field( + ..., + description="Receives a new counter to add. The counter is stored, under the hood, in an array in the har under the _counters key", + ), + ], + **kwargs, + ) -> ApiResponse: # noqa: E501 """add_counter # noqa: E501 Add Custom Counter to the captured traffic har # noqa: E501 @@ -93,7 +110,7 @@ def add_counter_with_http_info(self, counter : Annotated[Counter, Field(..., des :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the + be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional @@ -117,30 +134,28 @@ def add_counter_with_http_info(self, counter : Annotated[Counter, Field(..., des _params = locals() - _all_params = [ - 'counter' - ] + _all_params = ["counter"] _all_params.extend( [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", ] ) # validate the arguments - for _key, _val in _params['kwargs'].items(): + for _key, _val in _params["kwargs"].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method add_counter" % _key ) _params[_key] = _val - del _params['kwargs'] + del _params["kwargs"] _collection_formats = {} @@ -150,21 +165,22 @@ def add_counter_with_http_info(self, counter : Annotated[Counter, Field(..., des # process the query parameters _query_params = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) + _header_params = dict(_params.get("_headers", {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None - if _params['counter'] is not None: - _body_params = _params['counter'] + if _params["counter"] is not None: + _body_params = _params["counter"] # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) + _content_types_list = _params.get( + "_content_type", + self.api_client.select_header_content_type(["application/json"]), + ) if _content_types_list: - _header_params['Content-Type'] = _content_types_list + _header_params["Content-Type"] = _content_types_list # authentication setting _auth_settings = [] # noqa: E501 @@ -172,7 +188,8 @@ def add_counter_with_http_info(self, counter : Annotated[Counter, Field(..., des _response_types_map = {} return self.api_client.call_api( - '/har/counters', 'POST', + "/har/counters", + "POST", _path_params, _query_params, _header_params, @@ -181,15 +198,26 @@ def add_counter_with_http_info(self, counter : Annotated[Counter, Field(..., des files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _request_auth=_params.get("_request_auth"), + ) @validate_arguments - def add_error(self, error : Annotated[Error, Field(..., description="Receives an error to track. Internally, the error is stored in an array in the har under the _errors key")], **kwargs) -> None: # noqa: E501 + def add_error( + self, + error: Annotated[ + Error, + Field( + ..., + description="Receives an error to track. Internally, the error is stored in an array in the har under the _errors key", + ), + ], + **kwargs, + ) -> None: # noqa: E501 """add_error # noqa: E501 Add Custom Error to the captured traffic har # noqa: E501 @@ -212,13 +240,25 @@ def add_error(self, error : Annotated[Error, Field(..., description="Receives an returns the request thread. :rtype: None """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the add_error_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + raise ValueError( + "Error! Please call the add_error_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" + ) return self.add_error_with_http_info(error, **kwargs) # noqa: E501 @validate_arguments - def add_error_with_http_info(self, error : Annotated[Error, Field(..., description="Receives an error to track. Internally, the error is stored in an array in the har under the _errors key")], **kwargs) -> ApiResponse: # noqa: E501 + def add_error_with_http_info( + self, + error: Annotated[ + Error, + Field( + ..., + description="Receives an error to track. Internally, the error is stored in an array in the har under the _errors key", + ), + ], + **kwargs, + ) -> ApiResponse: # noqa: E501 """add_error # noqa: E501 Add Custom Error to the captured traffic har # noqa: E501 @@ -233,7 +273,7 @@ def add_error_with_http_info(self, error : Annotated[Error, Field(..., descripti :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the + be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional @@ -257,30 +297,28 @@ def add_error_with_http_info(self, error : Annotated[Error, Field(..., descripti _params = locals() - _all_params = [ - 'error' - ] + _all_params = ["error"] _all_params.extend( [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", ] ) # validate the arguments - for _key, _val in _params['kwargs'].items(): + for _key, _val in _params["kwargs"].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method add_error" % _key ) _params[_key] = _val - del _params['kwargs'] + del _params["kwargs"] _collection_formats = {} @@ -290,21 +328,22 @@ def add_error_with_http_info(self, error : Annotated[Error, Field(..., descripti # process the query parameters _query_params = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) + _header_params = dict(_params.get("_headers", {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None - if _params['error'] is not None: - _body_params = _params['error'] + if _params["error"] is not None: + _body_params = _params["error"] # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) + _content_types_list = _params.get( + "_content_type", + self.api_client.select_header_content_type(["application/json"]), + ) if _content_types_list: - _header_params['Content-Type'] = _content_types_list + _header_params["Content-Type"] = _content_types_list # authentication setting _auth_settings = [] # noqa: E501 @@ -312,7 +351,8 @@ def add_error_with_http_info(self, error : Annotated[Error, Field(..., descripti _response_types_map = {} return self.api_client.call_api( - '/har/errors', 'POST', + "/har/errors", + "POST", _path_params, _query_params, _header_params, @@ -321,12 +361,13 @@ def add_error_with_http_info(self, error : Annotated[Error, Field(..., descripti files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _request_auth=_params.get("_request_auth"), + ) @validate_arguments def get_har_log(self, **kwargs) -> Har: # noqa: E501 @@ -350,9 +391,11 @@ def get_har_log(self, **kwargs) -> Har: # noqa: E501 returns the request thread. :rtype: Har """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the get_har_log_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + raise ValueError( + "Error! Please call the get_har_log_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" + ) return self.get_har_log_with_http_info(**kwargs) # noqa: E501 @validate_arguments @@ -369,7 +412,7 @@ def get_har_log_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the + be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional @@ -393,29 +436,28 @@ def get_har_log_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 _params = locals() - _all_params = [ - ] + _all_params = [] _all_params.extend( [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", ] ) # validate the arguments - for _key, _val in _params['kwargs'].items(): + for _key, _val in _params["kwargs"].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_har_log" % _key ) _params[_key] = _val - del _params['kwargs'] + del _params["kwargs"] _collection_formats = {} @@ -425,25 +467,27 @@ def get_har_log_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 # process the query parameters _query_params = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) + _header_params = dict(_params.get("_headers", {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + _header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 # authentication setting _auth_settings = [] # noqa: E501 _response_types_map = { - '200': "Har", + "200": "Har", } return self.api_client.call_api( - '/har', 'GET', + "/har", + "GET", _path_params, _query_params, _header_params, @@ -452,12 +496,13 @@ def get_har_log_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _request_auth=_params.get("_request_auth"), + ) @validate_arguments def healthcheck(self, **kwargs) -> None: # noqa: E501 @@ -481,9 +526,11 @@ def healthcheck(self, **kwargs) -> None: # noqa: E501 returns the request thread. :rtype: None """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the healthcheck_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + raise ValueError( + "Error! Please call the healthcheck_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" + ) return self.healthcheck_with_http_info(**kwargs) # noqa: E501 @validate_arguments @@ -500,7 +547,7 @@ def healthcheck_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the + be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional @@ -524,29 +571,28 @@ def healthcheck_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 _params = locals() - _all_params = [ - ] + _all_params = [] _all_params.extend( [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", ] ) # validate the arguments - for _key, _val in _params['kwargs'].items(): + for _key, _val in _params["kwargs"].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method healthcheck" % _key ) _params[_key] = _val - del _params['kwargs'] + del _params["kwargs"] _collection_formats = {} @@ -556,7 +602,7 @@ def healthcheck_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 # process the query parameters _query_params = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) + _header_params = dict(_params.get("_headers", {})) # process the form parameters _form_params = [] _files = {} @@ -568,7 +614,8 @@ def healthcheck_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 _response_types_map = {} return self.api_client.call_api( - '/healthcheck', 'GET', + "/healthcheck", + "GET", _path_params, _query_params, _header_params, @@ -577,15 +624,23 @@ def healthcheck_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _request_auth=_params.get("_request_auth"), + ) @validate_arguments - def new_page(self, title : Annotated[constr(strict=True), Field(..., description="The unique title for this har page/step.")], **kwargs) -> Har: # noqa: E501 + def new_page( + self, + title: Annotated[ + constr(strict=True), + Field(..., description="The unique title for this har page/step."), + ], + **kwargs, + ) -> Har: # noqa: E501 """new_page # noqa: E501 Starts a fresh HAR Page (Step) in the current active HAR to group requests. # noqa: E501 @@ -608,13 +663,22 @@ def new_page(self, title : Annotated[constr(strict=True), Field(..., description returns the request thread. :rtype: Har """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the new_page_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + raise ValueError( + "Error! Please call the new_page_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" + ) return self.new_page_with_http_info(title, **kwargs) # noqa: E501 @validate_arguments - def new_page_with_http_info(self, title : Annotated[constr(strict=True), Field(..., description="The unique title for this har page/step.")], **kwargs) -> ApiResponse: # noqa: E501 + def new_page_with_http_info( + self, + title: Annotated[ + constr(strict=True), + Field(..., description="The unique title for this har page/step."), + ], + **kwargs, + ) -> ApiResponse: # noqa: E501 """new_page # noqa: E501 Starts a fresh HAR Page (Step) in the current active HAR to group requests. # noqa: E501 @@ -629,7 +693,7 @@ def new_page_with_http_info(self, title : Annotated[constr(strict=True), Field(. :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the + be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional @@ -653,61 +717,60 @@ def new_page_with_http_info(self, title : Annotated[constr(strict=True), Field(. _params = locals() - _all_params = [ - 'title' - ] + _all_params = ["title"] _all_params.extend( [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", ] ) # validate the arguments - for _key, _val in _params['kwargs'].items(): + for _key, _val in _params["kwargs"].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method new_page" % _key ) _params[_key] = _val - del _params['kwargs'] + del _params["kwargs"] _collection_formats = {} # process the path parameters _path_params = {} - if _params['title']: - _path_params['title'] = _params['title'] - + if _params["title"]: + _path_params["title"] = _params["title"] # process the query parameters _query_params = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) + _header_params = dict(_params.get("_headers", {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + _header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 # authentication setting _auth_settings = [] # noqa: E501 _response_types_map = { - '200': "Har", + "200": "Har", } return self.api_client.call_api( - '/har/page', 'POST', + "/har/page", + "POST", _path_params, _query_params, _header_params, @@ -716,12 +779,13 @@ def new_page_with_http_info(self, title : Annotated[constr(strict=True), Field(. files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _request_auth=_params.get("_request_auth"), + ) @validate_arguments def reset_har_log(self, **kwargs) -> Har: # noqa: E501 @@ -745,9 +809,11 @@ def reset_har_log(self, **kwargs) -> Har: # noqa: E501 returns the request thread. :rtype: Har """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the reset_har_log_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + raise ValueError( + "Error! Please call the reset_har_log_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" + ) return self.reset_har_log_with_http_info(**kwargs) # noqa: E501 @validate_arguments @@ -764,7 +830,7 @@ def reset_har_log_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the + be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional @@ -788,29 +854,28 @@ def reset_har_log_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 _params = locals() - _all_params = [ - ] + _all_params = [] _all_params.extend( [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", ] ) # validate the arguments - for _key, _val in _params['kwargs'].items(): + for _key, _val in _params["kwargs"].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method reset_har_log" % _key ) _params[_key] = _val - del _params['kwargs'] + del _params["kwargs"] _collection_formats = {} @@ -820,25 +885,27 @@ def reset_har_log_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 # process the query parameters _query_params = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) + _header_params = dict(_params.get("_headers", {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + _header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 # authentication setting _auth_settings = [] # noqa: E501 _response_types_map = { - '200': "Har", + "200": "Har", } return self.api_client.call_api( - '/har', 'PUT', + "/har", + "PUT", _path_params, _query_params, _header_params, @@ -847,15 +914,30 @@ def reset_har_log_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _request_auth=_params.get("_request_auth"), + ) @validate_arguments - def verify_not_present(self, name : Annotated[constr(strict=True), Field(..., description="The unique name for this verification operation")], match_criteria : Annotated[MatchCriteria, Field(..., description="Match criteria to select requests - response pairs for size tests")], **kwargs) -> VerifyResult: # noqa: E501 + def verify_not_present( + self, + name: Annotated[ + constr(strict=True), + Field(..., description="The unique name for this verification operation"), + ], + match_criteria: Annotated[ + MatchCriteria, + Field( + ..., + description="Match criteria to select requests - response pairs for size tests", + ), + ], + **kwargs, + ) -> VerifyResult: # noqa: E501 """verify_not_present # noqa: E501 Verify no matching items are present in the captured traffic # noqa: E501 @@ -880,13 +962,29 @@ def verify_not_present(self, name : Annotated[constr(strict=True), Field(..., de returns the request thread. :rtype: VerifyResult """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the verify_not_present_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + raise ValueError( + "Error! Please call the verify_not_present_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" + ) return self.verify_not_present_with_http_info(name, match_criteria, **kwargs) # noqa: E501 @validate_arguments - def verify_not_present_with_http_info(self, name : Annotated[constr(strict=True), Field(..., description="The unique name for this verification operation")], match_criteria : Annotated[MatchCriteria, Field(..., description="Match criteria to select requests - response pairs for size tests")], **kwargs) -> ApiResponse: # noqa: E501 + def verify_not_present_with_http_info( + self, + name: Annotated[ + constr(strict=True), + Field(..., description="The unique name for this verification operation"), + ], + match_criteria: Annotated[ + MatchCriteria, + Field( + ..., + description="Match criteria to select requests - response pairs for size tests", + ), + ], + **kwargs, + ) -> ApiResponse: # noqa: E501 """verify_not_present # noqa: E501 Verify no matching items are present in the captured traffic # noqa: E501 @@ -903,7 +1001,7 @@ def verify_not_present_with_http_info(self, name : Annotated[constr(strict=True) :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the + be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional @@ -927,73 +1025,72 @@ def verify_not_present_with_http_info(self, name : Annotated[constr(strict=True) _params = locals() - _all_params = [ - 'name', - 'match_criteria' - ] + _all_params = ["name", "match_criteria"] _all_params.extend( [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", ] ) # validate the arguments - for _key, _val in _params['kwargs'].items(): + for _key, _val in _params["kwargs"].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method verify_not_present" % _key ) _params[_key] = _val - del _params['kwargs'] + del _params["kwargs"] _collection_formats = {} # process the path parameters _path_params = {} - if _params['name']: - _path_params['name'] = _params['name'] - + if _params["name"]: + _path_params["name"] = _params["name"] # process the query parameters _query_params = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) + _header_params = dict(_params.get("_headers", {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None - if _params['match_criteria'] is not None: - _body_params = _params['match_criteria'] + if _params["match_criteria"] is not None: + _body_params = _params["match_criteria"] # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + _header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) + _content_types_list = _params.get( + "_content_type", + self.api_client.select_header_content_type(["application/json"]), + ) if _content_types_list: - _header_params['Content-Type'] = _content_types_list + _header_params["Content-Type"] = _content_types_list # authentication setting _auth_settings = [] # noqa: E501 _response_types_map = { - '200': "VerifyResult", - '422': None, + "200": "VerifyResult", + "422": None, } return self.api_client.call_api( - '/verify/not_present/{name}', 'POST', + "/verify/not_present/{name}", + "POST", _path_params, _query_params, _header_params, @@ -1002,15 +1099,30 @@ def verify_not_present_with_http_info(self, name : Annotated[constr(strict=True) files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _request_auth=_params.get("_request_auth"), + ) @validate_arguments - def verify_present(self, name : Annotated[constr(strict=True), Field(..., description="The unique name for this verification operation")], match_criteria : Annotated[MatchCriteria, Field(..., description="Match criteria to select requests - response pairs for size tests")], **kwargs) -> VerifyResult: # noqa: E501 + def verify_present( + self, + name: Annotated[ + constr(strict=True), + Field(..., description="The unique name for this verification operation"), + ], + match_criteria: Annotated[ + MatchCriteria, + Field( + ..., + description="Match criteria to select requests - response pairs for size tests", + ), + ], + **kwargs, + ) -> VerifyResult: # noqa: E501 """verify_present # noqa: E501 Verify at least one matching item is present in the captured traffic # noqa: E501 @@ -1035,13 +1147,29 @@ def verify_present(self, name : Annotated[constr(strict=True), Field(..., descri returns the request thread. :rtype: VerifyResult """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the verify_present_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + raise ValueError( + "Error! Please call the verify_present_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" + ) return self.verify_present_with_http_info(name, match_criteria, **kwargs) # noqa: E501 @validate_arguments - def verify_present_with_http_info(self, name : Annotated[constr(strict=True), Field(..., description="The unique name for this verification operation")], match_criteria : Annotated[MatchCriteria, Field(..., description="Match criteria to select requests - response pairs for size tests")], **kwargs) -> ApiResponse: # noqa: E501 + def verify_present_with_http_info( + self, + name: Annotated[ + constr(strict=True), + Field(..., description="The unique name for this verification operation"), + ], + match_criteria: Annotated[ + MatchCriteria, + Field( + ..., + description="Match criteria to select requests - response pairs for size tests", + ), + ], + **kwargs, + ) -> ApiResponse: # noqa: E501 """verify_present # noqa: E501 Verify at least one matching item is present in the captured traffic # noqa: E501 @@ -1058,7 +1186,7 @@ def verify_present_with_http_info(self, name : Annotated[constr(strict=True), Fi :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the + be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional @@ -1082,73 +1210,72 @@ def verify_present_with_http_info(self, name : Annotated[constr(strict=True), Fi _params = locals() - _all_params = [ - 'name', - 'match_criteria' - ] + _all_params = ["name", "match_criteria"] _all_params.extend( [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", ] ) # validate the arguments - for _key, _val in _params['kwargs'].items(): + for _key, _val in _params["kwargs"].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method verify_present" % _key ) _params[_key] = _val - del _params['kwargs'] + del _params["kwargs"] _collection_formats = {} # process the path parameters _path_params = {} - if _params['name']: - _path_params['name'] = _params['name'] - + if _params["name"]: + _path_params["name"] = _params["name"] # process the query parameters _query_params = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) + _header_params = dict(_params.get("_headers", {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None - if _params['match_criteria'] is not None: - _body_params = _params['match_criteria'] + if _params["match_criteria"] is not None: + _body_params = _params["match_criteria"] # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + _header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) + _content_types_list = _params.get( + "_content_type", + self.api_client.select_header_content_type(["application/json"]), + ) if _content_types_list: - _header_params['Content-Type'] = _content_types_list + _header_params["Content-Type"] = _content_types_list # authentication setting _auth_settings = [] # noqa: E501 _response_types_map = { - '200': "VerifyResult", - '422': None, + "200": "VerifyResult", + "422": None, } return self.api_client.call_api( - '/verify/present/{name}', 'POST', + "/verify/present/{name}", + "POST", _path_params, _query_params, _header_params, @@ -1157,15 +1284,34 @@ def verify_present_with_http_info(self, name : Annotated[constr(strict=True), Fi files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _request_auth=_params.get("_request_auth"), + ) @validate_arguments - def verify_size(self, size : Annotated[conint(strict=True, ge=0), Field(..., description="The size used for comparison, in kilobytes")], name : Annotated[constr(strict=True), Field(..., description="The unique name for this verification operation")], match_criteria : Annotated[MatchCriteria, Field(..., description="Match criteria to select requests - response pairs for size tests")], **kwargs) -> VerifyResult: # noqa: E501 + def verify_size( + self, + size: Annotated[ + conint(strict=True, ge=0), + Field(..., description="The size used for comparison, in kilobytes"), + ], + name: Annotated[ + constr(strict=True), + Field(..., description="The unique name for this verification operation"), + ], + match_criteria: Annotated[ + MatchCriteria, + Field( + ..., + description="Match criteria to select requests - response pairs for size tests", + ), + ], + **kwargs, + ) -> VerifyResult: # noqa: E501 """verify_size # noqa: E501 Verify matching items in the captured traffic meet the size criteria # noqa: E501 @@ -1192,13 +1338,33 @@ def verify_size(self, size : Annotated[conint(strict=True, ge=0), Field(..., des returns the request thread. :rtype: VerifyResult """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the verify_size_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + raise ValueError( + "Error! Please call the verify_size_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" + ) return self.verify_size_with_http_info(size, name, match_criteria, **kwargs) # noqa: E501 @validate_arguments - def verify_size_with_http_info(self, size : Annotated[conint(strict=True, ge=0), Field(..., description="The size used for comparison, in kilobytes")], name : Annotated[constr(strict=True), Field(..., description="The unique name for this verification operation")], match_criteria : Annotated[MatchCriteria, Field(..., description="Match criteria to select requests - response pairs for size tests")], **kwargs) -> ApiResponse: # noqa: E501 + def verify_size_with_http_info( + self, + size: Annotated[ + conint(strict=True, ge=0), + Field(..., description="The size used for comparison, in kilobytes"), + ], + name: Annotated[ + constr(strict=True), + Field(..., description="The unique name for this verification operation"), + ], + match_criteria: Annotated[ + MatchCriteria, + Field( + ..., + description="Match criteria to select requests - response pairs for size tests", + ), + ], + **kwargs, + ) -> ApiResponse: # noqa: E501 """verify_size # noqa: E501 Verify matching items in the captured traffic meet the size criteria # noqa: E501 @@ -1217,7 +1383,7 @@ def verify_size_with_http_info(self, size : Annotated[conint(strict=True, ge=0), :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the + be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional @@ -1241,77 +1407,75 @@ def verify_size_with_http_info(self, size : Annotated[conint(strict=True, ge=0), _params = locals() - _all_params = [ - 'size', - 'name', - 'match_criteria' - ] + _all_params = ["size", "name", "match_criteria"] _all_params.extend( [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", ] ) # validate the arguments - for _key, _val in _params['kwargs'].items(): + for _key, _val in _params["kwargs"].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method verify_size" % _key ) _params[_key] = _val - del _params['kwargs'] + del _params["kwargs"] _collection_formats = {} # process the path parameters _path_params = {} - if _params['size']: - _path_params['size'] = _params['size'] - - if _params['name']: - _path_params['name'] = _params['name'] + if _params["size"]: + _path_params["size"] = _params["size"] + if _params["name"]: + _path_params["name"] = _params["name"] # process the query parameters _query_params = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) + _header_params = dict(_params.get("_headers", {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None - if _params['match_criteria'] is not None: - _body_params = _params['match_criteria'] + if _params["match_criteria"] is not None: + _body_params = _params["match_criteria"] # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + _header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) + _content_types_list = _params.get( + "_content_type", + self.api_client.select_header_content_type(["application/json"]), + ) if _content_types_list: - _header_params['Content-Type'] = _content_types_list + _header_params["Content-Type"] = _content_types_list # authentication setting _auth_settings = [] # noqa: E501 _response_types_map = { - '200': "VerifyResult", - '422': None, + "200": "VerifyResult", + "422": None, } return self.api_client.call_api( - '/verify/size/{size}/{name}', 'POST', + "/verify/size/{size}/{name}", + "POST", _path_params, _query_params, _header_params, @@ -1320,15 +1484,34 @@ def verify_size_with_http_info(self, size : Annotated[conint(strict=True, ge=0), files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _request_auth=_params.get("_request_auth"), + ) @validate_arguments - def verify_sla(self, time : Annotated[conint(strict=True, ge=0), Field(..., description="The time used for comparison")], name : Annotated[constr(strict=True), Field(..., description="The unique name for this verification operation")], match_criteria : Annotated[MatchCriteria, Field(..., description="Match criteria to select requests - response pairs for size tests")], **kwargs) -> VerifyResult: # noqa: E501 + def verify_sla( + self, + time: Annotated[ + conint(strict=True, ge=0), + Field(..., description="The time used for comparison"), + ], + name: Annotated[ + constr(strict=True), + Field(..., description="The unique name for this verification operation"), + ], + match_criteria: Annotated[ + MatchCriteria, + Field( + ..., + description="Match criteria to select requests - response pairs for size tests", + ), + ], + **kwargs, + ) -> VerifyResult: # noqa: E501 """verify_sla # noqa: E501 Verify each traffic item matching the criteria meets is below SLA time # noqa: E501 @@ -1355,13 +1538,33 @@ def verify_sla(self, time : Annotated[conint(strict=True, ge=0), Field(..., desc returns the request thread. :rtype: VerifyResult """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - raise ValueError("Error! Please call the verify_sla_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data") + kwargs["_return_http_data_only"] = True + if "_preload_content" in kwargs: + raise ValueError( + "Error! Please call the verify_sla_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" + ) return self.verify_sla_with_http_info(time, name, match_criteria, **kwargs) # noqa: E501 @validate_arguments - def verify_sla_with_http_info(self, time : Annotated[conint(strict=True, ge=0), Field(..., description="The time used for comparison")], name : Annotated[constr(strict=True), Field(..., description="The unique name for this verification operation")], match_criteria : Annotated[MatchCriteria, Field(..., description="Match criteria to select requests - response pairs for size tests")], **kwargs) -> ApiResponse: # noqa: E501 + def verify_sla_with_http_info( + self, + time: Annotated[ + conint(strict=True, ge=0), + Field(..., description="The time used for comparison"), + ], + name: Annotated[ + constr(strict=True), + Field(..., description="The unique name for this verification operation"), + ], + match_criteria: Annotated[ + MatchCriteria, + Field( + ..., + description="Match criteria to select requests - response pairs for size tests", + ), + ], + **kwargs, + ) -> ApiResponse: # noqa: E501 """verify_sla # noqa: E501 Verify each traffic item matching the criteria meets is below SLA time # noqa: E501 @@ -1380,7 +1583,7 @@ def verify_sla_with_http_info(self, time : Annotated[conint(strict=True, ge=0), :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the + be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional @@ -1404,77 +1607,75 @@ def verify_sla_with_http_info(self, time : Annotated[conint(strict=True, ge=0), _params = locals() - _all_params = [ - 'time', - 'name', - 'match_criteria' - ] + _all_params = ["time", "name", "match_criteria"] _all_params.extend( [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + "_request_auth", + "_content_type", + "_headers", ] ) # validate the arguments - for _key, _val in _params['kwargs'].items(): + for _key, _val in _params["kwargs"].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method verify_sla" % _key ) _params[_key] = _val - del _params['kwargs'] + del _params["kwargs"] _collection_formats = {} # process the path parameters _path_params = {} - if _params['time']: - _path_params['time'] = _params['time'] - - if _params['name']: - _path_params['name'] = _params['name'] + if _params["time"]: + _path_params["time"] = _params["time"] + if _params["name"]: + _path_params["name"] = _params["name"] # process the query parameters _query_params = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) + _header_params = dict(_params.get("_headers", {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None - if _params['match_criteria'] is not None: - _body_params = _params['match_criteria'] + if _params["match_criteria"] is not None: + _body_params = _params["match_criteria"] # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + _header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) + _content_types_list = _params.get( + "_content_type", + self.api_client.select_header_content_type(["application/json"]), + ) if _content_types_list: - _header_params['Content-Type'] = _content_types_list + _header_params["Content-Type"] = _content_types_list # authentication setting _auth_settings = [] # noqa: E501 _response_types_map = { - '200': "VerifyResult", - '422': None, + "200": "VerifyResult", + "422": None, } return self.api_client.call_api( - '/verify/sla/{time}/{name}', 'POST', + "/verify/sla/{time}/{name}", + "POST", _path_params, _query_params, _header_params, @@ -1483,9 +1684,10 @@ def verify_sla_with_http_info(self, time : Annotated[conint(strict=True, ge=0), files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), + async_req=_params.get("async_req"), + _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501 + _preload_content=_params.get("_preload_content", True), + _request_timeout=_params.get("_request_timeout"), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _request_auth=_params.get("_request_auth"), + ) diff --git a/clients/python/BrowserUpMitmProxyClient/api_client.py b/clients/python/BrowserUpMitmProxyClient/api_client.py index cfd519d8d5..c24e8b5026 100644 --- a/clients/python/BrowserUpMitmProxyClient/api_client.py +++ b/clients/python/BrowserUpMitmProxyClient/api_client.py @@ -1,35 +1,35 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import atexit import datetime -from dateutil.parser import parse import json import mimetypes -from multiprocessing.pool import ThreadPool import os import re import tempfile - +from multiprocessing.pool import ThreadPool from urllib.parse import quote -from BrowserUpMitmProxyClient.configuration import Configuration -from BrowserUpMitmProxyClient.api_response import ApiResponse +from dateutil.parser import parse + import BrowserUpMitmProxyClient.models from BrowserUpMitmProxyClient import rest -from BrowserUpMitmProxyClient.exceptions import ApiValueError, ApiException +from BrowserUpMitmProxyClient.api_response import ApiResponse +from BrowserUpMitmProxyClient.configuration import Configuration +from BrowserUpMitmProxyClient.exceptions import ApiException +from BrowserUpMitmProxyClient.exceptions import ApiValueError class ApiClient(object): @@ -52,19 +52,25 @@ class ApiClient(object): PRIMITIVE_TYPES = (float, bool, bytes, str, int) NATIVE_TYPES_MAPPING = { - 'int': int, - 'long': int, # TODO remove as only py3 is supported? - 'float': float, - 'str': str, - 'bool': bool, - 'date': datetime.date, - 'datetime': datetime.datetime, - 'object': object, + "int": int, + "long": int, # TODO remove as only py3 is supported? + "float": float, + "str": str, + "bool": bool, + "date": datetime.date, + "datetime": datetime.datetime, + "object": object, } _pool = None - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None, pool_threads=1): + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None, + pool_threads=1, + ): # use default configuration if none is provided if configuration is None: configuration = Configuration.get_default() @@ -77,7 +83,7 @@ def __init__(self, configuration=None, header_name=None, header_value=None, self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. - self.user_agent = 'OpenAPI-Generator/1.0.1/python' + self.user_agent = "OpenAPI-Generator/1.0.1/python" self.client_side_validation = configuration.client_side_validation def __enter__(self): @@ -91,13 +97,13 @@ def close(self): self._pool.close() self._pool.join() self._pool = None - if hasattr(atexit, 'unregister'): + if hasattr(atexit, "unregister"): atexit.unregister(self.close) @property def pool(self): """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. + avoids instantiating unused threadpool for blocking clients. """ if self._pool is None: atexit.register(self.close) @@ -107,16 +113,15 @@ def pool(self): @property def user_agent(self): """User agent for this API client""" - return self.default_headers['User-Agent'] + return self.default_headers["User-Agent"] @user_agent.setter def user_agent(self, value): - self.default_headers['User-Agent'] = value + self.default_headers["User-Agent"] = value def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value - _default = None @classmethod @@ -144,50 +149,64 @@ def set_default(cls, default): cls._default = default def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_types_map=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None, - _request_auth=None): - + self, + resource_path, + method, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, + response_types_map=None, + auth_settings=None, + _return_http_data_only=None, + collection_formats=None, + _preload_content=True, + _request_timeout=None, + _host=None, + _request_auth=None, + ): config = self.configuration # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: - header_params['Cookie'] = self.cookie + header_params["Cookie"] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) + header_params = dict( + self.parameters_to_tuples(header_params, collection_formats) + ) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) + path_params = self.parameters_to_tuples(path_params, collection_formats) for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( - '{%s}' % k, - quote(str(v), safe=config.safe_chars_for_path_param) + "{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param) ) # post parameters if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) + post_params = self.parameters_to_tuples(post_params, collection_formats) post_params.extend(self.files_parameters(files)) # auth setting self.update_params_for_auth( - header_params, query_params, auth_settings, - resource_path, method, body, - request_auth=_request_auth) + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth, + ) # body if body: @@ -203,56 +222,60 @@ def __call_api( # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, - collection_formats) + url_query = self.parameters_to_url_query(query_params, collection_formats) url += "?" + url_query try: # perform request and return response response_data = self.request( - method, url, + method, + url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, + post_params=post_params, + body=body, _preload_content=_preload_content, - _request_timeout=_request_timeout) + _request_timeout=_request_timeout, + ) except ApiException as e: if e.body: - e.body = e.body.decode('utf-8') + e.body = e.body.decode("utf-8") raise e self.last_response = response_data - return_data = None # assuming derialization is not needed + return_data = None # assuming derialization is not needed # data needs deserialization or returns HTTP data (deserialized) only if _preload_content or _return_http_data_only: - response_type = response_types_map.get(str(response_data.status), None) - - if response_type == "bytearray": - response_data.data = response_data.data - else: - match = None - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_data.data = response_data.data.decode(encoding) - - # deserialize response data - if response_type == "bytearray": - return_data = response_data.data - elif response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None + response_type = response_types_map.get(str(response_data.status), None) + + if response_type == "bytearray": + response_data.data = response_data.data + else: + match = None + content_type = response_data.getheader("content-type") + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_data.data = response_data.data.decode(encoding) + + # deserialize response data + if response_type == "bytearray": + return_data = response_data.data + elif response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None if _return_http_data_only: return return_data else: - return ApiResponse(status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data) + return ApiResponse( + status_code=response_data.status, + data=return_data, + headers=response_data.getheaders(), + raw_data=response_data.data, + ) def sanitize_for_serialization(self, obj): """Builds a JSON POST object. @@ -273,11 +296,9 @@ def sanitize_for_serialization(self, obj): elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] + return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) + return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() @@ -291,8 +312,9 @@ def sanitize_for_serialization(self, obj): # model definition for request. obj_dict = obj.to_dict() - return {key: self.sanitize_for_serialization(val) - for key, val in obj_dict.items()} + return { + key: self.sanitize_for_serialization(val) for key, val in obj_dict.items() + } def deserialize(self, response, response_type): """Deserializes response into an object. @@ -328,15 +350,13 @@ def __deserialize(self, data, klass): return None if type(klass) == str: - if klass.startswith('List['): - sub_kls = re.match(r'List\[(.*)]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) - for sub_data in data] + if klass.startswith("List["): + sub_kls = re.match(r"List\[(.*)]", klass).group(1) + return [self.__deserialize(sub_data, sub_kls) for sub_data in data] - if klass.startswith('Dict['): - sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) - return {k: self.__deserialize(v, sub_kls) - for k, v in data.items()} + if klass.startswith("Dict["): + sub_kls = re.match(r"Dict\[([^,]*), (.*)]", klass).group(2) + return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: @@ -355,13 +375,26 @@ def __deserialize(self, data, klass): else: return self.__deserialize_model(data, klass) - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_types_map=None, auth_settings=None, - async_req=None, _return_http_data_only=None, - collection_formats=None, _preload_content=True, - _request_timeout=None, _host=None, _request_auth=None): + def call_api( + self, + resource_path, + method, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, + response_types_map=None, + auth_settings=None, + async_req=None, + _return_http_data_only=None, + collection_formats=None, + _preload_content=True, + _request_timeout=None, + _host=None, + _request_auth=None, + ): """Makes the HTTP request (synchronous) and returns deserialized data. To make an async_req request, set the async_req parameter. @@ -404,80 +437,122 @@ def call_api(self, resource_path, method, then the method will return the response directly. """ if not async_req: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_types_map, auth_settings, - _return_http_data_only, collection_formats, - _preload_content, _request_timeout, _host, - _request_auth) - - return self.pool.apply_async(self.__call_api, (resource_path, - method, path_params, - query_params, - header_params, body, - post_params, files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, _request_auth)) - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): + return self.__call_api( + resource_path, + method, + path_params, + query_params, + header_params, + body, + post_params, + files, + response_types_map, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, + _request_auth, + ) + + return self.pool.apply_async( + self.__call_api, + ( + resource_path, + method, + path_params, + query_params, + header_params, + body, + post_params, + files, + response_types_map, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, + _request_auth, + ), + ) + + def request( + self, + method, + url, + query_params=None, + headers=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): """Makes the HTTP request using RESTClient.""" if method == "GET": - return self.rest_client.get_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) + return self.rest_client.get_request( + url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers, + ) elif method == "HEAD": - return self.rest_client.head_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) + return self.rest_client.head_request( + url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers, + ) elif method == "OPTIONS": - return self.rest_client.options_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + return self.rest_client.options_request( + url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + ) elif method == "POST": - return self.rest_client.post_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + return self.rest_client.post_request( + url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) elif method == "PUT": - return self.rest_client.put_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + return self.rest_client.put_request( + url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) elif method == "PATCH": - return self.rest_client.patch_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + return self.rest_client.patch_request( + url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) elif method == "DELETE": - return self.rest_client.delete_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + return self.rest_client.delete_request( + url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) else: raise ApiValueError( "http method must be `GET`, `HEAD`, `OPTIONS`," @@ -497,19 +572,18 @@ def parameters_to_tuples(self, params, collection_formats): for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] - if collection_format == 'multi': + if collection_format == "multi": new_params.extend((k, value) for value in v) else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' + if collection_format == "ssv": + delimiter = " " + elif collection_format == "tsv": + delimiter = "\t" + elif collection_format == "pipes": + delimiter = "|" else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(str(value) for value in v))) + delimiter = "," + new_params.append((k, delimiter.join(str(value) for value in v))) else: new_params.append((k, v)) return new_params @@ -534,19 +608,20 @@ def parameters_to_url_query(self, params, collection_formats): if k in collection_formats: collection_format = collection_formats[k] - if collection_format == 'multi': + if collection_format == "multi": new_params.extend((k, value) for value in v) else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' + if collection_format == "ssv": + delimiter = " " + elif collection_format == "tsv": + delimiter = "\t" + elif collection_format == "pipes": + delimiter = "|" else: # csv is the default - delimiter = ',' + delimiter = "," new_params.append( - (k, delimiter.join(quote(str(value)) for value in v))) + (k, delimiter.join(quote(str(value)) for value in v)) + ) else: new_params.append((k, quote(str(v)))) @@ -566,13 +641,14 @@ def files_parameters(self, files=None): continue file_names = v if type(v) is list else [v] for n in file_names: - with open(n, 'rb') as f: + with open(n, "rb") as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') - params.append( - tuple([k, tuple([filename, filedata, mimetype])])) + mimetype = ( + mimetypes.guess_type(filename)[0] + or "application/octet-stream" + ) + params.append(tuple([k, tuple([filename, filedata, mimetype])])) return params @@ -586,7 +662,7 @@ def select_header_accept(self, accepts): return for accept in accepts: - if re.search('json', accept, re.IGNORECASE): + if re.search("json", accept, re.IGNORECASE): return accept return accepts[0] @@ -601,14 +677,21 @@ def select_header_content_type(self, content_types): return None for content_type in content_types: - if re.search('json', content_type, re.IGNORECASE): + if re.search("json", content_type, re.IGNORECASE): return content_type return content_types[0] - def update_params_for_auth(self, headers, queries, auth_settings, - resource_path, method, body, - request_auth=None): + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None, + ): """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. @@ -625,21 +708,21 @@ def update_params_for_auth(self, headers, queries, auth_settings, return if request_auth: - self._apply_auth_params(headers, queries, - resource_path, method, body, - request_auth) + self._apply_auth_params( + headers, queries, resource_path, method, body, request_auth + ) return for auth in auth_settings: auth_setting = self.configuration.auth_settings().get(auth) if auth_setting: - self._apply_auth_params(headers, queries, - resource_path, method, body, - auth_setting) + self._apply_auth_params( + headers, queries, resource_path, method, body, auth_setting + ) - def _apply_auth_params(self, headers, queries, - resource_path, method, body, - auth_setting): + def _apply_auth_params( + self, headers, queries, resource_path, method, body, auth_setting + ): """Updates the request parameters based on a single auth_setting :param headers: Header parameters dict to be updated. @@ -650,17 +733,15 @@ def _apply_auth_params(self, headers, queries, The object type is the return value of sanitize_for_serialization(). :param auth_setting: auth settings for the endpoint """ - if auth_setting['in'] == 'cookie': - headers['Cookie'] = auth_setting['value'] - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - queries.append((auth_setting['key'], auth_setting['value'])) + if auth_setting["in"] == "cookie": + headers["Cookie"] = auth_setting["value"] + elif auth_setting["in"] == "header": + if auth_setting["type"] != "http-signature": + headers[auth_setting["key"]] = auth_setting["value"] + elif auth_setting["in"] == "query": + queries.append((auth_setting["key"], auth_setting["value"])) else: - raise ApiValueError( - 'Authentication token must be in `query` or `header`' - ) + raise ApiValueError("Authentication token must be in `query` or `header`") def __deserialize_file(self, response): """Deserializes body to file @@ -677,8 +758,9 @@ def __deserialize_file(self, response): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) + filename = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition + ).group(1) path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: @@ -720,8 +802,7 @@ def __deserialize_date(self, string): return string except ValueError: raise rest.ApiException( - status=0, - reason="Failed to parse `{0}` as date object".format(string) + status=0, reason="Failed to parse `{0}` as date object".format(string) ) def __deserialize_datetime(self, string): @@ -739,10 +820,7 @@ def __deserialize_datetime(self, string): except ValueError: raise rest.ApiException( status=0, - reason=( - "Failed to parse `{0}` as datetime object" - .format(string) - ) + reason=("Failed to parse `{0}` as datetime object".format(string)), ) def __deserialize_model(self, data, klass): diff --git a/clients/python/BrowserUpMitmProxyClient/api_response.py b/clients/python/BrowserUpMitmProxyClient/api_response.py index d81c2ff584..d72c9280e5 100644 --- a/clients/python/BrowserUpMitmProxyClient/api_response.py +++ b/clients/python/BrowserUpMitmProxyClient/api_response.py @@ -1,8 +1,15 @@ """API response object.""" from __future__ import annotations -from typing import Any, Dict, Optional -from pydantic import Field, StrictInt, StrictStr + +from typing import Any +from typing import Dict +from typing import Optional + +from pydantic import Field +from pydantic import StrictInt +from pydantic import StrictStr + class ApiResponse: """ @@ -10,15 +17,15 @@ class ApiResponse: """ status_code: Optional[StrictInt] = Field(None, description="HTTP status code") - headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") - data: Optional[Any] = Field(None, description="Deserialized data given the data type") + headers: Optional[Dict[StrictStr, StrictStr]] = Field( + None, description="HTTP headers" + ) + data: Optional[Any] = Field( + None, description="Deserialized data given the data type" + ) raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") - def __init__(self, - status_code=None, - headers=None, - data=None, - raw_data=None): + def __init__(self, status_code=None, headers=None, data=None, raw_data=None): self.status_code = status_code self.headers = headers self.data = data diff --git a/clients/python/BrowserUpMitmProxyClient/configuration.py b/clients/python/BrowserUpMitmProxyClient/configuration.py index a131880e7f..b2f6bbb288 100644 --- a/clients/python/BrowserUpMitmProxyClient/configuration.py +++ b/clients/python/BrowserUpMitmProxyClient/configuration.py @@ -1,33 +1,39 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import copy +import http.client as httplib import logging import multiprocessing import sys -import urllib3 -import http.client as httplib -from BrowserUpMitmProxyClient.exceptions import ApiValueError +import urllib3 JSON_SCHEMA_VALIDATION_KEYWORDS = { - 'multipleOf', 'maximum', 'exclusiveMaximum', - 'minimum', 'exclusiveMinimum', 'maxLength', - 'minLength', 'pattern', 'maxItems', 'minItems' + "multipleOf", + "maximum", + "exclusiveMaximum", + "minimum", + "exclusiveMinimum", + "maxLength", + "minLength", + "pattern", + "maxItems", + "minItems", } + class Configuration(object): """This class contains various settings of the API client. @@ -58,16 +64,21 @@ class Configuration(object): _default = None - def __init__(self, host=None, - api_key=None, api_key_prefix=None, - username=None, password=None, - access_token=None, - server_index=None, server_variables=None, - server_operation_index=None, server_operation_variables=None, - ssl_ca_cert=None, - ): - """Constructor - """ + def __init__( + self, + host=None, + api_key=None, + api_key_prefix=None, + username=None, + password=None, + access_token=None, + server_index=None, + server_variables=None, + server_operation_index=None, + server_operation_variables=None, + ssl_ca_cert=None, + ): + """Constructor""" self._base_path = "http://localhost:48088" if host is None else host """Default Base url """ @@ -110,7 +121,7 @@ def __init__(self, host=None, """ self.logger["package_logger"] = logging.getLogger("BrowserUpMitmProxyClient") self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = '%(asctime)s %(levelname)s %(message)s' + self.logger_format = "%(asctime)s %(levelname)s %(message)s" """Log format """ self.logger_stream_handler = None @@ -162,7 +173,7 @@ def __init__(self, host=None, self.proxy_headers = None """Proxy headers """ - self.safe_chars_for_path_param = '' + self.safe_chars_for_path_param = "" """Safe chars for path_param """ self.retries = None @@ -188,7 +199,7 @@ def __deepcopy__(self, memo): result = cls.__new__(cls) memo[id(self)] = result for k, v in self.__dict__.items(): - if k not in ('logger', 'logger_file_handler'): + if k not in ("logger", "logger_file_handler"): setattr(result, k, copy.deepcopy(v, memo)) # shallow copy of loggers result.logger = copy.copy(self.logger) @@ -329,7 +340,9 @@ def get_api_key_with_prefix(self, identifier, alias=None): """ if self.refresh_api_key_hook is not None: self.refresh_api_key_hook(self) - key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + key = self.api_key.get( + identifier, self.api_key.get(alias) if alias is not None else None + ) if key: prefix = self.api_key_prefix.get(identifier) if prefix: @@ -348,9 +361,9 @@ def get_basic_auth_token(self): password = "" if self.password is not None: password = self.password - return urllib3.util.make_headers( - basic_auth=username + ':' + password - ).get('authorization') + return urllib3.util.make_headers(basic_auth=username + ":" + password).get( + "authorization" + ) def auth_settings(self): """Gets Auth Settings dict for api client. @@ -365,12 +378,13 @@ def to_debug_report(self): :return: The report for debugging. """ - return "Python SDK Debug Report:\n"\ - "OS: {env}\n"\ - "Python Version: {pyversion}\n"\ - "Version of the API: 1.0.0\n"\ - "SDK Package Version: 1.0.1".\ - format(env=sys.platform, pyversion=sys.version) + return ( + "Python SDK Debug Report:\n" + "OS: {env}\n" + "Python Version: {pyversion}\n" + "Version of the API: 1.0.0\n" + "SDK Package Version: 1.0.1".format(env=sys.platform, pyversion=sys.version) + ) def get_host_settings(self): """Gets an array of host settings @@ -379,17 +393,15 @@ def get_host_settings(self): """ return [ { - 'url': "http://localhost:{port}", - 'description': "The development API server", - 'variables': { - 'port': { - 'description': "No description provided", - 'default_value': "48088", - 'enum_values': [ - "48088" - ] - } + "url": "http://localhost:{port}", + "description": "The development API server", + "variables": { + "port": { + "description": "No description provided", + "default_value": "48088", + "enum_values": ["48088"], } + }, } ] @@ -411,22 +423,22 @@ def get_host_from_settings(self, index, variables=None, servers=None): except IndexError: raise ValueError( "Invalid index {0} when selecting the host settings. " - "Must be less than {1}".format(index, len(servers))) + "Must be less than {1}".format(index, len(servers)) + ) - url = server['url'] + url = server["url"] # go through variables and replace placeholders - for variable_name, variable in server.get('variables', {}).items(): - used_value = variables.get( - variable_name, variable['default_value']) + for variable_name, variable in server.get("variables", {}).items(): + used_value = variables.get(variable_name, variable["default_value"]) - if 'enum_values' in variable \ - and used_value not in variable['enum_values']: + if "enum_values" in variable and used_value not in variable["enum_values"]: raise ValueError( "The variable `{0}` in the host URL has invalid value " "{1}. Must be {2}.".format( - variable_name, variables[variable_name], - variable['enum_values'])) + variable_name, variables[variable_name], variable["enum_values"] + ) + ) url = url.replace("{" + variable_name + "}", used_value) @@ -435,7 +447,9 @@ def get_host_from_settings(self, index, variables=None, servers=None): @property def host(self): """Return generated host.""" - return self.get_host_from_settings(self.server_index, variables=self.server_variables) + return self.get_host_from_settings( + self.server_index, variables=self.server_variables + ) @host.setter def host(self, value): diff --git a/clients/python/BrowserUpMitmProxyClient/exceptions.py b/clients/python/BrowserUpMitmProxyClient/exceptions.py index 8c2d7b4f29..34d2bcffeb 100644 --- a/clients/python/BrowserUpMitmProxyClient/exceptions.py +++ b/clients/python/BrowserUpMitmProxyClient/exceptions.py @@ -1,15 +1,15 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 @@ -18,9 +18,8 @@ class OpenApiException(Exception): class ApiTypeError(OpenApiException, TypeError): - def __init__(self, msg, path_to_item=None, valid_classes=None, - key_type=None): - """ Raises an exception for TypeErrors + def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None): + """Raises an exception for TypeErrors Args: msg (str): the exception message @@ -101,7 +100,6 @@ def __init__(self, msg, path_to_item=None): class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, http_resp=None): if http_resp: self.status = http_resp.status @@ -116,42 +114,37 @@ def __init__(self, status=None, reason=None, http_resp=None): def __str__(self): """Custom error messages for exception""" - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) + error_message = "({0})\n" "Reason: {1}\n".format(self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}\n".format( - self.headers) + error_message += "HTTP response headers: {0}\n".format(self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) return error_message -class BadRequestException(ApiException): +class BadRequestException(ApiException): def __init__(self, status=None, reason=None, http_resp=None): super(BadRequestException, self).__init__(status, reason, http_resp) -class NotFoundException(ApiException): +class NotFoundException(ApiException): def __init__(self, status=None, reason=None, http_resp=None): super(NotFoundException, self).__init__(status, reason, http_resp) class UnauthorizedException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None): super(UnauthorizedException, self).__init__(status, reason, http_resp) class ForbiddenException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None): super(ForbiddenException, self).__init__(status, reason, http_resp) class ServiceException(ApiException): - def __init__(self, status=None, reason=None, http_resp=None): super(ServiceException, self).__init__(status, reason, http_resp) diff --git a/clients/python/BrowserUpMitmProxyClient/models/__init__.py b/clients/python/BrowserUpMitmProxyClient/models/__init__.py index eeb9d401ec..cc1f99f0a6 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/__init__.py +++ b/clients/python/BrowserUpMitmProxyClient/models/__init__.py @@ -2,18 +2,17 @@ # flake8: noqa """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - # import models into model package from BrowserUpMitmProxyClient.models.action import Action from BrowserUpMitmProxyClient.models.counter import Counter @@ -21,19 +20,33 @@ from BrowserUpMitmProxyClient.models.har import Har from BrowserUpMitmProxyClient.models.har_entry import HarEntry from BrowserUpMitmProxyClient.models.har_entry_cache import HarEntryCache -from BrowserUpMitmProxyClient.models.har_entry_cache_before_request import HarEntryCacheBeforeRequest +from BrowserUpMitmProxyClient.models.har_entry_cache_before_request import ( + HarEntryCacheBeforeRequest, +) from BrowserUpMitmProxyClient.models.har_entry_request import HarEntryRequest -from BrowserUpMitmProxyClient.models.har_entry_request_cookies_inner import HarEntryRequestCookiesInner -from BrowserUpMitmProxyClient.models.har_entry_request_post_data import HarEntryRequestPostData -from BrowserUpMitmProxyClient.models.har_entry_request_post_data_params_inner import HarEntryRequestPostDataParamsInner -from BrowserUpMitmProxyClient.models.har_entry_request_query_string_inner import HarEntryRequestQueryStringInner +from BrowserUpMitmProxyClient.models.har_entry_request_cookies_inner import ( + HarEntryRequestCookiesInner, +) +from BrowserUpMitmProxyClient.models.har_entry_request_post_data import ( + HarEntryRequestPostData, +) +from BrowserUpMitmProxyClient.models.har_entry_request_post_data_params_inner import ( + HarEntryRequestPostDataParamsInner, +) +from BrowserUpMitmProxyClient.models.har_entry_request_query_string_inner import ( + HarEntryRequestQueryStringInner, +) from BrowserUpMitmProxyClient.models.har_entry_response import HarEntryResponse -from BrowserUpMitmProxyClient.models.har_entry_response_content import HarEntryResponseContent +from BrowserUpMitmProxyClient.models.har_entry_response_content import ( + HarEntryResponseContent, +) from BrowserUpMitmProxyClient.models.har_entry_timings import HarEntryTimings from BrowserUpMitmProxyClient.models.har_log import HarLog from BrowserUpMitmProxyClient.models.har_log_creator import HarLogCreator from BrowserUpMitmProxyClient.models.header import Header -from BrowserUpMitmProxyClient.models.largest_contentful_paint import LargestContentfulPaint +from BrowserUpMitmProxyClient.models.largest_contentful_paint import ( + LargestContentfulPaint, +) from BrowserUpMitmProxyClient.models.match_criteria import MatchCriteria from BrowserUpMitmProxyClient.models.name_value_pair import NameValuePair from BrowserUpMitmProxyClient.models.page import Page diff --git a/clients/python/BrowserUpMitmProxyClient/models/action.py b/clients/python/BrowserUpMitmProxyClient/models/action.py index 5b88f2d383..b10d5b2d25 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/action.py +++ b/clients/python/BrowserUpMitmProxyClient/models/action.py @@ -1,31 +1,34 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictStr class Action(BaseModel): """ Action """ + name: Optional[StrictStr] = None id: Optional[StrictStr] = None class_name: Optional[StrictStr] = Field(None, alias="className") @@ -34,10 +37,20 @@ class Action(BaseModel): data_attributes: Optional[StrictStr] = Field(None, alias="dataAttributes") form_name: Optional[StrictStr] = Field(None, alias="formName") content: Optional[StrictStr] = None - __properties = ["name", "id", "className", "tagName", "xpath", "dataAttributes", "formName", "content"] + __properties = [ + "name", + "id", + "className", + "tagName", + "xpath", + "dataAttributes", + "formName", + "content", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -56,10 +69,7 @@ def from_json(cls, json_str: str) -> Action: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -71,16 +81,16 @@ def from_dict(cls, obj: dict) -> Action: if not isinstance(obj, dict): return Action.parse_obj(obj) - _obj = Action.parse_obj({ - "name": obj.get("name"), - "id": obj.get("id"), - "class_name": obj.get("className"), - "tag_name": obj.get("tagName"), - "xpath": obj.get("xpath"), - "data_attributes": obj.get("dataAttributes"), - "form_name": obj.get("formName"), - "content": obj.get("content") - }) + _obj = Action.parse_obj( + { + "name": obj.get("name"), + "id": obj.get("id"), + "class_name": obj.get("className"), + "tag_name": obj.get("tagName"), + "xpath": obj.get("xpath"), + "data_attributes": obj.get("dataAttributes"), + "form_name": obj.get("formName"), + "content": obj.get("content"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/counter.py b/clients/python/BrowserUpMitmProxyClient/models/counter.py index 7e80d7d0db..814263692b 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/counter.py +++ b/clients/python/BrowserUpMitmProxyClient/models/counter.py @@ -1,37 +1,48 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from typing import Union +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictFloat +from pydantic import StrictInt +from pydantic import StrictStr -from typing import Optional, Union -from pydantic import BaseModel, Field, StrictFloat, StrictInt, StrictStr class Counter(BaseModel): """ Counter """ - name: Optional[StrictStr] = Field(None, description="Name of Custom Counter to add to the page under _counters") - value: Optional[Union[StrictFloat, StrictInt]] = Field(None, description="Value for the counter") + + name: Optional[StrictStr] = Field( + None, description="Name of Custom Counter to add to the page under _counters" + ) + value: Optional[Union[StrictFloat, StrictInt]] = Field( + None, description="Value for the counter" + ) __properties = ["name", "value"] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -50,10 +61,7 @@ def from_json(cls, json_str: str) -> Counter: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -65,10 +73,5 @@ def from_dict(cls, obj: dict) -> Counter: if not isinstance(obj, dict): return Counter.parse_obj(obj) - _obj = Counter.parse_obj({ - "name": obj.get("name"), - "value": obj.get("value") - }) + _obj = Counter.parse_obj({"name": obj.get("name"), "value": obj.get("value")}) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/error.py b/clients/python/BrowserUpMitmProxyClient/models/error.py index 383abc440e..c08609a5e9 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/error.py +++ b/clients/python/BrowserUpMitmProxyClient/models/error.py @@ -1,37 +1,43 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictStr class Error(BaseModel): """ Error """ - name: Optional[StrictStr] = Field(None, description="Name of the Error to add. Stored in har under _errors") + + name: Optional[StrictStr] = Field( + None, description="Name of the Error to add. Stored in har under _errors" + ) details: Optional[StrictStr] = Field(None, description="Short details of the error") __properties = ["name", "details"] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -50,10 +56,7 @@ def from_json(cls, json_str: str) -> Error: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -65,10 +68,5 @@ def from_dict(cls, obj: dict) -> Error: if not isinstance(obj, dict): return Error.parse_obj(obj) - _obj = Error.parse_obj({ - "name": obj.get("name"), - "details": obj.get("details") - }) + _obj = Error.parse_obj({"name": obj.get("name"), "details": obj.get("details")}) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har.py b/clients/python/BrowserUpMitmProxyClient/models/har.py index 7621eba902..12a12f2e3a 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har.py @@ -1,38 +1,41 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json - +from pydantic import BaseModel +from pydantic import Field -from pydantic import BaseModel, Field from BrowserUpMitmProxyClient.models.har_log import HarLog + class Har(BaseModel): """ Har """ + log: HarLog = Field(...) additional_properties: Dict[str, Any] = {} __properties = ["log"] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -51,14 +54,12 @@ def from_json(cls, json_str: str) -> Har: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - "additional_properties" - }, - exclude_none=True) + _dict = self.dict( + by_alias=True, exclude={"additional_properties"}, exclude_none=True + ) # override the default output from pydantic by calling `to_dict()` of log if self.log: - _dict['log'] = self.log.to_dict() + _dict["log"] = self.log.to_dict() # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -75,14 +76,16 @@ def from_dict(cls, obj: dict) -> Har: if not isinstance(obj, dict): return Har.parse_obj(obj) - _obj = Har.parse_obj({ - "log": HarLog.from_dict(obj.get("log")) if obj.get("log") is not None else None - }) + _obj = Har.parse_obj( + { + "log": HarLog.from_dict(obj.get("log")) + if obj.get("log") is not None + else None + } + ) # store additional fields in additional_properties for _key in obj.keys(): if _key not in cls.__properties: _obj.additional_properties[_key] = obj.get(_key) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry.py index cddc52f8b2..40f8a97b16 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry.py @@ -1,36 +1,43 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json - from datetime import datetime -from typing import List, Optional -from pydantic import BaseModel, Field, StrictStr, conint, conlist +from typing import Optional + +from pydantic import BaseModel +from pydantic import conint +from pydantic import conlist +from pydantic import Field +from pydantic import StrictStr + from BrowserUpMitmProxyClient.models.har_entry_cache import HarEntryCache from BrowserUpMitmProxyClient.models.har_entry_request import HarEntryRequest from BrowserUpMitmProxyClient.models.har_entry_response import HarEntryResponse from BrowserUpMitmProxyClient.models.har_entry_timings import HarEntryTimings from BrowserUpMitmProxyClient.models.web_socket_message import WebSocketMessage + class HarEntry(BaseModel): """ HarEntry """ + pageref: Optional[StrictStr] = None started_date_time: datetime = Field(..., alias="startedDateTime") time: conint(strict=True, ge=0) = Field(...) @@ -39,13 +46,28 @@ class HarEntry(BaseModel): cache: HarEntryCache = Field(...) timings: HarEntryTimings = Field(...) server_ip_address: Optional[StrictStr] = Field(None, alias="serverIPAddress") - web_socket_messages: Optional[conlist(WebSocketMessage)] = Field(None, alias="_webSocketMessages") + web_socket_messages: Optional[conlist(WebSocketMessage)] = Field( + None, alias="_webSocketMessages" + ) connection: Optional[StrictStr] = None comment: Optional[StrictStr] = None - __properties = ["pageref", "startedDateTime", "time", "request", "response", "cache", "timings", "serverIPAddress", "_webSocketMessages", "connection", "comment"] + __properties = [ + "pageref", + "startedDateTime", + "time", + "request", + "response", + "cache", + "timings", + "serverIPAddress", + "_webSocketMessages", + "connection", + "comment", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -64,29 +86,26 @@ def from_json(cls, json_str: str) -> HarEntry: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) # override the default output from pydantic by calling `to_dict()` of request if self.request: - _dict['request'] = self.request.to_dict() + _dict["request"] = self.request.to_dict() # override the default output from pydantic by calling `to_dict()` of response if self.response: - _dict['response'] = self.response.to_dict() + _dict["response"] = self.response.to_dict() # override the default output from pydantic by calling `to_dict()` of cache if self.cache: - _dict['cache'] = self.cache.to_dict() + _dict["cache"] = self.cache.to_dict() # override the default output from pydantic by calling `to_dict()` of timings if self.timings: - _dict['timings'] = self.timings.to_dict() + _dict["timings"] = self.timings.to_dict() # override the default output from pydantic by calling `to_dict()` of each item in web_socket_messages (list) _items = [] if self.web_socket_messages: for _item in self.web_socket_messages: if _item: _items.append(_item.to_dict()) - _dict['_webSocketMessages'] = _items + _dict["_webSocketMessages"] = _items return _dict @classmethod @@ -98,19 +117,32 @@ def from_dict(cls, obj: dict) -> HarEntry: if not isinstance(obj, dict): return HarEntry.parse_obj(obj) - _obj = HarEntry.parse_obj({ - "pageref": obj.get("pageref"), - "started_date_time": obj.get("startedDateTime"), - "time": obj.get("time"), - "request": HarEntryRequest.from_dict(obj.get("request")) if obj.get("request") is not None else None, - "response": HarEntryResponse.from_dict(obj.get("response")) if obj.get("response") is not None else None, - "cache": HarEntryCache.from_dict(obj.get("cache")) if obj.get("cache") is not None else None, - "timings": HarEntryTimings.from_dict(obj.get("timings")) if obj.get("timings") is not None else None, - "server_ip_address": obj.get("serverIPAddress"), - "web_socket_messages": [WebSocketMessage.from_dict(_item) for _item in obj.get("_webSocketMessages")] if obj.get("_webSocketMessages") is not None else None, - "connection": obj.get("connection"), - "comment": obj.get("comment") - }) + _obj = HarEntry.parse_obj( + { + "pageref": obj.get("pageref"), + "started_date_time": obj.get("startedDateTime"), + "time": obj.get("time"), + "request": HarEntryRequest.from_dict(obj.get("request")) + if obj.get("request") is not None + else None, + "response": HarEntryResponse.from_dict(obj.get("response")) + if obj.get("response") is not None + else None, + "cache": HarEntryCache.from_dict(obj.get("cache")) + if obj.get("cache") is not None + else None, + "timings": HarEntryTimings.from_dict(obj.get("timings")) + if obj.get("timings") is not None + else None, + "server_ip_address": obj.get("serverIPAddress"), + "web_socket_messages": [ + WebSocketMessage.from_dict(_item) + for _item in obj.get("_webSocketMessages") + ] + if obj.get("_webSocketMessages") is not None + else None, + "connection": obj.get("connection"), + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_cache.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_cache.py index 89a1ff4e8d..a2373718c4 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_cache.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_cache.py @@ -1,39 +1,50 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictStr + +from BrowserUpMitmProxyClient.models.har_entry_cache_before_request import ( + HarEntryCacheBeforeRequest, +) -from typing import Optional -from pydantic import BaseModel, Field, StrictStr -from BrowserUpMitmProxyClient.models.har_entry_cache_before_request import HarEntryCacheBeforeRequest class HarEntryCache(BaseModel): """ HarEntryCache """ - before_request: Optional[HarEntryCacheBeforeRequest] = Field(None, alias="beforeRequest") - after_request: Optional[HarEntryCacheBeforeRequest] = Field(None, alias="afterRequest") + + before_request: Optional[HarEntryCacheBeforeRequest] = Field( + None, alias="beforeRequest" + ) + after_request: Optional[HarEntryCacheBeforeRequest] = Field( + None, alias="afterRequest" + ) comment: Optional[StrictStr] = None __properties = ["beforeRequest", "afterRequest", "comment"] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -52,25 +63,22 @@ def from_json(cls, json_str: str) -> HarEntryCache: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) # override the default output from pydantic by calling `to_dict()` of before_request if self.before_request: - _dict['beforeRequest'] = self.before_request.to_dict() + _dict["beforeRequest"] = self.before_request.to_dict() # override the default output from pydantic by calling `to_dict()` of after_request if self.after_request: - _dict['afterRequest'] = self.after_request.to_dict() + _dict["afterRequest"] = self.after_request.to_dict() # set to None if before_request (nullable) is None # and __fields_set__ contains the field if self.before_request is None and "before_request" in self.__fields_set__: - _dict['beforeRequest'] = None + _dict["beforeRequest"] = None # set to None if after_request (nullable) is None # and __fields_set__ contains the field if self.after_request is None and "after_request" in self.__fields_set__: - _dict['afterRequest'] = None + _dict["afterRequest"] = None return _dict @@ -83,11 +91,19 @@ def from_dict(cls, obj: dict) -> HarEntryCache: if not isinstance(obj, dict): return HarEntryCache.parse_obj(obj) - _obj = HarEntryCache.parse_obj({ - "before_request": HarEntryCacheBeforeRequest.from_dict(obj.get("beforeRequest")) if obj.get("beforeRequest") is not None else None, - "after_request": HarEntryCacheBeforeRequest.from_dict(obj.get("afterRequest")) if obj.get("afterRequest") is not None else None, - "comment": obj.get("comment") - }) + _obj = HarEntryCache.parse_obj( + { + "before_request": HarEntryCacheBeforeRequest.from_dict( + obj.get("beforeRequest") + ) + if obj.get("beforeRequest") is not None + else None, + "after_request": HarEntryCacheBeforeRequest.from_dict( + obj.get("afterRequest") + ) + if obj.get("afterRequest") is not None + else None, + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_cache_before_request.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_cache_before_request.py index 78101c63b0..5d8aadd739 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_cache_before_request.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_cache_before_request.py @@ -1,31 +1,35 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictInt +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictInt, StrictStr class HarEntryCacheBeforeRequest(BaseModel): """ HarEntryCacheBeforeRequest """ + expires: Optional[StrictStr] = None last_access: StrictStr = Field(..., alias="lastAccess") e_tag: StrictStr = Field(..., alias="eTag") @@ -35,6 +39,7 @@ class HarEntryCacheBeforeRequest(BaseModel): class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -53,10 +58,7 @@ def from_json(cls, json_str: str) -> HarEntryCacheBeforeRequest: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -68,13 +70,13 @@ def from_dict(cls, obj: dict) -> HarEntryCacheBeforeRequest: if not isinstance(obj, dict): return HarEntryCacheBeforeRequest.parse_obj(obj) - _obj = HarEntryCacheBeforeRequest.parse_obj({ - "expires": obj.get("expires"), - "last_access": obj.get("lastAccess"), - "e_tag": obj.get("eTag"), - "hit_count": obj.get("hitCount"), - "comment": obj.get("comment") - }) + _obj = HarEntryCacheBeforeRequest.parse_obj( + { + "expires": obj.get("expires"), + "last_access": obj.get("lastAccess"), + "e_tag": obj.get("eTag"), + "hit_count": obj.get("hitCount"), + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py index 916645042a..5344079c3e 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py @@ -1,50 +1,76 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import BaseModel, Field, StrictInt, StrictStr, conlist -from BrowserUpMitmProxyClient.models.har_entry_request_cookies_inner import HarEntryRequestCookiesInner -from BrowserUpMitmProxyClient.models.har_entry_request_post_data import HarEntryRequestPostData -from BrowserUpMitmProxyClient.models.har_entry_request_query_string_inner import HarEntryRequestQueryStringInner +from typing import Optional + +from pydantic import BaseModel +from pydantic import conlist +from pydantic import Field +from pydantic import StrictInt +from pydantic import StrictStr + +from BrowserUpMitmProxyClient.models.har_entry_request_cookies_inner import ( + HarEntryRequestCookiesInner, +) +from BrowserUpMitmProxyClient.models.har_entry_request_post_data import ( + HarEntryRequestPostData, +) +from BrowserUpMitmProxyClient.models.har_entry_request_query_string_inner import ( + HarEntryRequestQueryStringInner, +) from BrowserUpMitmProxyClient.models.header import Header + class HarEntryRequest(BaseModel): """ HarEntryRequest """ + method: StrictStr = Field(...) url: StrictStr = Field(...) http_version: StrictStr = Field(..., alias="httpVersion") cookies: conlist(HarEntryRequestCookiesInner) = Field(...) headers: conlist(Header) = Field(...) - query_string: conlist(HarEntryRequestQueryStringInner) = Field(..., alias="queryString") + query_string: conlist(HarEntryRequestQueryStringInner) = Field( + ..., alias="queryString" + ) post_data: Optional[HarEntryRequestPostData] = Field(None, alias="postData") headers_size: StrictInt = Field(..., alias="headersSize") body_size: StrictInt = Field(..., alias="bodySize") comment: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} - __properties = ["method", "url", "httpVersion", "cookies", "headers", "queryString", "postData", "headersSize", "bodySize", "comment"] + __properties = [ + "method", + "url", + "httpVersion", + "cookies", + "headers", + "queryString", + "postData", + "headersSize", + "bodySize", + "comment", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -63,35 +89,33 @@ def from_json(cls, json_str: str) -> HarEntryRequest: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - "additional_properties" - }, - exclude_none=True) + _dict = self.dict( + by_alias=True, exclude={"additional_properties"}, exclude_none=True + ) # override the default output from pydantic by calling `to_dict()` of each item in cookies (list) _items = [] if self.cookies: for _item in self.cookies: if _item: _items.append(_item.to_dict()) - _dict['cookies'] = _items + _dict["cookies"] = _items # override the default output from pydantic by calling `to_dict()` of each item in headers (list) _items = [] if self.headers: for _item in self.headers: if _item: _items.append(_item.to_dict()) - _dict['headers'] = _items + _dict["headers"] = _items # override the default output from pydantic by calling `to_dict()` of each item in query_string (list) _items = [] if self.query_string: for _item in self.query_string: if _item: _items.append(_item.to_dict()) - _dict['queryString'] = _items + _dict["queryString"] = _items # override the default output from pydantic by calling `to_dict()` of post_data if self.post_data: - _dict['postData'] = self.post_data.to_dict() + _dict["postData"] = self.post_data.to_dict() # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -108,23 +132,37 @@ def from_dict(cls, obj: dict) -> HarEntryRequest: if not isinstance(obj, dict): return HarEntryRequest.parse_obj(obj) - _obj = HarEntryRequest.parse_obj({ - "method": obj.get("method"), - "url": obj.get("url"), - "http_version": obj.get("httpVersion"), - "cookies": [HarEntryRequestCookiesInner.from_dict(_item) for _item in obj.get("cookies")] if obj.get("cookies") is not None else None, - "headers": [Header.from_dict(_item) for _item in obj.get("headers")] if obj.get("headers") is not None else None, - "query_string": [HarEntryRequestQueryStringInner.from_dict(_item) for _item in obj.get("queryString")] if obj.get("queryString") is not None else None, - "post_data": HarEntryRequestPostData.from_dict(obj.get("postData")) if obj.get("postData") is not None else None, - "headers_size": obj.get("headersSize"), - "body_size": obj.get("bodySize"), - "comment": obj.get("comment") - }) + _obj = HarEntryRequest.parse_obj( + { + "method": obj.get("method"), + "url": obj.get("url"), + "http_version": obj.get("httpVersion"), + "cookies": [ + HarEntryRequestCookiesInner.from_dict(_item) + for _item in obj.get("cookies") + ] + if obj.get("cookies") is not None + else None, + "headers": [Header.from_dict(_item) for _item in obj.get("headers")] + if obj.get("headers") is not None + else None, + "query_string": [ + HarEntryRequestQueryStringInner.from_dict(_item) + for _item in obj.get("queryString") + ] + if obj.get("queryString") is not None + else None, + "post_data": HarEntryRequestPostData.from_dict(obj.get("postData")) + if obj.get("postData") is not None + else None, + "headers_size": obj.get("headersSize"), + "body_size": obj.get("bodySize"), + "comment": obj.get("comment"), + } + ) # store additional fields in additional_properties for _key in obj.keys(): if _key not in cls.__properties: _obj.additional_properties[_key] = obj.get(_key) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_cookies_inner.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_cookies_inner.py index 6e05884120..fcb92f79f6 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_cookies_inner.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_cookies_inner.py @@ -1,31 +1,35 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictBool +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictBool, StrictStr class HarEntryRequestCookiesInner(BaseModel): """ HarEntryRequestCookiesInner """ + name: StrictStr = Field(...) value: StrictStr = Field(...) path: Optional[StrictStr] = None @@ -34,10 +38,20 @@ class HarEntryRequestCookiesInner(BaseModel): http_only: Optional[StrictBool] = Field(None, alias="httpOnly") secure: Optional[StrictBool] = None comment: Optional[StrictStr] = None - __properties = ["name", "value", "path", "domain", "expires", "httpOnly", "secure", "comment"] + __properties = [ + "name", + "value", + "path", + "domain", + "expires", + "httpOnly", + "secure", + "comment", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -56,10 +70,7 @@ def from_json(cls, json_str: str) -> HarEntryRequestCookiesInner: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -71,16 +82,16 @@ def from_dict(cls, obj: dict) -> HarEntryRequestCookiesInner: if not isinstance(obj, dict): return HarEntryRequestCookiesInner.parse_obj(obj) - _obj = HarEntryRequestCookiesInner.parse_obj({ - "name": obj.get("name"), - "value": obj.get("value"), - "path": obj.get("path"), - "domain": obj.get("domain"), - "expires": obj.get("expires"), - "http_only": obj.get("httpOnly"), - "secure": obj.get("secure"), - "comment": obj.get("comment") - }) + _obj = HarEntryRequestCookiesInner.parse_obj( + { + "name": obj.get("name"), + "value": obj.get("value"), + "path": obj.get("path"), + "domain": obj.get("domain"), + "expires": obj.get("expires"), + "http_only": obj.get("httpOnly"), + "secure": obj.get("secure"), + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_post_data.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_post_data.py index e1212791e7..88a115d8db 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_post_data.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_post_data.py @@ -1,32 +1,39 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional + +from pydantic import BaseModel +from pydantic import conlist +from pydantic import Field +from pydantic import StrictStr +from BrowserUpMitmProxyClient.models.har_entry_request_post_data_params_inner import ( + HarEntryRequestPostDataParamsInner, +) -from typing import List, Optional -from pydantic import BaseModel, Field, StrictStr, conlist -from BrowserUpMitmProxyClient.models.har_entry_request_post_data_params_inner import HarEntryRequestPostDataParamsInner class HarEntryRequestPostData(BaseModel): """ Posted data info. """ + mime_type: StrictStr = Field(..., alias="mimeType") text: Optional[StrictStr] = None params: Optional[conlist(HarEntryRequestPostDataParamsInner)] = None @@ -34,6 +41,7 @@ class HarEntryRequestPostData(BaseModel): class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -52,17 +60,14 @@ def from_json(cls, json_str: str) -> HarEntryRequestPostData: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) # override the default output from pydantic by calling `to_dict()` of each item in params (list) _items = [] if self.params: for _item in self.params: if _item: _items.append(_item.to_dict()) - _dict['params'] = _items + _dict["params"] = _items return _dict @classmethod @@ -74,11 +79,16 @@ def from_dict(cls, obj: dict) -> HarEntryRequestPostData: if not isinstance(obj, dict): return HarEntryRequestPostData.parse_obj(obj) - _obj = HarEntryRequestPostData.parse_obj({ - "mime_type": obj.get("mimeType"), - "text": obj.get("text"), - "params": [HarEntryRequestPostDataParamsInner.from_dict(_item) for _item in obj.get("params")] if obj.get("params") is not None else None - }) + _obj = HarEntryRequestPostData.parse_obj( + { + "mime_type": obj.get("mimeType"), + "text": obj.get("text"), + "params": [ + HarEntryRequestPostDataParamsInner.from_dict(_item) + for _item in obj.get("params") + ] + if obj.get("params") is not None + else None, + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_post_data_params_inner.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_post_data_params_inner.py index a4212856ce..1725cb7274 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_post_data_params_inner.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_post_data_params_inner.py @@ -1,31 +1,34 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictStr class HarEntryRequestPostDataParamsInner(BaseModel): """ HarEntryRequestPostDataParamsInner """ + name: Optional[StrictStr] = None value: Optional[StrictStr] = None file_name: Optional[StrictStr] = Field(None, alias="fileName") @@ -35,6 +38,7 @@ class HarEntryRequestPostDataParamsInner(BaseModel): class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -53,10 +57,7 @@ def from_json(cls, json_str: str) -> HarEntryRequestPostDataParamsInner: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -68,13 +69,13 @@ def from_dict(cls, obj: dict) -> HarEntryRequestPostDataParamsInner: if not isinstance(obj, dict): return HarEntryRequestPostDataParamsInner.parse_obj(obj) - _obj = HarEntryRequestPostDataParamsInner.parse_obj({ - "name": obj.get("name"), - "value": obj.get("value"), - "file_name": obj.get("fileName"), - "content_type": obj.get("contentType"), - "comment": obj.get("comment") - }) + _obj = HarEntryRequestPostDataParamsInner.parse_obj( + { + "name": obj.get("name"), + "value": obj.get("value"), + "file_name": obj.get("fileName"), + "content_type": obj.get("contentType"), + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_query_string_inner.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_query_string_inner.py index f1f0db4ae7..3378c1d299 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_query_string_inner.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request_query_string_inner.py @@ -1,31 +1,34 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictStr class HarEntryRequestQueryStringInner(BaseModel): """ HarEntryRequestQueryStringInner """ + name: StrictStr = Field(...) value: StrictStr = Field(...) comment: Optional[StrictStr] = None @@ -33,6 +36,7 @@ class HarEntryRequestQueryStringInner(BaseModel): class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -51,10 +55,7 @@ def from_json(cls, json_str: str) -> HarEntryRequestQueryStringInner: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -66,11 +67,11 @@ def from_dict(cls, obj: dict) -> HarEntryRequestQueryStringInner: if not isinstance(obj, dict): return HarEntryRequestQueryStringInner.parse_obj(obj) - _obj = HarEntryRequestQueryStringInner.parse_obj({ - "name": obj.get("name"), - "value": obj.get("value"), - "comment": obj.get("comment") - }) + _obj = HarEntryRequestQueryStringInner.parse_obj( + { + "name": obj.get("name"), + "value": obj.get("value"), + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py index 30d31fb964..21e15bf6ad 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py @@ -1,34 +1,44 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json - - -from typing import List, Optional -from pydantic import BaseModel, Field, StrictInt, StrictStr, conlist -from BrowserUpMitmProxyClient.models.har_entry_request_cookies_inner import HarEntryRequestCookiesInner -from BrowserUpMitmProxyClient.models.har_entry_response_content import HarEntryResponseContent +from typing import Optional + +from pydantic import BaseModel +from pydantic import conlist +from pydantic import Field +from pydantic import StrictInt +from pydantic import StrictStr + +from BrowserUpMitmProxyClient.models.har_entry_request_cookies_inner import ( + HarEntryRequestCookiesInner, +) +from BrowserUpMitmProxyClient.models.har_entry_response_content import ( + HarEntryResponseContent, +) from BrowserUpMitmProxyClient.models.header import Header + class HarEntryResponse(BaseModel): """ HarEntryResponse """ + status: StrictInt = Field(...) status_text: StrictStr = Field(..., alias="statusText") http_version: StrictStr = Field(..., alias="httpVersion") @@ -40,10 +50,22 @@ class HarEntryResponse(BaseModel): body_size: StrictInt = Field(..., alias="bodySize") comment: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} - __properties = ["status", "statusText", "httpVersion", "cookies", "headers", "content", "redirectURL", "headersSize", "bodySize", "comment"] + __properties = [ + "status", + "statusText", + "httpVersion", + "cookies", + "headers", + "content", + "redirectURL", + "headersSize", + "bodySize", + "comment", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -62,28 +84,26 @@ def from_json(cls, json_str: str) -> HarEntryResponse: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - "additional_properties" - }, - exclude_none=True) + _dict = self.dict( + by_alias=True, exclude={"additional_properties"}, exclude_none=True + ) # override the default output from pydantic by calling `to_dict()` of each item in cookies (list) _items = [] if self.cookies: for _item in self.cookies: if _item: _items.append(_item.to_dict()) - _dict['cookies'] = _items + _dict["cookies"] = _items # override the default output from pydantic by calling `to_dict()` of each item in headers (list) _items = [] if self.headers: for _item in self.headers: if _item: _items.append(_item.to_dict()) - _dict['headers'] = _items + _dict["headers"] = _items # override the default output from pydantic by calling `to_dict()` of content if self.content: - _dict['content'] = self.content.to_dict() + _dict["content"] = self.content.to_dict() # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -100,23 +120,32 @@ def from_dict(cls, obj: dict) -> HarEntryResponse: if not isinstance(obj, dict): return HarEntryResponse.parse_obj(obj) - _obj = HarEntryResponse.parse_obj({ - "status": obj.get("status"), - "status_text": obj.get("statusText"), - "http_version": obj.get("httpVersion"), - "cookies": [HarEntryRequestCookiesInner.from_dict(_item) for _item in obj.get("cookies")] if obj.get("cookies") is not None else None, - "headers": [Header.from_dict(_item) for _item in obj.get("headers")] if obj.get("headers") is not None else None, - "content": HarEntryResponseContent.from_dict(obj.get("content")) if obj.get("content") is not None else None, - "redirect_url": obj.get("redirectURL"), - "headers_size": obj.get("headersSize"), - "body_size": obj.get("bodySize"), - "comment": obj.get("comment") - }) + _obj = HarEntryResponse.parse_obj( + { + "status": obj.get("status"), + "status_text": obj.get("statusText"), + "http_version": obj.get("httpVersion"), + "cookies": [ + HarEntryRequestCookiesInner.from_dict(_item) + for _item in obj.get("cookies") + ] + if obj.get("cookies") is not None + else None, + "headers": [Header.from_dict(_item) for _item in obj.get("headers")] + if obj.get("headers") is not None + else None, + "content": HarEntryResponseContent.from_dict(obj.get("content")) + if obj.get("content") is not None + else None, + "redirect_url": obj.get("redirectURL"), + "headers_size": obj.get("headersSize"), + "body_size": obj.get("bodySize"), + "comment": obj.get("comment"), + } + ) # store additional fields in additional_properties for _key in obj.keys(): if _key not in cls.__properties: _obj.additional_properties[_key] = obj.get(_key) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_response_content.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_response_content.py index 2d2aa39614..fb40a85cfa 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_response_content.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_response_content.py @@ -1,49 +1,86 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import conint +from pydantic import Field +from pydantic import StrictInt +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictInt, StrictStr, conint class HarEntryResponseContent(BaseModel): """ HarEntryResponseContent """ + size: StrictInt = Field(...) compression: Optional[StrictInt] = None mime_type: StrictStr = Field(..., alias="mimeType") text: Optional[StrictStr] = None encoding: Optional[StrictStr] = None - video_buffered_percent: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_videoBufferedPercent") - video_stall_count: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_videoStallCount") - video_decoded_byte_count: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_videoDecodedByteCount") - video_waiting_count: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_videoWaitingCount") - video_error_count: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_videoErrorCount") - video_dropped_frames: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_videoDroppedFrames") - video_total_frames: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_videoTotalFrames") - video_audio_bytes_decoded: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_videoAudioBytesDecoded") + video_buffered_percent: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_videoBufferedPercent" + ) + video_stall_count: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_videoStallCount" + ) + video_decoded_byte_count: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_videoDecodedByteCount" + ) + video_waiting_count: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_videoWaitingCount" + ) + video_error_count: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_videoErrorCount" + ) + video_dropped_frames: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_videoDroppedFrames" + ) + video_total_frames: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_videoTotalFrames" + ) + video_audio_bytes_decoded: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_videoAudioBytesDecoded" + ) comment: Optional[StrictStr] = None - __properties = ["size", "compression", "mimeType", "text", "encoding", "_videoBufferedPercent", "_videoStallCount", "_videoDecodedByteCount", "_videoWaitingCount", "_videoErrorCount", "_videoDroppedFrames", "_videoTotalFrames", "_videoAudioBytesDecoded", "comment"] + __properties = [ + "size", + "compression", + "mimeType", + "text", + "encoding", + "_videoBufferedPercent", + "_videoStallCount", + "_videoDecodedByteCount", + "_videoWaitingCount", + "_videoErrorCount", + "_videoDroppedFrames", + "_videoTotalFrames", + "_videoAudioBytesDecoded", + "comment", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -62,10 +99,7 @@ def from_json(cls, json_str: str) -> HarEntryResponseContent: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -77,22 +111,38 @@ def from_dict(cls, obj: dict) -> HarEntryResponseContent: if not isinstance(obj, dict): return HarEntryResponseContent.parse_obj(obj) - _obj = HarEntryResponseContent.parse_obj({ - "size": obj.get("size"), - "compression": obj.get("compression"), - "mime_type": obj.get("mimeType"), - "text": obj.get("text"), - "encoding": obj.get("encoding"), - "video_buffered_percent": obj.get("_videoBufferedPercent") if obj.get("_videoBufferedPercent") is not None else -1, - "video_stall_count": obj.get("_videoStallCount") if obj.get("_videoStallCount") is not None else -1, - "video_decoded_byte_count": obj.get("_videoDecodedByteCount") if obj.get("_videoDecodedByteCount") is not None else -1, - "video_waiting_count": obj.get("_videoWaitingCount") if obj.get("_videoWaitingCount") is not None else -1, - "video_error_count": obj.get("_videoErrorCount") if obj.get("_videoErrorCount") is not None else -1, - "video_dropped_frames": obj.get("_videoDroppedFrames") if obj.get("_videoDroppedFrames") is not None else -1, - "video_total_frames": obj.get("_videoTotalFrames") if obj.get("_videoTotalFrames") is not None else -1, - "video_audio_bytes_decoded": obj.get("_videoAudioBytesDecoded") if obj.get("_videoAudioBytesDecoded") is not None else -1, - "comment": obj.get("comment") - }) + _obj = HarEntryResponseContent.parse_obj( + { + "size": obj.get("size"), + "compression": obj.get("compression"), + "mime_type": obj.get("mimeType"), + "text": obj.get("text"), + "encoding": obj.get("encoding"), + "video_buffered_percent": obj.get("_videoBufferedPercent") + if obj.get("_videoBufferedPercent") is not None + else -1, + "video_stall_count": obj.get("_videoStallCount") + if obj.get("_videoStallCount") is not None + else -1, + "video_decoded_byte_count": obj.get("_videoDecodedByteCount") + if obj.get("_videoDecodedByteCount") is not None + else -1, + "video_waiting_count": obj.get("_videoWaitingCount") + if obj.get("_videoWaitingCount") is not None + else -1, + "video_error_count": obj.get("_videoErrorCount") + if obj.get("_videoErrorCount") is not None + else -1, + "video_dropped_frames": obj.get("_videoDroppedFrames") + if obj.get("_videoDroppedFrames") is not None + else -1, + "video_total_frames": obj.get("_videoTotalFrames") + if obj.get("_videoTotalFrames") is not None + else -1, + "video_audio_bytes_decoded": obj.get("_videoAudioBytesDecoded") + if obj.get("_videoAudioBytesDecoded") is not None + else -1, + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_timings.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_timings.py index effcda1b07..5c75c52ef4 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_timings.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_timings.py @@ -1,31 +1,35 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import conint +from pydantic import Field +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictStr, conint class HarEntryTimings(BaseModel): """ HarEntryTimings """ + dns: conint(strict=True, ge=-1) = Field(...) connect: conint(strict=True, ge=-1) = Field(...) blocked: conint(strict=True, ge=-1) = Field(...) @@ -34,10 +38,20 @@ class HarEntryTimings(BaseModel): receive: conint(strict=True, ge=-1) = Field(...) ssl: conint(strict=True, ge=-1) = Field(...) comment: Optional[StrictStr] = None - __properties = ["dns", "connect", "blocked", "send", "wait", "receive", "ssl", "comment"] + __properties = [ + "dns", + "connect", + "blocked", + "send", + "wait", + "receive", + "ssl", + "comment", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -56,10 +70,7 @@ def from_json(cls, json_str: str) -> HarEntryTimings: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -71,16 +82,16 @@ def from_dict(cls, obj: dict) -> HarEntryTimings: if not isinstance(obj, dict): return HarEntryTimings.parse_obj(obj) - _obj = HarEntryTimings.parse_obj({ - "dns": obj.get("dns") if obj.get("dns") is not None else -1, - "connect": obj.get("connect") if obj.get("connect") is not None else -1, - "blocked": obj.get("blocked") if obj.get("blocked") is not None else -1, - "send": obj.get("send") if obj.get("send") is not None else -1, - "wait": obj.get("wait") if obj.get("wait") is not None else -1, - "receive": obj.get("receive") if obj.get("receive") is not None else -1, - "ssl": obj.get("ssl") if obj.get("ssl") is not None else -1, - "comment": obj.get("comment") - }) + _obj = HarEntryTimings.parse_obj( + { + "dns": obj.get("dns") if obj.get("dns") is not None else -1, + "connect": obj.get("connect") if obj.get("connect") is not None else -1, + "blocked": obj.get("blocked") if obj.get("blocked") is not None else -1, + "send": obj.get("send") if obj.get("send") is not None else -1, + "wait": obj.get("wait") if obj.get("wait") is not None else -1, + "receive": obj.get("receive") if obj.get("receive") is not None else -1, + "ssl": obj.get("ssl") if obj.get("ssl") is not None else -1, + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_log.py b/clients/python/BrowserUpMitmProxyClient/models/har_log.py index d35cd4f6a6..8cbd2d4205 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_log.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_log.py @@ -1,34 +1,39 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import conlist +from pydantic import Field +from pydantic import StrictStr -from typing import List, Optional -from pydantic import BaseModel, Field, StrictStr, conlist from BrowserUpMitmProxyClient.models.har_entry import HarEntry from BrowserUpMitmProxyClient.models.har_log_creator import HarLogCreator from BrowserUpMitmProxyClient.models.page import Page + class HarLog(BaseModel): """ HarLog """ + version: StrictStr = Field(...) creator: HarLogCreator = Field(...) browser: Optional[HarLogCreator] = None @@ -39,6 +44,7 @@ class HarLog(BaseModel): class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -57,30 +63,27 @@ def from_json(cls, json_str: str) -> HarLog: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) # override the default output from pydantic by calling `to_dict()` of creator if self.creator: - _dict['creator'] = self.creator.to_dict() + _dict["creator"] = self.creator.to_dict() # override the default output from pydantic by calling `to_dict()` of browser if self.browser: - _dict['browser'] = self.browser.to_dict() + _dict["browser"] = self.browser.to_dict() # override the default output from pydantic by calling `to_dict()` of each item in pages (list) _items = [] if self.pages: for _item in self.pages: if _item: _items.append(_item.to_dict()) - _dict['pages'] = _items + _dict["pages"] = _items # override the default output from pydantic by calling `to_dict()` of each item in entries (list) _items = [] if self.entries: for _item in self.entries: if _item: _items.append(_item.to_dict()) - _dict['entries'] = _items + _dict["entries"] = _items return _dict @classmethod @@ -92,14 +95,22 @@ def from_dict(cls, obj: dict) -> HarLog: if not isinstance(obj, dict): return HarLog.parse_obj(obj) - _obj = HarLog.parse_obj({ - "version": obj.get("version"), - "creator": HarLogCreator.from_dict(obj.get("creator")) if obj.get("creator") is not None else None, - "browser": HarLogCreator.from_dict(obj.get("browser")) if obj.get("browser") is not None else None, - "pages": [Page.from_dict(_item) for _item in obj.get("pages")] if obj.get("pages") is not None else None, - "entries": [HarEntry.from_dict(_item) for _item in obj.get("entries")] if obj.get("entries") is not None else None, - "comment": obj.get("comment") - }) + _obj = HarLog.parse_obj( + { + "version": obj.get("version"), + "creator": HarLogCreator.from_dict(obj.get("creator")) + if obj.get("creator") is not None + else None, + "browser": HarLogCreator.from_dict(obj.get("browser")) + if obj.get("browser") is not None + else None, + "pages": [Page.from_dict(_item) for _item in obj.get("pages")] + if obj.get("pages") is not None + else None, + "entries": [HarEntry.from_dict(_item) for _item in obj.get("entries")] + if obj.get("entries") is not None + else None, + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_log_creator.py b/clients/python/BrowserUpMitmProxyClient/models/har_log_creator.py index fde0eaa897..e38cf0226b 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_log_creator.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_log_creator.py @@ -1,31 +1,34 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictStr class HarLogCreator(BaseModel): """ HarLogCreator """ + name: StrictStr = Field(...) version: StrictStr = Field(...) comment: Optional[StrictStr] = None @@ -33,6 +36,7 @@ class HarLogCreator(BaseModel): class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -51,10 +55,7 @@ def from_json(cls, json_str: str) -> HarLogCreator: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -66,11 +67,11 @@ def from_dict(cls, obj: dict) -> HarLogCreator: if not isinstance(obj, dict): return HarLogCreator.parse_obj(obj) - _obj = HarLogCreator.parse_obj({ - "name": obj.get("name"), - "version": obj.get("version"), - "comment": obj.get("comment") - }) + _obj = HarLogCreator.parse_obj( + { + "name": obj.get("name"), + "version": obj.get("version"), + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/header.py b/clients/python/BrowserUpMitmProxyClient/models/header.py index 4fc29f3754..724d8cf327 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/header.py +++ b/clients/python/BrowserUpMitmProxyClient/models/header.py @@ -1,31 +1,34 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictStr class Header(BaseModel): """ Header """ + name: StrictStr = Field(...) value: StrictStr = Field(...) comment: Optional[StrictStr] = None @@ -33,6 +36,7 @@ class Header(BaseModel): class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -51,10 +55,7 @@ def from_json(cls, json_str: str) -> Header: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -66,11 +67,11 @@ def from_dict(cls, obj: dict) -> Header: if not isinstance(obj, dict): return Header.parse_obj(obj) - _obj = Header.parse_obj({ - "name": obj.get("name"), - "value": obj.get("value"), - "comment": obj.get("comment") - }) + _obj = Header.parse_obj( + { + "name": obj.get("name"), + "value": obj.get("value"), + "comment": obj.get("comment"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py b/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py index 5c0a081285..e878485a31 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py +++ b/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py @@ -1,40 +1,45 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import conint +from pydantic import Field +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictStr, conint class LargestContentfulPaint(BaseModel): """ LargestContentfulPaint """ + start_time: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="startTime") size: Optional[conint(strict=True, ge=-1)] = -1 - dom_path: Optional[StrictStr] = Field('', alias="domPath") - tag: Optional[StrictStr] = '' + dom_path: Optional[StrictStr] = Field("", alias="domPath") + tag: Optional[StrictStr] = "" additional_properties: Dict[str, Any] = {} __properties = ["startTime", "size", "domPath", "tag"] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -53,11 +58,9 @@ def from_json(cls, json_str: str) -> LargestContentfulPaint: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - "additional_properties" - }, - exclude_none=True) + _dict = self.dict( + by_alias=True, exclude={"additional_properties"}, exclude_none=True + ) # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -74,17 +77,21 @@ def from_dict(cls, obj: dict) -> LargestContentfulPaint: if not isinstance(obj, dict): return LargestContentfulPaint.parse_obj(obj) - _obj = LargestContentfulPaint.parse_obj({ - "start_time": obj.get("startTime") if obj.get("startTime") is not None else -1, - "size": obj.get("size") if obj.get("size") is not None else -1, - "dom_path": obj.get("domPath") if obj.get("domPath") is not None else '', - "tag": obj.get("tag") if obj.get("tag") is not None else '' - }) + _obj = LargestContentfulPaint.parse_obj( + { + "start_time": obj.get("startTime") + if obj.get("startTime") is not None + else -1, + "size": obj.get("size") if obj.get("size") is not None else -1, + "dom_path": obj.get("domPath") + if obj.get("domPath") is not None + else "", + "tag": obj.get("tag") if obj.get("tag") is not None else "", + } + ) # store additional fields in additional_properties for _key in obj.keys(): if _key not in cls.__properties: _obj.additional_properties[_key] = obj.get(_key) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/match_criteria.py b/clients/python/BrowserUpMitmProxyClient/models/match_criteria.py index f330b4816d..1c2b432450 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/match_criteria.py +++ b/clients/python/BrowserUpMitmProxyClient/models/match_criteria.py @@ -1,50 +1,79 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictBool +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictBool, StrictStr from BrowserUpMitmProxyClient.models.name_value_pair import NameValuePair + class MatchCriteria(BaseModel): """ A set of criteria for filtering HTTP Requests and Responses. Criteria are AND based, and use python regular expressions for string comparison """ + url: Optional[StrictStr] = Field(None, description="Request URL regexp to match") page: Optional[StrictStr] = Field(None, description="current|all") status: Optional[StrictStr] = Field(None, description="HTTP Status code to match.") - content: Optional[StrictStr] = Field(None, description="Body content regexp content to match") + content: Optional[StrictStr] = Field( + None, description="Body content regexp content to match" + ) content_type: Optional[StrictStr] = Field(None, description="Content type") - websocket_message: Optional[StrictStr] = Field(None, description="Websocket message text to match") + websocket_message: Optional[StrictStr] = Field( + None, description="Websocket message text to match" + ) request_header: Optional[NameValuePair] = None request_cookie: Optional[NameValuePair] = None response_header: Optional[NameValuePair] = None response_cookie: Optional[NameValuePair] = None json_valid: Optional[StrictBool] = Field(None, description="Is valid JSON") json_path: Optional[StrictStr] = Field(None, description="Has JSON path") - json_schema: Optional[StrictStr] = Field(None, description="Validates against passed JSON schema") - error_if_no_traffic: Optional[StrictBool] = Field(True, description="If the proxy has NO traffic at all, return error") - __properties = ["url", "page", "status", "content", "content_type", "websocket_message", "request_header", "request_cookie", "response_header", "response_cookie", "json_valid", "json_path", "json_schema", "error_if_no_traffic"] + json_schema: Optional[StrictStr] = Field( + None, description="Validates against passed JSON schema" + ) + error_if_no_traffic: Optional[StrictBool] = Field( + True, description="If the proxy has NO traffic at all, return error" + ) + __properties = [ + "url", + "page", + "status", + "content", + "content_type", + "websocket_message", + "request_header", + "request_cookie", + "response_header", + "response_cookie", + "json_valid", + "json_path", + "json_schema", + "error_if_no_traffic", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -63,22 +92,19 @@ def from_json(cls, json_str: str) -> MatchCriteria: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) # override the default output from pydantic by calling `to_dict()` of request_header if self.request_header: - _dict['request_header'] = self.request_header.to_dict() + _dict["request_header"] = self.request_header.to_dict() # override the default output from pydantic by calling `to_dict()` of request_cookie if self.request_cookie: - _dict['request_cookie'] = self.request_cookie.to_dict() + _dict["request_cookie"] = self.request_cookie.to_dict() # override the default output from pydantic by calling `to_dict()` of response_header if self.response_header: - _dict['response_header'] = self.response_header.to_dict() + _dict["response_header"] = self.response_header.to_dict() # override the default output from pydantic by calling `to_dict()` of response_cookie if self.response_cookie: - _dict['response_cookie'] = self.response_cookie.to_dict() + _dict["response_cookie"] = self.response_cookie.to_dict() return _dict @classmethod @@ -90,22 +116,32 @@ def from_dict(cls, obj: dict) -> MatchCriteria: if not isinstance(obj, dict): return MatchCriteria.parse_obj(obj) - _obj = MatchCriteria.parse_obj({ - "url": obj.get("url"), - "page": obj.get("page"), - "status": obj.get("status"), - "content": obj.get("content"), - "content_type": obj.get("content_type"), - "websocket_message": obj.get("websocket_message"), - "request_header": NameValuePair.from_dict(obj.get("request_header")) if obj.get("request_header") is not None else None, - "request_cookie": NameValuePair.from_dict(obj.get("request_cookie")) if obj.get("request_cookie") is not None else None, - "response_header": NameValuePair.from_dict(obj.get("response_header")) if obj.get("response_header") is not None else None, - "response_cookie": NameValuePair.from_dict(obj.get("response_cookie")) if obj.get("response_cookie") is not None else None, - "json_valid": obj.get("json_valid"), - "json_path": obj.get("json_path"), - "json_schema": obj.get("json_schema"), - "error_if_no_traffic": obj.get("error_if_no_traffic") if obj.get("error_if_no_traffic") is not None else True - }) + _obj = MatchCriteria.parse_obj( + { + "url": obj.get("url"), + "page": obj.get("page"), + "status": obj.get("status"), + "content": obj.get("content"), + "content_type": obj.get("content_type"), + "websocket_message": obj.get("websocket_message"), + "request_header": NameValuePair.from_dict(obj.get("request_header")) + if obj.get("request_header") is not None + else None, + "request_cookie": NameValuePair.from_dict(obj.get("request_cookie")) + if obj.get("request_cookie") is not None + else None, + "response_header": NameValuePair.from_dict(obj.get("response_header")) + if obj.get("response_header") is not None + else None, + "response_cookie": NameValuePair.from_dict(obj.get("response_cookie")) + if obj.get("response_cookie") is not None + else None, + "json_valid": obj.get("json_valid"), + "json_path": obj.get("json_path"), + "json_schema": obj.get("json_schema"), + "error_if_no_traffic": obj.get("error_if_no_traffic") + if obj.get("error_if_no_traffic") is not None + else True, + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/name_value_pair.py b/clients/python/BrowserUpMitmProxyClient/models/name_value_pair.py index f39fd87744..2511dd1503 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/name_value_pair.py +++ b/clients/python/BrowserUpMitmProxyClient/models/name_value_pair.py @@ -1,37 +1,41 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictStr class NameValuePair(BaseModel): """ NameValuePair """ + name: Optional[StrictStr] = Field(None, description="Name to match") value: Optional[StrictStr] = Field(None, description="Value to match") __properties = ["name", "value"] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -50,10 +54,7 @@ def from_json(cls, json_str: str) -> NameValuePair: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -65,10 +66,7 @@ def from_dict(cls, obj: dict) -> NameValuePair: if not isinstance(obj, dict): return NameValuePair.parse_obj(obj) - _obj = NameValuePair.parse_obj({ - "name": obj.get("name"), - "value": obj.get("value") - }) + _obj = NameValuePair.parse_obj( + {"name": obj.get("name"), "value": obj.get("value")} + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/page.py b/clients/python/BrowserUpMitmProxyClient/models/page.py index a3ca35e6fc..c85c1706c9 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/page.py +++ b/clients/python/BrowserUpMitmProxyClient/models/page.py @@ -1,35 +1,41 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json - from datetime import datetime -from typing import List, Optional -from pydantic import BaseModel, Field, StrictStr, conlist +from typing import Optional + +from pydantic import BaseModel +from pydantic import conlist +from pydantic import Field +from pydantic import StrictStr + from BrowserUpMitmProxyClient.models.counter import Counter from BrowserUpMitmProxyClient.models.error import Error from BrowserUpMitmProxyClient.models.page_timings import PageTimings from BrowserUpMitmProxyClient.models.verify_result import VerifyResult + class Page(BaseModel): """ Page """ + started_date_time: datetime = Field(..., alias="startedDateTime") id: StrictStr = Field(...) title: StrictStr = Field(...) @@ -39,10 +45,20 @@ class Page(BaseModel): page_timings: PageTimings = Field(..., alias="pageTimings") comment: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} - __properties = ["startedDateTime", "id", "title", "_verifications", "_counters", "_errors", "pageTimings", "comment"] + __properties = [ + "startedDateTime", + "id", + "title", + "_verifications", + "_counters", + "_errors", + "pageTimings", + "comment", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -61,35 +77,33 @@ def from_json(cls, json_str: str) -> Page: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - "additional_properties" - }, - exclude_none=True) + _dict = self.dict( + by_alias=True, exclude={"additional_properties"}, exclude_none=True + ) # override the default output from pydantic by calling `to_dict()` of each item in verifications (list) _items = [] if self.verifications: for _item in self.verifications: if _item: _items.append(_item.to_dict()) - _dict['_verifications'] = _items + _dict["_verifications"] = _items # override the default output from pydantic by calling `to_dict()` of each item in counters (list) _items = [] if self.counters: for _item in self.counters: if _item: _items.append(_item.to_dict()) - _dict['_counters'] = _items + _dict["_counters"] = _items # override the default output from pydantic by calling `to_dict()` of each item in errors (list) _items = [] if self.errors: for _item in self.errors: if _item: _items.append(_item.to_dict()) - _dict['_errors'] = _items + _dict["_errors"] = _items # override the default output from pydantic by calling `to_dict()` of page_timings if self.page_timings: - _dict['pageTimings'] = self.page_timings.to_dict() + _dict["pageTimings"] = self.page_timings.to_dict() # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -106,21 +120,31 @@ def from_dict(cls, obj: dict) -> Page: if not isinstance(obj, dict): return Page.parse_obj(obj) - _obj = Page.parse_obj({ - "started_date_time": obj.get("startedDateTime"), - "id": obj.get("id"), - "title": obj.get("title"), - "verifications": [VerifyResult.from_dict(_item) for _item in obj.get("_verifications")] if obj.get("_verifications") is not None else None, - "counters": [Counter.from_dict(_item) for _item in obj.get("_counters")] if obj.get("_counters") is not None else None, - "errors": [Error.from_dict(_item) for _item in obj.get("_errors")] if obj.get("_errors") is not None else None, - "page_timings": PageTimings.from_dict(obj.get("pageTimings")) if obj.get("pageTimings") is not None else None, - "comment": obj.get("comment") - }) + _obj = Page.parse_obj( + { + "started_date_time": obj.get("startedDateTime"), + "id": obj.get("id"), + "title": obj.get("title"), + "verifications": [ + VerifyResult.from_dict(_item) for _item in obj.get("_verifications") + ] + if obj.get("_verifications") is not None + else None, + "counters": [Counter.from_dict(_item) for _item in obj.get("_counters")] + if obj.get("_counters") is not None + else None, + "errors": [Error.from_dict(_item) for _item in obj.get("_errors")] + if obj.get("_errors") is not None + else None, + "page_timings": PageTimings.from_dict(obj.get("pageTimings")) + if obj.get("pageTimings") is not None + else None, + "comment": obj.get("comment"), + } + ) # store additional fields in additional_properties for _key in obj.keys(): if _key not in cls.__properties: _obj.additional_properties[_key] = obj.get(_key) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/page_timing.py b/clients/python/BrowserUpMitmProxyClient/models/page_timing.py index 6ad85ac922..5ea99b2869 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/page_timing.py +++ b/clients/python/BrowserUpMitmProxyClient/models/page_timing.py @@ -1,47 +1,101 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from typing import Union +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictFloat +from pydantic import StrictInt +from pydantic import StrictStr -from typing import Optional, Union -from pydantic import BaseModel, Field, StrictFloat, StrictInt, StrictStr class PageTiming(BaseModel): """ PageTiming """ - on_content_load: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="onContentLoad", description="onContentLoad per the browser") - on_load: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="onLoad", description="onLoad per the browser") - first_input_delay: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="_firstInputDelay", description="firstInputDelay from the browser") - first_paint: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="_firstPaint", description="firstPaint from the browser") - cumulative_layout_shift: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="_cumulativeLayoutShift", description="cumulativeLayoutShift metric from the browser") - largest_contentful_paint: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="_largestContentfulPaint", description="largestContentfulPaint from the browser") - dom_interactive: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="_domInteractive", description="domInteractive from the browser") - first_contentful_paint: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="_firstContentfulPaint", description="firstContentfulPaint from the browser") - dns: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="_dns", description="dns lookup time from the browser") - ssl: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="_ssl", description="Ssl connect time from the browser") - time_to_first_byte: Optional[Union[StrictFloat, StrictInt]] = Field(None, alias="_timeToFirstByte", description="Time to first byte of the page's first request per the browser") - href: Optional[StrictStr] = Field(None, alias="_href", description="Top level href, including hashtag, etc per the browser") - __properties = ["onContentLoad", "onLoad", "_firstInputDelay", "_firstPaint", "_cumulativeLayoutShift", "_largestContentfulPaint", "_domInteractive", "_firstContentfulPaint", "_dns", "_ssl", "_timeToFirstByte", "_href"] + + on_content_load: Optional[Union[StrictFloat, StrictInt]] = Field( + None, alias="onContentLoad", description="onContentLoad per the browser" + ) + on_load: Optional[Union[StrictFloat, StrictInt]] = Field( + None, alias="onLoad", description="onLoad per the browser" + ) + first_input_delay: Optional[Union[StrictFloat, StrictInt]] = Field( + None, alias="_firstInputDelay", description="firstInputDelay from the browser" + ) + first_paint: Optional[Union[StrictFloat, StrictInt]] = Field( + None, alias="_firstPaint", description="firstPaint from the browser" + ) + cumulative_layout_shift: Optional[Union[StrictFloat, StrictInt]] = Field( + None, + alias="_cumulativeLayoutShift", + description="cumulativeLayoutShift metric from the browser", + ) + largest_contentful_paint: Optional[Union[StrictFloat, StrictInt]] = Field( + None, + alias="_largestContentfulPaint", + description="largestContentfulPaint from the browser", + ) + dom_interactive: Optional[Union[StrictFloat, StrictInt]] = Field( + None, alias="_domInteractive", description="domInteractive from the browser" + ) + first_contentful_paint: Optional[Union[StrictFloat, StrictInt]] = Field( + None, + alias="_firstContentfulPaint", + description="firstContentfulPaint from the browser", + ) + dns: Optional[Union[StrictFloat, StrictInt]] = Field( + None, alias="_dns", description="dns lookup time from the browser" + ) + ssl: Optional[Union[StrictFloat, StrictInt]] = Field( + None, alias="_ssl", description="Ssl connect time from the browser" + ) + time_to_first_byte: Optional[Union[StrictFloat, StrictInt]] = Field( + None, + alias="_timeToFirstByte", + description="Time to first byte of the page's first request per the browser", + ) + href: Optional[StrictStr] = Field( + None, + alias="_href", + description="Top level href, including hashtag, etc per the browser", + ) + __properties = [ + "onContentLoad", + "onLoad", + "_firstInputDelay", + "_firstPaint", + "_cumulativeLayoutShift", + "_largestContentfulPaint", + "_domInteractive", + "_firstContentfulPaint", + "_dns", + "_ssl", + "_timeToFirstByte", + "_href", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -60,10 +114,7 @@ def from_json(cls, json_str: str) -> PageTiming: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -75,20 +126,20 @@ def from_dict(cls, obj: dict) -> PageTiming: if not isinstance(obj, dict): return PageTiming.parse_obj(obj) - _obj = PageTiming.parse_obj({ - "on_content_load": obj.get("onContentLoad"), - "on_load": obj.get("onLoad"), - "first_input_delay": obj.get("_firstInputDelay"), - "first_paint": obj.get("_firstPaint"), - "cumulative_layout_shift": obj.get("_cumulativeLayoutShift"), - "largest_contentful_paint": obj.get("_largestContentfulPaint"), - "dom_interactive": obj.get("_domInteractive"), - "first_contentful_paint": obj.get("_firstContentfulPaint"), - "dns": obj.get("_dns"), - "ssl": obj.get("_ssl"), - "time_to_first_byte": obj.get("_timeToFirstByte"), - "href": obj.get("_href") - }) + _obj = PageTiming.parse_obj( + { + "on_content_load": obj.get("onContentLoad"), + "on_load": obj.get("onLoad"), + "first_input_delay": obj.get("_firstInputDelay"), + "first_paint": obj.get("_firstPaint"), + "cumulative_layout_shift": obj.get("_cumulativeLayoutShift"), + "largest_contentful_paint": obj.get("_largestContentfulPaint"), + "dom_interactive": obj.get("_domInteractive"), + "first_contentful_paint": obj.get("_firstContentfulPaint"), + "dns": obj.get("_dns"), + "ssl": obj.get("_ssl"), + "time_to_first_byte": obj.get("_timeToFirstByte"), + "href": obj.get("_href"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/page_timings.py b/clients/python/BrowserUpMitmProxyClient/models/page_timings.py index 1bf0aaae5d..1241fc425e 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/page_timings.py +++ b/clients/python/BrowserUpMitmProxyClient/models/page_timings.py @@ -1,50 +1,86 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from typing import Union + +from pydantic import BaseModel +from pydantic import confloat +from pydantic import conint +from pydantic import Field +from pydantic import StrictStr +from BrowserUpMitmProxyClient.models.largest_contentful_paint import ( + LargestContentfulPaint, +) -from typing import Optional, Union -from pydantic import BaseModel, Field, StrictStr, confloat, conint -from BrowserUpMitmProxyClient.models.largest_contentful_paint import LargestContentfulPaint class PageTimings(BaseModel): """ PageTimings """ + on_content_load: conint(strict=True, ge=-1) = Field(..., alias="onContentLoad") on_load: conint(strict=True, ge=-1) = Field(..., alias="onLoad") - href: Optional[StrictStr] = Field('', alias="_href") + href: Optional[StrictStr] = Field("", alias="_href") dns: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_dns") ssl: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_ssl") - time_to_first_byte: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_timeToFirstByte") - cumulative_layout_shift: Optional[Union[confloat(ge=-1, strict=True), conint(ge=-1, strict=True)]] = Field(-1, alias="_cumulativeLayoutShift") - largest_contentful_paint: Optional[LargestContentfulPaint] = Field(None, alias="_largestContentfulPaint") + time_to_first_byte: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_timeToFirstByte" + ) + cumulative_layout_shift: Optional[ + Union[confloat(ge=-1, strict=True), conint(ge=-1, strict=True)] + ] = Field(-1, alias="_cumulativeLayoutShift") + largest_contentful_paint: Optional[LargestContentfulPaint] = Field( + None, alias="_largestContentfulPaint" + ) first_paint: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_firstPaint") - first_input_delay: Optional[Union[confloat(ge=-1, strict=True), conint(ge=-1, strict=True)]] = Field(-1, alias="_firstInputDelay") - dom_interactive: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_domInteractive") - first_contentful_paint: Optional[conint(strict=True, ge=-1)] = Field(-1, alias="_firstContentfulPaint") + first_input_delay: Optional[ + Union[confloat(ge=-1, strict=True), conint(ge=-1, strict=True)] + ] = Field(-1, alias="_firstInputDelay") + dom_interactive: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_domInteractive" + ) + first_contentful_paint: Optional[conint(strict=True, ge=-1)] = Field( + -1, alias="_firstContentfulPaint" + ) comment: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} - __properties = ["onContentLoad", "onLoad", "_href", "_dns", "_ssl", "_timeToFirstByte", "_cumulativeLayoutShift", "_largestContentfulPaint", "_firstPaint", "_firstInputDelay", "_domInteractive", "_firstContentfulPaint", "comment"] + __properties = [ + "onContentLoad", + "onLoad", + "_href", + "_dns", + "_ssl", + "_timeToFirstByte", + "_cumulativeLayoutShift", + "_largestContentfulPaint", + "_firstPaint", + "_firstInputDelay", + "_domInteractive", + "_firstContentfulPaint", + "comment", + ] class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -63,14 +99,12 @@ def from_json(cls, json_str: str) -> PageTimings: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - "additional_properties" - }, - exclude_none=True) + _dict = self.dict( + by_alias=True, exclude={"additional_properties"}, exclude_none=True + ) # override the default output from pydantic by calling `to_dict()` of largest_contentful_paint if self.largest_contentful_paint: - _dict['_largestContentfulPaint'] = self.largest_contentful_paint.to_dict() + _dict["_largestContentfulPaint"] = self.largest_contentful_paint.to_dict() # puts key-value pairs in additional_properties in the top level if self.additional_properties is not None: for _key, _value in self.additional_properties.items(): @@ -87,26 +121,44 @@ def from_dict(cls, obj: dict) -> PageTimings: if not isinstance(obj, dict): return PageTimings.parse_obj(obj) - _obj = PageTimings.parse_obj({ - "on_content_load": obj.get("onContentLoad") if obj.get("onContentLoad") is not None else -1, - "on_load": obj.get("onLoad") if obj.get("onLoad") is not None else -1, - "href": obj.get("_href") if obj.get("_href") is not None else '', - "dns": obj.get("_dns") if obj.get("_dns") is not None else -1, - "ssl": obj.get("_ssl") if obj.get("_ssl") is not None else -1, - "time_to_first_byte": obj.get("_timeToFirstByte") if obj.get("_timeToFirstByte") is not None else -1, - "cumulative_layout_shift": obj.get("_cumulativeLayoutShift") if obj.get("_cumulativeLayoutShift") is not None else -1, - "largest_contentful_paint": LargestContentfulPaint.from_dict(obj.get("_largestContentfulPaint")) if obj.get("_largestContentfulPaint") is not None else None, - "first_paint": obj.get("_firstPaint") if obj.get("_firstPaint") is not None else -1, - "first_input_delay": obj.get("_firstInputDelay") if obj.get("_firstInputDelay") is not None else -1, - "dom_interactive": obj.get("_domInteractive") if obj.get("_domInteractive") is not None else -1, - "first_contentful_paint": obj.get("_firstContentfulPaint") if obj.get("_firstContentfulPaint") is not None else -1, - "comment": obj.get("comment") - }) + _obj = PageTimings.parse_obj( + { + "on_content_load": obj.get("onContentLoad") + if obj.get("onContentLoad") is not None + else -1, + "on_load": obj.get("onLoad") if obj.get("onLoad") is not None else -1, + "href": obj.get("_href") if obj.get("_href") is not None else "", + "dns": obj.get("_dns") if obj.get("_dns") is not None else -1, + "ssl": obj.get("_ssl") if obj.get("_ssl") is not None else -1, + "time_to_first_byte": obj.get("_timeToFirstByte") + if obj.get("_timeToFirstByte") is not None + else -1, + "cumulative_layout_shift": obj.get("_cumulativeLayoutShift") + if obj.get("_cumulativeLayoutShift") is not None + else -1, + "largest_contentful_paint": LargestContentfulPaint.from_dict( + obj.get("_largestContentfulPaint") + ) + if obj.get("_largestContentfulPaint") is not None + else None, + "first_paint": obj.get("_firstPaint") + if obj.get("_firstPaint") is not None + else -1, + "first_input_delay": obj.get("_firstInputDelay") + if obj.get("_firstInputDelay") is not None + else -1, + "dom_interactive": obj.get("_domInteractive") + if obj.get("_domInteractive") is not None + else -1, + "first_contentful_paint": obj.get("_firstContentfulPaint") + if obj.get("_firstContentfulPaint") is not None + else -1, + "comment": obj.get("comment"), + } + ) # store additional fields in additional_properties for _key in obj.keys(): if _key not in cls.__properties: _obj.additional_properties[_key] = obj.get(_key) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/verify_result.py b/clients/python/BrowserUpMitmProxyClient/models/verify_result.py index 7562a77d8b..e41a2b4115 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/verify_result.py +++ b/clients/python/BrowserUpMitmProxyClient/models/verify_result.py @@ -1,31 +1,35 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Optional +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictBool +from pydantic import StrictStr -from typing import Optional -from pydantic import BaseModel, Field, StrictBool, StrictStr class VerifyResult(BaseModel): """ VerifyResult """ + result: Optional[StrictBool] = Field(None, description="Result True / False") name: Optional[StrictStr] = Field(None, description="Name") type: Optional[StrictStr] = Field(None, description="Type") @@ -33,6 +37,7 @@ class VerifyResult(BaseModel): class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -51,10 +56,7 @@ def from_json(cls, json_str: str) -> VerifyResult: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -66,11 +68,11 @@ def from_dict(cls, obj: dict) -> VerifyResult: if not isinstance(obj, dict): return VerifyResult.parse_obj(obj) - _obj = VerifyResult.parse_obj({ - "result": obj.get("result"), - "name": obj.get("name"), - "type": obj.get("type") - }) + _obj = VerifyResult.parse_obj( + { + "result": obj.get("result"), + "name": obj.get("name"), + "type": obj.get("type"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/models/web_socket_message.py b/clients/python/BrowserUpMitmProxyClient/models/web_socket_message.py index ad7dfd4942..536410c14e 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/web_socket_message.py +++ b/clients/python/BrowserUpMitmProxyClient/models/web_socket_message.py @@ -1,31 +1,36 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - from __future__ import annotations + +import json import pprint import re # noqa: F401 -import json +from typing import Union +from pydantic import BaseModel +from pydantic import Field +from pydantic import StrictFloat +from pydantic import StrictInt +from pydantic import StrictStr -from typing import Union -from pydantic import BaseModel, Field, StrictFloat, StrictInt, StrictStr class WebSocketMessage(BaseModel): """ WebSocketMessage """ + type: StrictStr = Field(...) opcode: Union[StrictFloat, StrictInt] = Field(...) data: StrictStr = Field(...) @@ -34,6 +39,7 @@ class WebSocketMessage(BaseModel): class Config: """Pydantic configuration""" + allow_population_by_field_name = True validate_assignment = True @@ -52,10 +58,7 @@ def from_json(cls, json_str: str) -> WebSocketMessage: def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.dict(by_alias=True, - exclude={ - }, - exclude_none=True) + _dict = self.dict(by_alias=True, exclude={}, exclude_none=True) return _dict @classmethod @@ -67,12 +70,12 @@ def from_dict(cls, obj: dict) -> WebSocketMessage: if not isinstance(obj, dict): return WebSocketMessage.parse_obj(obj) - _obj = WebSocketMessage.parse_obj({ - "type": obj.get("type"), - "opcode": obj.get("opcode"), - "data": obj.get("data"), - "time": obj.get("time") - }) + _obj = WebSocketMessage.parse_obj( + { + "type": obj.get("type"), + "opcode": obj.get("opcode"), + "data": obj.get("data"), + "time": obj.get("time"), + } + ) return _obj - - diff --git a/clients/python/BrowserUpMitmProxyClient/rest.py b/clients/python/BrowserUpMitmProxyClient/rest.py index 82f2313e09..06c1fdebb7 100644 --- a/clients/python/BrowserUpMitmProxyClient/rest.py +++ b/clients/python/BrowserUpMitmProxyClient/rest.py @@ -1,35 +1,37 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import io import json import logging import re import ssl -from urllib.parse import urlencode, quote_plus import urllib3 -from BrowserUpMitmProxyClient.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, BadRequestException - +from BrowserUpMitmProxyClient.exceptions import ApiException +from BrowserUpMitmProxyClient.exceptions import ApiValueError +from BrowserUpMitmProxyClient.exceptions import BadRequestException +from BrowserUpMitmProxyClient.exceptions import ForbiddenException +from BrowserUpMitmProxyClient.exceptions import NotFoundException +from BrowserUpMitmProxyClient.exceptions import ServiceException +from BrowserUpMitmProxyClient.exceptions import UnauthorizedException logger = logging.getLogger(__name__) class RESTResponse(io.IOBase): - def __init__(self, resp): self.urllib3_response = resp self.status = resp.status @@ -46,7 +48,6 @@ def getheader(self, name, default=None): class RESTClientObject(object): - def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 @@ -62,17 +63,16 @@ def __init__(self, configuration, pools_size=4, maxsize=None): addition_pool_args = {} if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + addition_pool_args["assert_hostname"] = configuration.assert_hostname # noqa: E501 if configuration.retries is not None: - addition_pool_args['retries'] = configuration.retries + addition_pool_args["retries"] = configuration.retries if configuration.tls_server_name: - addition_pool_args['server_hostname'] = configuration.tls_server_name - + addition_pool_args["server_hostname"] = configuration.tls_server_name if configuration.socket_options is not None: - addition_pool_args['socket_options'] = configuration.socket_options + addition_pool_args["socket_options"] = configuration.socket_options if maxsize is None: if configuration.connection_pool_maxsize is not None: @@ -91,7 +91,7 @@ def __init__(self, configuration, pools_size=4, maxsize=None): key_file=configuration.key_file, proxy_url=configuration.proxy, proxy_headers=configuration.proxy_headers, - **addition_pool_args + **addition_pool_args, ) else: self.pool_manager = urllib3.PoolManager( @@ -101,12 +101,20 @@ def __init__(self, configuration, pools_size=4, maxsize=None): ca_certs=configuration.ssl_ca_cert, cert_file=configuration.cert_file, key_file=configuration.key_file, - **addition_pool_args + **addition_pool_args, ) - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): + def request( + self, + method, + url, + query_params=None, + headers=None, + body=None, + post_params=None, + _preload_content=True, + _request_timeout=None, + ): """Perform requests. :param method: http request method @@ -126,8 +134,7 @@ def request(self, method, url, query_params=None, headers=None, (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] + assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"] if post_params and body: raise ApiValueError( @@ -142,59 +149,68 @@ def request(self, method, url, query_params=None, headers=None, timeout = None if _request_timeout: - if isinstance(_request_timeout, (int,float)): # noqa: E501,F821 + if isinstance(_request_timeout, (int, float)): # noqa: E501,F821 timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): + elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) + connect=_request_timeout[0], read=_request_timeout[1] + ) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - + if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: # no content type provided or payload is json - if not headers.get('Content-Type') or re.search('json', headers['Content-Type'], re.IGNORECASE): + if not headers.get("Content-Type") or re.search( + "json", headers["Content-Type"], re.IGNORECASE + ): request_body = None if body is not None: request_body = json.dumps(body) r = self.pool_manager.request( - method, url, + method, + url, body=request_body, preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + headers=headers, + ) + elif headers["Content-Type"] == "application/x-www-form-urlencoded": # noqa: E501 r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=False, preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': + headers=headers, + ) + elif headers["Content-Type"] == "multipart/form-data": # must del headers['Content-Type'], or the correct # Content-Type which generated by urllib3 will be # overwritten. - del headers['Content-Type'] + del headers["Content-Type"] r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=True, preload_content=_preload_content, timeout=timeout, - headers=headers) + headers=headers, + ) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is # provided in serialized form elif isinstance(body, str) or isinstance(body, bytes): request_body = body r = self.pool_manager.request( - method, url, + method, + url, body=request_body, preload_content=_preload_content, timeout=timeout, - headers=headers) + headers=headers, + ) else: # Cannot generate the request from given parameters msg = """Cannot prepare a request message for provided @@ -203,11 +219,14 @@ def request(self, method, url, query_params=None, headers=None, raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: - r = self.pool_manager.request(method, url, - fields={}, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, + url, + fields={}, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) @@ -238,67 +257,139 @@ def request(self, method, url, query_params=None, headers=None, return r - def get_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def head_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def options_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def delete_request(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def post_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def put_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def patch_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + def get_request( + self, + url, + headers=None, + query_params=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "GET", + url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params, + ) + + def head_request( + self, + url, + headers=None, + query_params=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "HEAD", + url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params, + ) + + def options_request( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "OPTIONS", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def delete_request( + self, + url, + headers=None, + query_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "DELETE", + url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def post_request( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "POST", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def put_request( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "PUT", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def patch_request( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "PATCH", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) diff --git a/clients/python/setup.py b/clients/python/setup.py index f44ccea627..29f8042373 100644 --- a/clients/python/setup.py +++ b/clients/python/setup.py @@ -1,19 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - -from setuptools import setup, find_packages # noqa: H301 +from setuptools import find_packages # noqa: H301 +from setuptools import setup # noqa: H301 # To install the library, run the following # @@ -28,7 +28,7 @@ "urllib3 >= 1.25.3, < 2.1.0", "python-dateutil", "pydantic >= 1.10.5, < 2", - "aenum" + "aenum", ] setup( @@ -42,7 +42,7 @@ install_requires=REQUIRES, packages=find_packages(exclude=["test", "tests"]), include_package_data=True, - long_description_content_type='text/markdown', + long_description_content_type="text/markdown", long_description="""\ ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ """, # noqa: E501 diff --git a/clients/python/test/test_action.py b/clients/python/test/test_action.py index 681755cfe1..0c8ca4f768 100644 --- a/clients/python/test/test_action.py +++ b/clients/python/test/test_action.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.action import Action # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestAction(unittest.TestCase): """Action unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test Action - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `Action` """ model = BrowserUpMitmProxyClient.models.action.Action() # noqa: E501 @@ -58,5 +53,6 @@ def testAction(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_browser_up_proxy_api.py b/clients/python/test/test_browser_up_proxy_api.py index 78f9b041d6..7f20ed2431 100644 --- a/clients/python/test/test_browser_up_proxy_api.py +++ b/clients/python/test/test_browser_up_proxy_api.py @@ -1,23 +1,20 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.api.browser_up_proxy_api import BrowserUpProxyApi # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestBrowserUpProxyApi(unittest.TestCase): @@ -30,65 +27,45 @@ def tearDown(self): pass def test_add_counter(self): - """Test case for add_counter - - """ + """Test case for add_counter""" pass def test_add_error(self): - """Test case for add_error - - """ + """Test case for add_error""" pass def test_get_har_log(self): - """Test case for get_har_log - - """ + """Test case for get_har_log""" pass def test_healthcheck(self): - """Test case for healthcheck - - """ + """Test case for healthcheck""" pass def test_new_page(self): - """Test case for new_page - - """ + """Test case for new_page""" pass def test_reset_har_log(self): - """Test case for reset_har_log - - """ + """Test case for reset_har_log""" pass def test_verify_not_present(self): - """Test case for verify_not_present - - """ + """Test case for verify_not_present""" pass def test_verify_present(self): - """Test case for verify_present - - """ + """Test case for verify_present""" pass def test_verify_size(self): - """Test case for verify_size - - """ + """Test case for verify_size""" pass def test_verify_sla(self): - """Test case for verify_sla - - """ + """Test case for verify_sla""" pass -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_counter.py b/clients/python/test/test_counter.py index 5e2a47264a..d33025fef0 100644 --- a/clients/python/test/test_counter.py +++ b/clients/python/test/test_counter.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.counter import Counter # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestCounter(unittest.TestCase): """Counter unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test Counter - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `Counter` """ model = BrowserUpMitmProxyClient.models.counter.Counter() # noqa: E501 @@ -52,5 +47,6 @@ def testCounter(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_error.py b/clients/python/test/test_error.py index cc47357948..7455e5dedc 100644 --- a/clients/python/test/test_error.py +++ b/clients/python/test/test_error.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.error import Error # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestError(unittest.TestCase): """Error unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test Error - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `Error` """ model = BrowserUpMitmProxyClient.models.error.Error() # noqa: E501 @@ -52,5 +47,6 @@ def testError(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har.py b/clients/python/test/test_har.py index bb6b08cf52..8b54cd4424 100644 --- a/clients/python/test/test_har.py +++ b/clients/python/test/test_har.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har import Har # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHar(unittest.TestCase): """Har unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test Har - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `Har` """ model = BrowserUpMitmProxyClient.models.har.Har() # noqa: E501 @@ -160,5 +155,6 @@ def testHar(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry.py b/clients/python/test/test_har_entry.py index 992812d57b..5358313cf2 100644 --- a/clients/python/test/test_har_entry.py +++ b/clients/python/test/test_har_entry.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry import HarEntry # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntry(unittest.TestCase): """HarEntry unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntry - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntry` """ model = BrowserUpMitmProxyClient.models.har_entry.HarEntry() # noqa: E501 @@ -115,5 +110,6 @@ def testHarEntry(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry_cache.py b/clients/python/test/test_har_entry_cache.py index 297ae25f58..a1944cce92 100644 --- a/clients/python/test/test_har_entry_cache.py +++ b/clients/python/test/test_har_entry_cache.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry_cache import HarEntryCache # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntryCache(unittest.TestCase): """HarEntryCache unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntryCache - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntryCache` """ model = BrowserUpMitmProxyClient.models.har_entry_cache.HarEntryCache() # noqa: E501 @@ -63,5 +58,6 @@ def testHarEntryCache(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry_cache_before_request.py b/clients/python/test/test_har_entry_cache_before_request.py index a28b57a563..a507bb8a42 100644 --- a/clients/python/test/test_har_entry_cache_before_request.py +++ b/clients/python/test/test_har_entry_cache_before_request.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry_cache_before_request import HarEntryCacheBeforeRequest # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntryCacheBeforeRequest(unittest.TestCase): """HarEntryCacheBeforeRequest unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntryCacheBeforeRequest - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntryCacheBeforeRequest` """ model = BrowserUpMitmProxyClient.models.har_entry_cache_before_request.HarEntryCacheBeforeRequest() # noqa: E501 @@ -58,5 +53,6 @@ def testHarEntryCacheBeforeRequest(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry_request.py b/clients/python/test/test_har_entry_request.py index 5fe71fa484..cd650a6251 100644 --- a/clients/python/test/test_har_entry_request.py +++ b/clients/python/test/test_har_entry_request.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry_request import HarEntryRequest # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntryRequest(unittest.TestCase): """HarEntryRequest unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntryRequest - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntryRequest` """ model = BrowserUpMitmProxyClient.models.har_entry_request.HarEntryRequest() # noqa: E501 @@ -118,5 +113,6 @@ def testHarEntryRequest(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry_request_cookies_inner.py b/clients/python/test/test_har_entry_request_cookies_inner.py index f90f202fc7..2484c87214 100644 --- a/clients/python/test/test_har_entry_request_cookies_inner.py +++ b/clients/python/test/test_har_entry_request_cookies_inner.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry_request_cookies_inner import HarEntryRequestCookiesInner # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntryRequestCookiesInner(unittest.TestCase): """HarEntryRequestCookiesInner unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntryRequestCookiesInner - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntryRequestCookiesInner` """ model = BrowserUpMitmProxyClient.models.har_entry_request_cookies_inner.HarEntryRequestCookiesInner() # noqa: E501 @@ -60,5 +55,6 @@ def testHarEntryRequestCookiesInner(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry_request_post_data.py b/clients/python/test/test_har_entry_request_post_data.py index 30d9d6a54c..72d0520412 100644 --- a/clients/python/test/test_har_entry_request_post_data.py +++ b/clients/python/test/test_har_entry_request_post_data.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry_request_post_data import HarEntryRequestPostData # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntryRequestPostData(unittest.TestCase): """HarEntryRequestPostData unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntryRequestPostData - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntryRequestPostData` """ model = BrowserUpMitmProxyClient.models.har_entry_request_post_data.HarEntryRequestPostData() # noqa: E501 @@ -61,5 +56,6 @@ def testHarEntryRequestPostData(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry_request_post_data_params_inner.py b/clients/python/test/test_har_entry_request_post_data_params_inner.py index 1a0d1b38a7..502660650a 100644 --- a/clients/python/test/test_har_entry_request_post_data_params_inner.py +++ b/clients/python/test/test_har_entry_request_post_data_params_inner.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry_request_post_data_params_inner import HarEntryRequestPostDataParamsInner # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntryRequestPostDataParamsInner(unittest.TestCase): """HarEntryRequestPostDataParamsInner unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntryRequestPostDataParamsInner - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntryRequestPostDataParamsInner` """ model = BrowserUpMitmProxyClient.models.har_entry_request_post_data_params_inner.HarEntryRequestPostDataParamsInner() # noqa: E501 @@ -55,5 +50,6 @@ def testHarEntryRequestPostDataParamsInner(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry_request_query_string_inner.py b/clients/python/test/test_har_entry_request_query_string_inner.py index b8735c38fc..4b6b27ddb8 100644 --- a/clients/python/test/test_har_entry_request_query_string_inner.py +++ b/clients/python/test/test_har_entry_request_query_string_inner.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry_request_query_string_inner import HarEntryRequestQueryStringInner # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntryRequestQueryStringInner(unittest.TestCase): """HarEntryRequestQueryStringInner unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntryRequestQueryStringInner - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntryRequestQueryStringInner` """ model = BrowserUpMitmProxyClient.models.har_entry_request_query_string_inner.HarEntryRequestQueryStringInner() # noqa: E501 @@ -55,5 +50,6 @@ def testHarEntryRequestQueryStringInner(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry_response.py b/clients/python/test/test_har_entry_response.py index 31e2abc715..8643dec4ac 100644 --- a/clients/python/test/test_har_entry_response.py +++ b/clients/python/test/test_har_entry_response.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry_response import HarEntryResponse # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntryResponse(unittest.TestCase): """HarEntryResponse unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntryResponse - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntryResponse` """ model = BrowserUpMitmProxyClient.models.har_entry_response.HarEntryResponse() # noqa: E501 @@ -119,5 +114,6 @@ def testHarEntryResponse(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry_response_content.py b/clients/python/test/test_har_entry_response_content.py index 17662dea99..be9071ffaa 100644 --- a/clients/python/test/test_har_entry_response_content.py +++ b/clients/python/test/test_har_entry_response_content.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry_response_content import HarEntryResponseContent # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntryResponseContent(unittest.TestCase): """HarEntryResponseContent unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntryResponseContent - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntryResponseContent` """ model = BrowserUpMitmProxyClient.models.har_entry_response_content.HarEntryResponseContent() # noqa: E501 @@ -58,5 +53,6 @@ def testHarEntryResponseContent(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_entry_timings.py b/clients/python/test/test_har_entry_timings.py index d7ba849136..3949478dc7 100644 --- a/clients/python/test/test_har_entry_timings.py +++ b/clients/python/test/test_har_entry_timings.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_entry_timings import HarEntryTimings # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarEntryTimings(unittest.TestCase): """HarEntryTimings unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarEntryTimings - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarEntryTimings` """ model = BrowserUpMitmProxyClient.models.har_entry_timings.HarEntryTimings() # noqa: E501 @@ -65,5 +60,6 @@ def testHarEntryTimings(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_log.py b/clients/python/test/test_har_log.py index 66e88550ab..6b82a9a2ed 100644 --- a/clients/python/test/test_har_log.py +++ b/clients/python/test/test_har_log.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_log import HarLog # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarLog(unittest.TestCase): """HarLog unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarLog - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarLog` """ model = BrowserUpMitmProxyClient.models.har_log.HarLog() # noqa: E501 @@ -153,5 +148,6 @@ def testHarLog(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_har_log_creator.py b/clients/python/test/test_har_log_creator.py index f947c8defe..41aeeffeb5 100644 --- a/clients/python/test/test_har_log_creator.py +++ b/clients/python/test/test_har_log_creator.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.har_log_creator import HarLogCreator # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHarLogCreator(unittest.TestCase): """HarLogCreator unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test HarLogCreator - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `HarLogCreator` """ model = BrowserUpMitmProxyClient.models.har_log_creator.HarLogCreator() # noqa: E501 @@ -55,5 +50,6 @@ def testHarLogCreator(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_header.py b/clients/python/test/test_header.py index 4f0fdaffc1..3e293db2c2 100644 --- a/clients/python/test/test_header.py +++ b/clients/python/test/test_header.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.header import Header # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestHeader(unittest.TestCase): """Header unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test Header - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `Header` """ model = BrowserUpMitmProxyClient.models.header.Header() # noqa: E501 @@ -55,5 +50,6 @@ def testHeader(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_largest_contentful_paint.py b/clients/python/test/test_largest_contentful_paint.py index 4201d20c91..c9a9aab0ef 100644 --- a/clients/python/test/test_largest_contentful_paint.py +++ b/clients/python/test/test_largest_contentful_paint.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.largest_contentful_paint import LargestContentfulPaint # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestLargestContentfulPaint(unittest.TestCase): """LargestContentfulPaint unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test LargestContentfulPaint - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `LargestContentfulPaint` """ model = BrowserUpMitmProxyClient.models.largest_contentful_paint.LargestContentfulPaint() # noqa: E501 @@ -54,5 +49,6 @@ def testLargestContentfulPaint(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_match_criteria.py b/clients/python/test/test_match_criteria.py index 1f025273aa..8fa7c9fcf4 100644 --- a/clients/python/test/test_match_criteria.py +++ b/clients/python/test/test_match_criteria.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.match_criteria import MatchCriteria # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestMatchCriteria(unittest.TestCase): """MatchCriteria unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test MatchCriteria - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `MatchCriteria` """ model = BrowserUpMitmProxyClient.models.match_criteria.MatchCriteria() # noqa: E501 @@ -72,5 +67,6 @@ def testMatchCriteria(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_name_value_pair.py b/clients/python/test/test_name_value_pair.py index 944c3efeb9..30ca2a3abe 100644 --- a/clients/python/test/test_name_value_pair.py +++ b/clients/python/test/test_name_value_pair.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.name_value_pair import NameValuePair # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestNameValuePair(unittest.TestCase): """NameValuePair unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test NameValuePair - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `NameValuePair` """ model = BrowserUpMitmProxyClient.models.name_value_pair.NameValuePair() # noqa: E501 @@ -52,5 +47,6 @@ def testNameValuePair(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_page.py b/clients/python/test/test_page.py index fc985ff85d..34b0535ec0 100644 --- a/clients/python/test/test_page.py +++ b/clients/python/test/test_page.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.page import Page # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestPage(unittest.TestCase): """Page unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test Page - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `Page` """ model = BrowserUpMitmProxyClient.models.page.Page() # noqa: E501 @@ -75,5 +70,6 @@ def testPage(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_page_timing.py b/clients/python/test/test_page_timing.py index d210512ff9..829c20113f 100644 --- a/clients/python/test/test_page_timing.py +++ b/clients/python/test/test_page_timing.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.page_timing import PageTiming # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestPageTiming(unittest.TestCase): """PageTiming unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test PageTiming - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `PageTiming` """ model = BrowserUpMitmProxyClient.models.page_timing.PageTiming() # noqa: E501 @@ -62,5 +57,6 @@ def testPageTiming(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_page_timings.py b/clients/python/test/test_page_timings.py index 2a0759f9d6..94f9060ffc 100644 --- a/clients/python/test/test_page_timings.py +++ b/clients/python/test/test_page_timings.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.page_timings import PageTimings # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestPageTimings(unittest.TestCase): """PageTimings unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test PageTimings - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `PageTimings` """ model = BrowserUpMitmProxyClient.models.page_timings.PageTimings() # noqa: E501 @@ -65,5 +60,6 @@ def testPageTimings(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_verify_result.py b/clients/python/test/test_verify_result.py index 8d6b009cd2..f30601e95f 100644 --- a/clients/python/test/test_verify_result.py +++ b/clients/python/test/test_verify_result.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.verify_result import VerifyResult # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestVerifyResult(unittest.TestCase): """VerifyResult unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test VerifyResult - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `VerifyResult` """ model = BrowserUpMitmProxyClient.models.verify_result.VerifyResult() # noqa: E501 @@ -53,5 +48,6 @@ def testVerifyResult(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/clients/python/test/test_web_socket_message.py b/clients/python/test/test_web_socket_message.py index 008ec0aea8..66b88bfbc8 100644 --- a/clients/python/test/test_web_socket_message.py +++ b/clients/python/test/test_web_socket_message.py @@ -1,24 +1,19 @@ # coding: utf-8 """ - BrowserUp MitmProxy +BrowserUp MitmProxy - ___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ +___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ - The version of the OpenAPI document: 1.0.0 - Contact: developers@browserup.com - Generated by OpenAPI Generator (https://openapi-generator.tech) +The version of the OpenAPI document: 1.0.0 +Contact: developers@browserup.com +Generated by OpenAPI Generator (https://openapi-generator.tech) - Do not edit the class manually. +Do not edit the class manually. """ # noqa: E501 - import unittest -import datetime -import BrowserUpMitmProxyClient -from BrowserUpMitmProxyClient.models.web_socket_message import WebSocketMessage # noqa: E501 -from BrowserUpMitmProxyClient.rest import ApiException class TestWebSocketMessage(unittest.TestCase): """WebSocketMessage unit test stubs""" @@ -31,9 +26,9 @@ def tearDown(self): def make_instance(self, include_optional): """Test WebSocketMessage - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included""" # uncomment below to create an instance of `WebSocketMessage` """ model = BrowserUpMitmProxyClient.models.web_socket_message.WebSocketMessage() # noqa: E501 @@ -58,5 +53,6 @@ def testWebSocketMessage(self): # inst_req_only = self.make_instance(include_optional=False) # inst_req_and_optional = self.make_instance(include_optional=True) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() diff --git a/mitmproxy/addons/browserup/browser_data_addon.py b/mitmproxy/addons/browserup/browser_data_addon.py index 74ea9e061f..f6cf639013 100644 --- a/mitmproxy/addons/browserup/browser_data_addon.py +++ b/mitmproxy/addons/browserup/browser_data_addon.py @@ -12,20 +12,23 @@ # Inject a script into browser-responses for html that lets us get DOM timings, first paint time, and other metrics. class BrowserDataAddOn: - def __init__(self, har_capture_addon): self.handshaked = False file_dir = pathlib.Path(__file__).parent.parent.parent.parent.resolve() - filepath = os.path.normpath(os.path.join(file_dir, "scripts/browsertime/browser-data.min.js")) - with open(filepath, 'r') as file: - self.browser_data_script = f'' + filepath = os.path.normpath( + os.path.join(file_dir, "scripts/browsertime/browser-data.min.js") + ) + with open(filepath, "r") as file: + self.browser_data_script = ( + f"" + ) self.browser_data_script_len = len(self.browser_data_script) self.HarCaptureAddon = har_capture_addon def websocket_message(self, f: mitmproxy.http.HTTPFlow): - logging.info(f'websocket_message: {f.request.url}') + logging.info(f"websocket_message: {f.request.url}") assert f.websocket is not None - if 'BrowserUpData' in f.request.url: + if "BrowserUpData" in f.request.url: message = f.websocket.messages[-1] content = message.content message.drop() @@ -38,10 +41,10 @@ def websocket_message(self, f: mitmproxy.http.HTTPFlow): logging.error("Invalid JSON string") def request(self, f: mitmproxy.http.HTTPFlow): - logging.info(f'request: {f.request.url}') - if 'BrowserUpData' in f.request.url: + logging.info(f"request: {f.request.url}") + if "BrowserUpData" in f.request.url: # Generate the handshake response - websocket_key = f.request.headers.get('Sec-WebSocket-Key', '') + websocket_key = f.request.headers.get("Sec-WebSocket-Key", "") websocket_accept = self._compute_websocket_accept_value(websocket_key) response_headers = ( (b"Upgrade", b"websocket"), @@ -61,7 +64,7 @@ def request(self, f: mitmproxy.http.HTTPFlow): content=b"", trailers=(), timestamp_start=timestamp_start, - timestamp_end=timestamp_end + timestamp_end=timestamp_end, ) f.server_conn.timestamp_start = None @@ -72,15 +75,15 @@ def response(self, f: mitmproxy.http.HTTPFlow): def _inject_data_script(self, f: mitmproxy.http.HTTPFlow): assert f.response is not None assert f.response.content is not None - html = f.response.content.decode('utf-8') + html = f.response.content.decode("utf-8") # html = re.sub('(?i)]+content-security-policy[^>]+>', '', html) - html = re.sub(' # if we don't delete this, customer pages may be cranky about the script - if 'content-security-policy' in f.response.headers: - del f.response.headers['content-security-policy'] + if "content-security-policy" in f.response.headers: + del f.response.headers["content-security-policy"] f.response.text = html @@ -90,21 +93,31 @@ def _is_full_html_page(self, f: mitmproxy.http.HTTPFlow): logging.info("Evaluating injection false for content") return False - if f.response.status_code != 200 or f.request.method not in ['GET', 'POST', 'PUT']: + if f.response.status_code != 200 or f.request.method not in [ + "GET", + "POST", + "PUT", + ]: logging.info("Evaluating injection for response false for meth or code") return False - if "content-type" in f.response.headers and "text/html" not in f.response.headers["content-type"]: + if ( + "content-type" in f.response.headers + and "text/html" not in f.response.headers["content-type"] + ): logging.info("Evaluating injection for response false for content type") return False - if "content-length" in f.response.headers and int(f.response.headers["content-length"]) < 100: + if ( + "content-length" in f.response.headers + and int(f.response.headers["content-length"]) < 100 + ): logging.info("Evaluating injection for response false for content length") return False - html = f.response.content.decode('utf-8', 'ignore') + html = f.response.content.decode("utf-8", "ignore") logging.info("Evaluating injection for response false for raw len") - if (len(html) < 100): + if len(html) < 100: return False if " str: magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" combined = key + magic_string - accept_value = base64.b64encode(hashlib.sha1(combined.encode()).digest()).decode('utf-8') + accept_value = base64.b64encode( + hashlib.sha1(combined.encode()).digest() + ).decode("utf-8") return accept_value diff --git a/mitmproxy/addons/browserup/browserup_addons_manager.py b/mitmproxy/addons/browserup/browserup_addons_manager.py index 7e38d3ace8..db2659e5ab 100644 --- a/mitmproxy/addons/browserup/browserup_addons_manager.py +++ b/mitmproxy/addons/browserup/browserup_addons_manager.py @@ -14,40 +14,40 @@ from mitmproxy import ctx from mitmproxy.addons.browserup.browser_data_addon import BrowserDataAddOn -from mitmproxy.addons.browserup.har.har_schemas import (CounterSchema, - ErrorSchema, - MatchCriteriaSchema, - PageTimingSchema, - VerifyResultSchema) +from mitmproxy.addons.browserup.har.har_schemas import CounterSchema +from mitmproxy.addons.browserup.har.har_schemas import ErrorSchema +from mitmproxy.addons.browserup.har.har_schemas import MatchCriteriaSchema +from mitmproxy.addons.browserup.har.har_schemas import PageTimingSchema +from mitmproxy.addons.browserup.har.har_schemas import VerifyResultSchema from mitmproxy.addons.browserup.har_capture_addon import HarCaptureAddOn # https://marshmallow.readthedocs.io/en/stable/quickstart.html -VERSION = '1.24' +VERSION = "1.24" class BrowserUpAddonsManagerAddOn: initialized = False def load(self, l): - logging.info('Loading BrowserUpAddonsManagerAddOn') - logging.info('Version {}'.format(VERSION)) + logging.info("Loading BrowserUpAddonsManagerAddOn") + logging.info("Version {}".format(VERSION)) - ctx.options.update(listen_port = 48080) + ctx.options.update(listen_port=48080) l.add_option( name="addons_management_port", typespec=Optional[int], default=48088, - help= "REST api management port.", + help="REST api management port.", ) def running(self): - logging.info('Scanning for custom add-ons resources...') + logging.info("Scanning for custom add-ons resources...") global initialized if not self.initialized and self.is_script_loader_initialized(): - logging.info('Scanning for custom add-ons resources...') - logging.info('Starting falcon REST service...') + logging.info("Scanning for custom add-ons resources...") + logging.info("Starting falcon REST service...") _thread.start_new_thread(self.start_falcon, ()) initialized = True @@ -62,21 +62,31 @@ def is_script_loader_initialized(self): def basic_spec(self, app): return APISpec( - title='BrowserUp MitmProxy', + title="BrowserUp MitmProxy", version=VERSION, - servers = [{"url": "http://localhost:{port}/", - "description": "The development API server", - "variables": {"port": {"enum": ["48088"], "default": '48088'}} - }], - tags = [{"name": 'The BrowserUp MitmProxy API', "description": "BrowserUp MitmProxy REST API"}], - info= {"description": - """___ + servers=[ + { + "url": "http://localhost:{port}/", + "description": "The development API server", + "variables": {"port": {"enum": ["48088"], "default": "48088"}}, + } + ], + tags=[ + { + "name": "The BrowserUp MitmProxy API", + "description": "BrowserUp MitmProxy REST API", + } + ], + info={ + "description": """___ This is the REST API for controlling the BrowserUp MitmProxy. The BrowserUp MitmProxy is a swiss army knife for automated testing that captures HTTP traffic in HAR files. It is also useful for Selenium/Cypress tests. ___ -""", "x-logo": {"url": "logo.png"}}, - openapi_version='3.0.3', +""", + "x-logo": {"url": "logo.png"}, + }, + openapi_version="3.0.3", plugins=[ FalconPlugin(app), MarshmallowPlugin(), @@ -86,8 +96,8 @@ def basic_spec(self, app): def write_spec(self, spec): pretty_json = json.dumps(spec.to_dict(), indent=2) root = Path(__file__).parent.parent.parent.parent - schema_path = os.path.join(root, 'browserup-proxy.schema.json') - f = open(schema_path, 'w') + schema_path = os.path.join(root, "browserup-proxy.schema.json") + f = open(schema_path, "w") f.write(pretty_json) f.close() @@ -103,7 +113,7 @@ def load_resources_from_addons(self, app, spec): for resource in addon_resources: route = "/" + resource.addon_path() app.add_route(route, resource) - if 'apispec' in dir(resource): + if "apispec" in dir(resource): resource.apispec(spec) resources.append(resource) return resources @@ -116,11 +126,11 @@ def get_app(self): app.req_options.auto_parse_form_urlencoded = True spec = self.basic_spec(app) - spec.components.schema('PageTiming', schema=PageTimingSchema) - spec.components.schema('MatchCriteria', schema=MatchCriteriaSchema) - spec.components.schema('VerifyResult', schema=VerifyResultSchema) - spec.components.schema('Error', schema=ErrorSchema) - spec.components.schema('Counter', schema=CounterSchema) + spec.components.schema("PageTiming", schema=PageTimingSchema) + spec.components.schema("MatchCriteria", schema=MatchCriteriaSchema) + spec.components.schema("VerifyResult", schema=VerifyResultSchema) + spec.components.schema("Error", schema=ErrorSchema) + spec.components.schema("Counter", schema=CounterSchema) self.load_resources_from_addons(app, spec) self.write_spec(spec) return app @@ -134,6 +144,7 @@ def get_children(node): get_children(child_node) else: routes_list.append((node.uri_template, node.resource)) + [get_children(node) for node in app._router._roots] return routes_list @@ -144,8 +155,12 @@ def start_falcon(self): app = self.get_app() print("Routes: ") print(self.get_all_routes(app)) - with make_server('', ctx.options.addons_management_port, app) as httpd: - print('Starting REST API management on port: {}'.format(ctx.options.addons_management_port)) + with make_server("", ctx.options.addons_management_port, app) as httpd: + print( + "Starting REST API management on port: {}".format( + ctx.options.addons_management_port + ) + ) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) httpd.serve_forever() @@ -156,5 +171,5 @@ def start_falcon(self): addons = [ har_capture_addon, BrowserDataAddOn(har_capture_addon), - BrowserUpAddonsManagerAddOn() + BrowserUpAddonsManagerAddOn(), ] diff --git a/mitmproxy/addons/browserup/har/flow_capture.py b/mitmproxy/addons/browserup/har/flow_capture.py index bdb76dde28..e03fb1ab3c 100644 --- a/mitmproxy/addons/browserup/har/flow_capture.py +++ b/mitmproxy/addons/browserup/har/flow_capture.py @@ -1,7 +1,8 @@ import base64 import logging import typing -from datetime import datetime, timezone +from datetime import datetime +from datetime import timezone from mitmproxy import connection from mitmproxy.addons.browserup.har.har_builder import HarBuilder @@ -16,51 +17,82 @@ REQUEST_SUBMITTED_FLAG = "_submitted" STATIC_MIME_TYPES = { - 'application/javascript', 'application/pdf', 'image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', - 'image/webp', 'image/bmp', 'image/tiff', 'audio/mpeg', 'audio/wav', 'audio/ogg', 'video/mp4', - 'video/webm', 'video/ogg', 'video/quicktime', 'font/woff', 'font/woff2', 'font/ttf', 'image/x-icon', - 'application/zip', 'application/x-rar-compressed', 'application/x-tar', 'application/x-7z-compressed', - 'application/octet-stream', 'application/x-shockwave-flash', 'text/css' + "application/javascript", + "application/pdf", + "image/jpeg", + "image/png", + "image/gif", + "image/svg+xml", + "image/webp", + "image/bmp", + "image/tiff", + "audio/mpeg", + "audio/wav", + "audio/ogg", + "video/mp4", + "video/webm", + "video/ogg", + "video/quicktime", + "font/woff", + "font/woff2", + "font/ttf", + "image/x-icon", + "application/zip", + "application/x-rar-compressed", + "application/x-tar", + "application/x-7z-compressed", + "application/octet-stream", + "application/x-shockwave-flash", + "text/css", } class FlowCaptureMixin(object): - def capture_request(self, flow): full_url = self.get_full_url(flow.request) - if 'BrowserUpData' in full_url or 'detectportal.firefox.com' in full_url: - logging.info('Ignored, capturing nothing.') + if "BrowserUpData" in full_url or "detectportal.firefox.com" in full_url: + logging.info("Ignored, capturing nothing.") return - logging.info('Populating har entry for request: {}'.format(full_url)) + logging.info("Populating har entry for request: {}".format(full_url)) har_entry = flow.get_har_entry() - har_entry['startedDateTime'] = datetime.fromtimestamp(flow.request.timestamp_start, timezone.utc).isoformat() + har_entry["startedDateTime"] = datetime.fromtimestamp( + flow.request.timestamp_start, timezone.utc + ).isoformat() - logging.info('Har startedDateTime for request: {} is {}'.format(full_url, har_entry['startedDateTime'])) + logging.info( + "Har startedDateTime for request: {} is {}".format( + full_url, har_entry["startedDateTime"] + ) + ) har_request = HarBuilder.entry_request() - har_request['method'] = flow.request.method - har_request['url'] = full_url - har_request['httpVersion'] = flow.request.http_version - har_request['queryString'] = self.name_value(flow.request.query or {}) - har_request['headersSize'] = len(str(flow.request.headers)) - - har_request['_updated'] = datetime.fromtimestamp(flow.request.timestamp_start, timezone.utc).isoformat() - - har_entry['request'] = har_request - req_url = 'none' + har_request["method"] = flow.request.method + har_request["url"] = full_url + har_request["httpVersion"] = flow.request.http_version + har_request["queryString"] = self.name_value(flow.request.query or {}) + har_request["headersSize"] = len(str(flow.request.headers)) + + har_request["_updated"] = datetime.fromtimestamp( + flow.request.timestamp_start, timezone.utc + ).isoformat() + + har_entry["request"] = har_request + req_url = "none" if flow.request is not None: req_url = flow.request.url - logging.info('Incoming request, url: {}'.format(req_url)) + logging.info("Incoming request, url: {}".format(req_url)) if HarCaptureTypes.REQUEST_COOKIES in self.har_capture_types: - har_entry['request']['cookies'] = self.format_request_cookies(flow.request.cookies.fields) + har_entry["request"]["cookies"] = self.format_request_cookies( + flow.request.cookies.fields + ) if HarCaptureTypes.REQUEST_HEADERS in self.har_capture_types: - har_entry['request']['headers'] = self.name_value(flow.request.headers) + har_entry["request"]["headers"] = self.name_value(flow.request.headers) if HarCaptureTypes.REQUEST_CONTENT in self.har_capture_types: params = [ @@ -70,47 +102,70 @@ def capture_request(self, flow): har_entry["request"]["postData"] = { "mimeType": flow.request.headers.get("Content-Type", ""), "text": flow.request.get_text(strict=False), - "params": params + "params": params, } - har_entry['request']['bodySize'] = len(flow.request.raw_content) if flow.request.raw_content else 0 + har_entry["request"]["bodySize"] = ( + len(flow.request.raw_content) if flow.request.raw_content else 0 + ) flow.set_har_entry(har_entry) def capture_response(self, flow): full_url = self.get_full_url(flow.request) - if 'BrowserUpData' in full_url or 'detectportal.firefox.com' in full_url: - logging.info('BrowserUpData response or ignored response, capturing nothing.') + if "BrowserUpData" in full_url or "detectportal.firefox.com" in full_url: + logging.info( + "BrowserUpData response or ignored response, capturing nothing." + ) return - logging.debug('Incoming response for request to url: {}'.format(full_url)) + logging.debug("Incoming response for request to url: {}".format(full_url)) t = HarBuilder.entry_timings() - t['send'] = self.diff_millis(flow.request.timestamp_end, flow.request.timestamp_start) - t['wait'] = self.diff_millis(flow.response.timestamp_start, flow.request.timestamp_end) - t['receive'] = self.diff_millis(flow.response.timestamp_end, flow.response.timestamp_start) + t["send"] = self.diff_millis( + flow.request.timestamp_end, flow.request.timestamp_start + ) + t["wait"] = self.diff_millis( + flow.response.timestamp_start, flow.request.timestamp_end + ) + t["receive"] = self.diff_millis( + flow.response.timestamp_end, flow.response.timestamp_start + ) if flow.server_conn and flow.server_conn not in SERVERS_SEEN: - t['connect'] = self.diff_millis(flow.server_conn.timestamp_tcp_setup, flow.server_conn.timestamp_start) + t["connect"] = self.diff_millis( + flow.server_conn.timestamp_tcp_setup, flow.server_conn.timestamp_start + ) if flow.server_conn.timestamp_tls_setup is not None: - t['ssl'] = self.diff_millis(flow.server_conn.timestamp_tls_setup, flow.server_conn.timestamp_tcp_setup) + t["ssl"] = self.diff_millis( + flow.server_conn.timestamp_tls_setup, + flow.server_conn.timestamp_tcp_setup, + ) SERVERS_SEEN.add(flow.server_conn) full_time = sum(v for v in t.values() if v > -1) har_entry = flow.get_har_entry() - har_entry['timings'] = t + har_entry["timings"] = t # Response body size and encoding - response_body_size = len(flow.response.raw_content) if flow.response.raw_content else 0 - response_body_decoded_size = len(flow.response.content) if flow.response.content else 0 + response_body_size = ( + len(flow.response.raw_content) if flow.response.raw_content else 0 + ) + response_body_decoded_size = ( + len(flow.response.content) if flow.response.content else 0 + ) response_body_compression = response_body_decoded_size - response_body_size - if flow.metadata.get('injected_script_len') and response_body_size > 0: - logging.debug(f"Subtracting injected script length of {flow.metadata.get('injected_script_len')}") - response_body_size = response_body_size - flow.metadata.get('injected_script_len') + if flow.metadata.get("injected_script_len") and response_body_size > 0: + logging.debug( + f"Subtracting injected script length of {flow.metadata.get('injected_script_len')}" + ) + response_body_size = response_body_size - flow.metadata.get( + "injected_script_len" + ) har_response = HarBuilder.entry_response() har_response["status"] = flow.response.status_code @@ -118,60 +173,68 @@ def capture_response(self, flow): har_response["httpVersion"] = flow.response.http_version if HarCaptureTypes.RESPONSE_COOKIES in self.har_capture_types: - har_response["cookies"] = \ - self.format_response_cookies(flow.response.cookies.fields) + har_response["cookies"] = self.format_response_cookies( + flow.response.cookies.fields + ) if HarCaptureTypes.RESPONSE_HEADERS in self.har_capture_types: har_response["headers"] = self.name_value(flow.response.headers) if flow.response.status_code in [300, 301, 302, 303, 307]: - har_response['redirectURL'] = flow.response.headers['Location'] + har_response["redirectURL"] = flow.response.headers["Location"] - content = har_response['content'] - content['size'] = response_body_size - content['compression'] = response_body_compression - content['mimeType'] = flow.response.headers.get('Content-Type', '') + content = har_response["content"] + content["size"] = response_body_size + content["compression"] = response_body_compression + content["mimeType"] = flow.response.headers.get("Content-Type", "") if HarCaptureTypes.RESPONSE_DYNAMIC_CONTENT in self.har_capture_types: - mime_type = flow.response.headers.get('Content-Type', '').split(';')[0].strip() + mime_type = ( + flow.response.headers.get("Content-Type", "").split(";")[0].strip() + ) # Skip capturing if mime_type is in the types to ignore if mime_type not in STATIC_MIME_TYPES: if strutils.is_mostly_bin(flow.response.content): - har_response["content"]["text"] = base64.b64encode(flow.response.content).decode() + har_response["content"]["text"] = base64.b64encode( + flow.response.content + ).decode() har_response["content"]["encoding"] = "base64" else: - har_response["content"]["text"] = flow.response.get_text(strict=False) + har_response["content"]["text"] = flow.response.get_text( + strict=False + ) if HarCaptureTypes.RESPONSE_CONTENT in self.har_capture_types: if strutils.is_mostly_bin(flow.response.content): if HarCaptureTypes.RESPONSE_BINARY_CONTENT in self.har_capture_types: - har_response["content"]["text"] = base64.b64encode(flow.response.content).decode() + har_response["content"]["text"] = base64.b64encode( + flow.response.content + ).decode() har_response["content"]["encoding"] = "base64" else: har_response["content"]["text"] = flow.response.get_text(strict=False) - har_response["redirectURL"] = flow.response.headers.get('Location', '') + har_response["redirectURL"] = flow.response.headers.get("Location", "") har_response["headersSize"] = len(str(flow.response.headers)) har_response["bodySize"] = response_body_size - har_entry['response'] = har_response - har_entry['time'] = full_time - har_entry['pageref'] = self.get_current_page_ref() + har_entry["response"] = har_response + har_entry["time"] = full_time + har_entry["pageref"] = self.get_current_page_ref() - har_entry['timings'] = t + har_entry["timings"] = t if flow.server_conn.connected: - har_entry["serverIPAddress"] = str( - flow.server_conn.ip_address[0]) + har_entry["serverIPAddress"] = str(flow.server_conn.ip_address[0]) flow.set_har_entry(har_entry) def capture_websocket_message(self, flow): full_url = self.get_full_url(flow.request) - if 'BrowserUpData' in full_url or 'devtools' in full_url: - logging.info('BrowserUpData websocket, capturing nothing.') + if "BrowserUpData" in full_url or "devtools" in full_url: + logging.info("BrowserUpData websocket, capturing nothing.") else: - logging.info('Capturing WS data.') + logging.info("Capturing WS data.") if HarCaptureTypes.WEBSOCKET_MESSAGES in self.har_capture_types: har_entry = flow.get_har_entry() msg = flow.websocket.messages[-1] @@ -182,15 +245,15 @@ def capture_websocket_message(self, flow): pass msg = { - "type": 'send' if msg.from_client else 'receive', + "type": "send" if msg.from_client else "receive", "opcode": msg.type.value, "data": data, - "time": msg.timestamp + "time": msg.timestamp, } - msgs = har_entry.get('_webSocketMessages', []) + msgs = har_entry.get("_webSocketMessages", []) msgs.append(msg) - har_entry['_webSocketMessages'] = msgs + har_entry["_webSocketMessages"] = msgs flow.set_har_entry(har_entry) # for all of these: Use -1 if the timing does not apply to the current request. @@ -203,10 +266,10 @@ def capture_websocket_message(self, flow): def get_full_url(self, request): host_port = request.pretty_host - if request.method == 'CONNECT': + if request.method == "CONNECT": if request.port != 443: - host_port = host_port + ':' + str(request.port) - host_port = 'https://' + host_port + host_port = host_port + ":" + str(request.port) + host_port = "https://" + host_port else: if request.scheme is not None: host_port = request.pretty_url diff --git a/mitmproxy/addons/browserup/har/flow_har_entry_patch.py b/mitmproxy/addons/browserup/har/flow_har_entry_patch.py index fe93eb6595..4328e39723 100644 --- a/mitmproxy/addons/browserup/har/flow_har_entry_patch.py +++ b/mitmproxy/addons/browserup/har/flow_har_entry_patch.py @@ -4,15 +4,15 @@ def patch_flow(): def set_har_entry(self, updated_entry): - setattr(self, 'har_entry', updated_entry) + setattr(self, "har_entry", updated_entry) def get_har_entry(self): - if hasattr(self, 'har_entry'): + if hasattr(self, "har_entry"): return self.har_entry else: - addon = ctx.master.addons.get('harcaptureaddon') + addon = ctx.master.addons.get("harcaptureaddon") entry = addon.create_har_entry(self) - setattr(self, 'har_entry', entry) + setattr(self, "har_entry", entry) return entry # Make every flow able to get/carry a har entry reference diff --git a/mitmproxy/addons/browserup/har/har_builder.py b/mitmproxy/addons/browserup/har/har_builder.py index de0613302c..eb679ddfe5 100644 --- a/mitmproxy/addons/browserup/har/har_builder.py +++ b/mitmproxy/addons/browserup/har/har_builder.py @@ -1,37 +1,27 @@ -from datetime import datetime, timezone +from datetime import datetime +from datetime import timezone DEFAULT_PAGE_TITLE = "Default" DEFAULT_PAGE_REF = "page_1" -class HarBuilder(): - +class HarBuilder: @staticmethod def har(): - return { - "log": HarBuilder.log() - } + return {"log": HarBuilder.log()} @staticmethod def log(): return { "version": "1.1", - "creator": { - "name": "BrowserUp Proxy", - "version": "0.1", - "comment": "" - }, + "creator": {"name": "BrowserUp Proxy", "version": "0.1", "comment": ""}, "entries": [], - "pages": [HarBuilder.page(id=DEFAULT_PAGE_REF)] + "pages": [HarBuilder.page(id=DEFAULT_PAGE_REF)], } @staticmethod def page_timings(): - return { - "onContentLoad": -1, - "onLoad": -1, - "comment": "" - } + return {"onContentLoad": -1, "onLoad": -1, "comment": ""} @staticmethod def page(id=DEFAULT_PAGE_REF, title=DEFAULT_PAGE_TITLE): @@ -39,7 +29,7 @@ def page(id=DEFAULT_PAGE_REF, title=DEFAULT_PAGE_TITLE): "title": title, "id": id, "startedDateTime": str(datetime.now(tz=timezone.utc).isoformat()), - "pageTimings": HarBuilder.page_timings() + "pageTimings": HarBuilder.page_timings(), } @staticmethod @@ -48,7 +38,7 @@ def post_data(): "mimeType": "multipart/form-data", "params": [], "text": "plain posted data", - "comment": "" + "comment": "", } @staticmethod @@ -62,7 +52,7 @@ def entry_request(): "queryString": [], "headersSize": 0, "bodySize": 0, - "comment": "" + "comment": "", } @staticmethod @@ -74,7 +64,7 @@ def entry_timings(): "ssl": -1, "send": 0, "wait": 0, - "receive": 0 + "receive": 0, } @staticmethod @@ -102,14 +92,14 @@ def entry_response(): @staticmethod def entry_response_for_failure(): result = HarBuilder.entry_response() - result['status'] = 0 - result['statusText'] = "" - result['httpVersion'] = "unknown" - result['_errorMessage'] = "No response received" + result["status"] = 0 + result["statusText"] = "" + result["httpVersion"] = "unknown" + result["_errorMessage"] = "No response received" return result @staticmethod - def entry(pageref = DEFAULT_PAGE_REF): + def entry(pageref=DEFAULT_PAGE_REF): return { "pageref": pageref, "startedDateTime": str(datetime.now(tz=timezone.utc).isoformat()), @@ -121,5 +111,5 @@ def entry(pageref = DEFAULT_PAGE_REF): "timings": HarBuilder.entry_timings(), "serverIPAddress": "", "connection": "", - "comment": "" + "comment": "", } diff --git a/mitmproxy/addons/browserup/har/har_capture_types.py b/mitmproxy/addons/browserup/har/har_capture_types.py index a95332aadb..e4a5ca3b16 100644 --- a/mitmproxy/addons/browserup/har/har_capture_types.py +++ b/mitmproxy/addons/browserup/har/har_capture_types.py @@ -1,4 +1,5 @@ -from enum import Enum, auto +from enum import auto +from enum import Enum class HarCaptureTypes(Enum): @@ -13,12 +14,32 @@ class HarCaptureTypes(Enum): RESPONSE_DYNAMIC_CONTENT = auto() WEBSOCKET_MESSAGES = auto() - REQUEST_CAPTURE_TYPES = {REQUEST_HEADERS, REQUEST_CONTENT, REQUEST_BINARY_CONTENT, REQUEST_COOKIES} - RESPONSE_CAPTURE_TYPES = {RESPONSE_HEADERS, RESPONSE_CONTENT, RESPONSE_DYNAMIC_CONTENT, - RESPONSE_BINARY_CONTENT, RESPONSE_COOKIES, WEBSOCKET_MESSAGES} + REQUEST_CAPTURE_TYPES = { + REQUEST_HEADERS, + REQUEST_CONTENT, + REQUEST_BINARY_CONTENT, + REQUEST_COOKIES, + } + RESPONSE_CAPTURE_TYPES = { + RESPONSE_HEADERS, + RESPONSE_CONTENT, + RESPONSE_DYNAMIC_CONTENT, + RESPONSE_BINARY_CONTENT, + RESPONSE_COOKIES, + WEBSOCKET_MESSAGES, + } HEADER_CAPTURE_TYPES = {REQUEST_HEADERS, RESPONSE_HEADERS} - NON_BINARY_CONTENT_CAPTURE_TYPES = {REQUEST_CONTENT, RESPONSE_CONTENT, WEBSOCKET_MESSAGES} + NON_BINARY_CONTENT_CAPTURE_TYPES = { + REQUEST_CONTENT, + RESPONSE_CONTENT, + WEBSOCKET_MESSAGES, + } BINARY_CONTENT_CAPTURE_TYPES = {REQUEST_BINARY_CONTENT, RESPONSE_BINARY_CONTENT} - ALL_CONTENT_CAPTURE_TYPES = {REQUEST_CONTENT, RESPONSE_CONTENT, - REQUEST_BINARY_CONTENT, RESPONSE_BINARY_CONTENT, WEBSOCKET_MESSAGES} + ALL_CONTENT_CAPTURE_TYPES = { + REQUEST_CONTENT, + RESPONSE_CONTENT, + REQUEST_BINARY_CONTENT, + RESPONSE_BINARY_CONTENT, + WEBSOCKET_MESSAGES, + } COOKIE_CAPTURE_TYPES = {REQUEST_COOKIES, RESPONSE_COOKIES} diff --git a/mitmproxy/addons/browserup/har/har_manager.py b/mitmproxy/addons/browserup/har/har_manager.py index 015fedcfe5..548a0ce8e0 100644 --- a/mitmproxy/addons/browserup/har/har_manager.py +++ b/mitmproxy/addons/browserup/har/har_manager.py @@ -2,7 +2,8 @@ import json import logging import tempfile -from datetime import datetime, timezone +from datetime import datetime +from datetime import timezone from threading import Lock from mitmproxy.addons.browserup.har.har_builder import HarBuilder @@ -14,7 +15,7 @@ SUBMITTED_FLAG = "_submitted" -class HarManagerMixin(): +class HarManagerMixin: # Used to manage a single active har, gets mixed into har_capture_addon def __init__(self): @@ -34,7 +35,7 @@ def __init__(self): # omitting HarCaptureTypes.RESPONSE_BINARY_CONTENT, self.http_connect_timings = {} - def get_or_create_har(self, page_ref = None, page_title = None): + def get_or_create_har(self, page_ref=None, page_title=None): if self.har is None: self.reset_har_and_return_old_har() return self.har @@ -45,9 +46,9 @@ def new_har(self): def create_har_entry(self, flow): har = self.get_or_create_har() page = self.get_or_create_current_page() - pageref = page['id'] + pageref = page["id"] entry = HarBuilder.entry(pageref) - har['log']['entries'].append(entry) + har["log"]["entries"].append(entry) self.print_har_summary() return entry @@ -56,45 +57,45 @@ def get_har(self, clean_har): self.new_har() return self.har - def new_page(self, page_title = None, page_ref=None): - logging.info('-->Creating new page') + def new_page(self, page_title=None, page_ref=None): + logging.info("-->Creating new page") # only create a new page if there are entries in the current page - if len(self.har['log']['pages']) > 0: + if len(self.har["log"]["pages"]) > 0: self.end_page() har = self.get_or_create_har() - next_page_number = len(har['log']['pages']) + 1 + next_page_number = len(har["log"]["pages"]) + 1 next_id = "page_{}".format(next_page_number) new_page = HarBuilder.page(id=next_id) - har['log']['pages'].append(new_page) + har["log"]["pages"].append(new_page) # print a list of the pages with their title and a list of the entries, and their page ref def print_har_summary(self): return - logging.debug('-->Printing har summary') + logging.debug("-->Printing har summary") h = self.get_or_create_har() - for page in h['log']['pages']: - logging.debug(page['title'] + " " + page['id']) - for entry in h['log']['entries']: + for page in h["log"]["pages"]: + logging.debug(page["title"] + " " + page["id"]) + for entry in h["log"]["entries"]: logging.info("===>entry: {}".format(entry)) def get_current_page_ref(self): har_page = self.get_or_create_current_page() - return har_page['id'] + return har_page["id"] def get_or_create_current_page(self): self.get_or_create_har() - if len(self.har['log']['pages']) > 0: - return self.har['log']['pages'][-1] + if len(self.har["log"]["pages"]) > 0: + return self.har["log"]["pages"][-1] else: har_page = HarBuilder.page - self.har['log']['pages'].append(har_page) + self.har["log"]["pages"].append(har_page) return har_page def reset_har_and_return_old_har(self): - logging.info('Creating new har') + logging.info("Creating new har") with mutex: old_har = self.end_har() @@ -103,19 +104,22 @@ def reset_har_and_return_old_har(self): return old_har def add_verification_to_har(self, verification_type, verification_name, result): - self.add_custom_value_to_har('_verifications', {'name': verification_name, 'type': verification_type, 'result': result}) + self.add_custom_value_to_har( + "_verifications", + {"name": verification_name, "type": verification_type, "result": result}, + ) def add_counter_to_har(self, counter_dict): - self.add_custom_value_to_har('_counters', counter_dict) + self.add_custom_value_to_har("_counters", counter_dict) def add_error_to_har(self, error_dict): - self.add_custom_value_to_har('_errors', error_dict) + self.add_custom_value_to_har("_errors", error_dict) def add_page_timings_to_har(self, page_info): page = self.get_or_create_current_page() - timings = page['pageTimings'] + timings = page["pageTimings"] timings.update(page_info) - page['pageTimings'] = timings + page["pageTimings"] = timings logging.info(self.get_or_create_current_page()) def add_page_data_to_har(self, page_data): @@ -125,32 +129,37 @@ def add_page_data_to_har(self, page_data): def entries_for_page(self, page_ref): har = self.get_or_create_har() - return [entry for entry in har['log']['entries'] if entry['pageref'] == page_ref] + return [ + entry for entry in har["log"]["entries"] if entry["pageref"] == page_ref + ] def page_from_page_ref(self, page_ref): har = self.get_or_create_har() - for page in har['log']['pages']: - if page['id'] == page_ref: + for page in har["log"]["pages"]: + if page["id"] == page_ref: return page def is_a_websocket(self, entry): # check if the request is a websocket by checking headers for upgrade: websocket - for header in entry['response']['headers']: - if header['name'].lower() == 'upgrade' and header['value'].lower() == 'websocket': + for header in entry["response"]["headers"]: + if ( + header["name"].lower() == "upgrade" + and header["value"].lower() == "websocket" + ): return True # not guaranteed def is_a_video(self, entry): - url = entry['request']['url'] + url = entry["request"]["url"] - video_extensions = ['.mp4', '.webm', '.ogg', '.flv', '.avi'] + video_extensions = [".mp4", ".webm", ".ogg", ".flv", ".avi"] if any(url.lower().endswith(ext) for ext in video_extensions): return True mime_type = "" - for header in entry['response']['headers']: - if header['name'].lower() == 'content-type': - mime_type = header['value'] + for header in entry["response"]["headers"]: + if header["name"].lower() == "content-type": + mime_type = header["value"] break if "video" in mime_type: @@ -160,25 +169,25 @@ def is_a_video(self, entry): def submit_har(self): page = self.get_or_create_current_page() - self.submit_entries(page['id'], True, True) + self.submit_entries(page["id"], True, True) self.submit_page(page) def decorate_video_data_on_entries(self, video_data): page = self.get_or_create_current_page() - latest_page_entries = self.entries_for_page(page['id']) + latest_page_entries = self.entries_for_page(page["id"]) if len(latest_page_entries) == 0 or len(video_data) == 0: return for entry in latest_page_entries: for video in video_data: - videosrc = video['_videoSRC'] - if not videosrc or videosrc == '': + videosrc = video["_videoSRC"] + if not videosrc or videosrc == "": continue - if videosrc in entry['request']['url']: - print('found video entry! {}'.format(entry)) - del video['_videoSRC'] - entry['response']['content'].update(video) + if videosrc in entry["request"]["url"]: + print("found video entry! {}".format(entry)) + del video["_videoSRC"] + entry["response"]["content"].update(video) video_data.remove(video) # remove the video from the video_data break @@ -189,12 +198,12 @@ def add_custom_value_to_har(self, item_type, item): items.append(item) def set_page_title(self, title): - logging.debug('Setting page title to: {}'.format(title)) + logging.debug("Setting page title to: {}".format(title)) page = self.get_or_create_current_page() - page['title'] = title + page["title"] = title def end_har(self): - logging.info('Ending current har...') + logging.info("Ending current har...") self.end_page() old_har = self.har self.har = HarBuilder.har() @@ -202,55 +211,63 @@ def end_har(self): def copy_entries_without_response(self, old_har): if old_har is not None: - for entry in old_har['log']['entries']: + for entry in old_har["log"]["entries"]: if not self.har_entry_has_response(entry): - self.har['log']['entries'].append(entry) + self.har["log"]["entries"].append(entry) def end_page(self): - logging.info('Ending current page...') + logging.info("Ending current page...") def is_har_entry_submitted(self, har_entry): return har_entry.get(SUBMITTED_FLAG) def har_entry_has_response(self, har_entry): - return bool(har_entry['response']) + return bool(har_entry["response"]) # normally, for responses, we only submit when 'done' (have a response) and they are not websockets or videos # because websocket and video responses may be ongoing until the page is exited (next page started) # however, we do want to submit websocket messages and video data, so we pass the flags to include them # when we are done with the page (a final submit). - def create_filtered_har_and_track_submitted(self, report_last_page = False, include_websockets = False, include_videos = False): + def create_filtered_har_and_track_submitted( + self, report_last_page=False, include_websockets=False, include_videos=False + ): if self.har is None: return None entries_to_report = [] - for entry in self.har['log']['entries']: + for entry in self.har["log"]["entries"]: request_copy = {} response_copy = {} # always submit request unless already submitted - if not entry['request'].get(SUBMITTED_FLAG): - request_copy = copy.deepcopy(entry['request']) - entry['request'][SUBMITTED_FLAG] = True + if not entry["request"].get(SUBMITTED_FLAG): + request_copy = copy.deepcopy(entry["request"]) + entry["request"][SUBMITTED_FLAG] = True - if entry['response']: + if entry["response"]: # delay websocket harvesting until we have all messages - if not entry['response'].get(SUBMITTED_FLAG): - if (include_websockets or not self.is_a_websocket(entry)) and (include_videos or not self.is_a_video(entry)): - response_copy = copy.deepcopy(entry['response']) - entry['response'][SUBMITTED_FLAG] = True + if not entry["response"].get(SUBMITTED_FLAG): + if (include_websockets or not self.is_a_websocket(entry)) and ( + include_videos or not self.is_a_video(entry) + ): + response_copy = copy.deepcopy(entry["response"]) + entry["response"][SUBMITTED_FLAG] = True if request_copy or response_copy: entry_copy = copy.deepcopy(entry) - entry_copy['request'] = request_copy - entry_copy['response'] = response_copy + entry_copy["request"] = request_copy + entry_copy["response"] = response_copy entries_to_report.append(entry_copy) pages_to_report = [] - pages = self.har['log']['pages'] if report_last_page else self.har['log']['pages'][:-1] + pages = ( + self.har["log"]["pages"] + if report_last_page + else self.har["log"]["pages"][:-1] + ) for page in pages: if not page.get(SUBMITTED_FLAG): page_copy = copy.deepcopy(page) @@ -258,22 +275,22 @@ def create_filtered_har_and_track_submitted(self, report_last_page = False, incl page[SUBMITTED_FLAG] = True har_copy = copy.deepcopy(self.har) - har_copy['log']['entries'] = entries_to_report - har_copy['log']['pages'] = pages_to_report + har_copy["log"]["entries"] = entries_to_report + har_copy["log"]["pages"] = pages_to_report return har_copy def _likely_a_video(entry): - url = entry['request']['url'] + url = entry["request"]["url"] mime_type = "" - for header in entry['response']['headers']: - if header['name'].lower() == 'content-type': - mime_type = header['value'] + for header in entry["response"]["headers"]: + if header["name"].lower() == "content-type": + mime_type = header["value"] break if "video" in mime_type: return True - video_extensions = ['.mp4', '.webm', '.ogg', '.flv', '.avi'] + video_extensions = [".mp4", ".webm", ".ogg", ".flv", ".avi"] if any(url.lower().endswith(ext) for ext in video_extensions): return True @@ -300,7 +317,9 @@ def format_cookies(self, cookie_list): # Expiration time needs to be formatted expire_ts = cookies.get_expiration_ts(attrs) if expire_ts is not None: - cookie_har["expires"] = datetime.fromtimestamp(expire_ts, timezone.utc).isoformat() + cookie_har["expires"] = datetime.fromtimestamp( + expire_ts, timezone.utc + ).isoformat() rv.append(cookie_har) @@ -309,7 +328,9 @@ def format_cookies(self, cookie_list): def save_har(self, har): json_dump: str = json.dumps(har, ensure_ascii=True, indent=2) - tmp_file = tempfile.NamedTemporaryFile(mode="wb", prefix="har_dump_", delete=False) + tmp_file = tempfile.NamedTemporaryFile( + mode="wb", prefix="har_dump_", delete=False + ) raw: bytes = json_dump.encode() tmp_file.write(raw) tmp_file.flush() @@ -334,6 +355,6 @@ def format_response_cookies(self, fields): def name_value(self, obj): """ - Convert (key, value) pairs to HAR format. + Convert (key, value) pairs to HAR format. """ return [{"name": k, "value": v} for k, v in obj.items()] diff --git a/mitmproxy/addons/browserup/har/har_resources.py b/mitmproxy/addons/browserup/har/har_resources.py index acef2488f5..ab7d0e7a8d 100644 --- a/mitmproxy/addons/browserup/har/har_resources.py +++ b/mitmproxy/addons/browserup/har/har_resources.py @@ -8,9 +8,9 @@ from marshmallow import ValidationError from mitmproxy.addons.browserup.har.har_capture_types import HarCaptureTypes -from mitmproxy.addons.browserup.har.har_schemas import (CounterSchema, - ErrorSchema, - MatchCriteriaSchema) +from mitmproxy.addons.browserup.har.har_schemas import CounterSchema +from mitmproxy.addons.browserup.har.har_schemas import ErrorSchema +from mitmproxy.addons.browserup.har.har_schemas import MatchCriteriaSchema from mitmproxy.addons.browserup.har.har_verifications import HarVerifications @@ -32,7 +32,7 @@ def on_get(self, req, resp): 200: description: OK means all is well. """ - resp.text = 'OK' + resp.text = "OK" resp.content_type = falcon.MEDIA_TEXT resp.status = falcon.HTTP_200 @@ -51,7 +51,10 @@ def respond_with_error_on_invalid_criteria(self, req, resp): MatchCriteriaSchema().load(criteria) except ValidationError as err: resp.content_type = falcon.MEDIA_JSON - raise falcon.HTTPError(falcon.HTTP_422, description=json.dumps({'error': err.messages}, ensure_ascii=False)) + raise falcon.HTTPError( + falcon.HTTP_422, + description=json.dumps({"error": err.messages}, ensure_ascii=False), + ) class VerifyResponseMixin: @@ -65,16 +68,21 @@ class NoEntriesResponseMixin: def respond_with_no_entries_error(self, resp, bool): resp.status = falcon.HTTP_500 resp.content_type = falcon.MEDIA_JSON - resp.text = json.dumps({"error": 'No traffic entries are present! Is the proxy setup correctly?', }, ensure_ascii=False) + resp.text = json.dumps( + { + "error": "No traffic entries are present! Is the proxy setup correctly?", + }, + ensure_ascii=False, + ) class HarResource(RespondWithHarMixin): def apispec(self, spec): - path = os.path.abspath(os.path.dirname(__file__) + '/../schemas/*.json') + path = os.path.abspath(os.path.dirname(__file__) + "/../schemas/*.json") files = glob.glob(path) for filepath in files: filename = Path(filepath).resolve().stem - with open(filepath, encoding='utf-8') as f: + with open(filepath, encoding="utf-8") as f: schema = json.load(f) spec.components.schema(filename, component=schema) spec.path(resource=self) @@ -101,17 +109,17 @@ def on_get(self, req, resp): schema: $ref: "#/components/schemas/Har" """ - clean_har = req.get_param('cleanHar') == 'true' + clean_har = req.get_param("cleanHar") == "true" har = self.HarCaptureAddon.get_har(clean_har) if clean_har: - filtered_har = self.HarCaptureAddon.create_filtered_har_and_track_submitted(report_last_page = True, - include_websockets = True, - include_videos = True) + filtered_har = self.HarCaptureAddon.create_filtered_har_and_track_submitted( + report_last_page=True, include_websockets=True, include_videos=True + ) else: - filtered_har = self.HarCaptureAddon.create_filtered_har_and_track_submitted(report_last_page = False, - include_websockets = False, - include_videos = False) + filtered_har = self.HarCaptureAddon.create_filtered_har_and_track_submitted( + report_last_page=False, include_websockets=False, include_videos=False + ) old_har_file = self.HarCaptureAddon.save_har(filtered_har) if clean_har: @@ -172,13 +180,13 @@ def on_post(self, req, resp): schema: $ref: "#/components/schemas/Har" """ - page_title = req.get_param('title') + page_title = req.get_param("title") har = self.HarCaptureAddon.new_page(page_title) har_file = self.HarCaptureAddon.save_har(har) self.respond_with_har(resp, har, har_file) -class HarCaptureTypesResource(): +class HarCaptureTypesResource: def __init__(self, HarCaptureAddon): self.name = "harcapture" self.HarCaptureAddon = HarCaptureAddon @@ -201,7 +209,7 @@ def on_put(self, req, resp): schema: $ref: "#/components/schemas/Har" """ - capture_types = req.get_param('captureTypes') + capture_types = req.get_param("captureTypes") capture_types = capture_types.strip("[]").split(",") capture_types_parsed = [] @@ -220,10 +228,11 @@ def on_put(self, req, resp): self.HarCaptureAddon.har_capture_types = capture_types_parsed resp.status = falcon.HTTP_200 + # decorates har with _page_timings gathered from injected JS script -class PageTimingsResource(): +class PageTimingsResource: def __init__(self, HarCaptureAddon): self.name = "harcapture" self.HarCaptureAddon = HarCaptureAddon @@ -238,7 +247,7 @@ def apispec(self, spec): # By accepting regular form posts, rather than application/json, we get out of some # CORS headaches. def on_post(self, req, resp): - logging.debug('Page timings resource post') + logging.debug("Page timings resource post") try: form = req.get_media() page_timings = {} @@ -246,17 +255,19 @@ def on_post(self, req, resp): page_timings = json.loads(part.text) self.HarCaptureAddon.add_page_info_to_har(page_timings) except ValidationError as err: - logging.debug('Page timings validation error') - logging.debug(json.dumps({'Page timings error': err.messages})) + logging.debug("Page timings validation error") + logging.debug(json.dumps({"Page timings error": err.messages})) resp.status = falcon.HTTP_422 resp.content_type = falcon.MEDIA_JSON - resp.text = json.dumps({'error': err.messages}, ensure_ascii=False) + resp.text = json.dumps({"error": err.messages}, ensure_ascii=False) else: - logging.debug('Page timings returning 204') + logging.debug("Page timings returning 204") resp.status = falcon.HTTP_204 -class PresentResource(VerifyResponseMixin, NoEntriesResponseMixin, ValidateMatchCriteriaMixin): +class PresentResource( + VerifyResponseMixin, NoEntriesResponseMixin, ValidateMatchCriteriaMixin +): def __init__(self, HarCaptureAddon): self.name = "harcapture" self.HarCaptureAddon = HarCaptureAddon @@ -304,14 +315,16 @@ def on_post(self, req, resp, name): criteria = req.media hv = HarVerifications(self.HarCaptureAddon.har) result = hv.present(criteria) - self.HarCaptureAddon.add_verification_to_har(name, 'present', result) - if criteria.get('error_if_no_traffic', True) and hv.no_entries(): + self.HarCaptureAddon.add_verification_to_har(name, "present", result) + if criteria.get("error_if_no_traffic", True) and hv.no_entries(): self.respond_with_no_entries_error(resp, result) else: self.respond_with_bool(resp, result) -class NotPresentResource(VerifyResponseMixin, NoEntriesResponseMixin, ValidateMatchCriteriaMixin): +class NotPresentResource( + VerifyResponseMixin, NoEntriesResponseMixin, ValidateMatchCriteriaMixin +): def __init__(self, HarCaptureAddon): self.name = "harcapture" self.HarCaptureAddon = HarCaptureAddon @@ -358,14 +371,16 @@ def on_post(self, req, resp, name): criteria = req.media hv = HarVerifications(self.HarCaptureAddon.har) result = hv.not_present(criteria) - self.HarCaptureAddon.add_verification_to_har(name, 'not_present', result) - if criteria.get('error_if_no_traffic', True) and hv.no_entries(): + self.HarCaptureAddon.add_verification_to_har(name, "not_present", result) + if criteria.get("error_if_no_traffic", True) and hv.no_entries(): self.respond_with_no_entries_error(resp, result) else: self.respond_with_bool(resp, result) -class SizeResource(VerifyResponseMixin, NoEntriesResponseMixin, ValidateMatchCriteriaMixin): +class SizeResource( + VerifyResponseMixin, NoEntriesResponseMixin, ValidateMatchCriteriaMixin +): def __init__(self, HarCaptureAddon): self.name = "harcapture" self.HarCaptureAddon = HarCaptureAddon @@ -419,16 +434,18 @@ def on_post(self, req, resp, size, name): criteria = req.media size_val = int(size) * 1000 hv = HarVerifications(self.HarCaptureAddon.har) - max_size = hv.get_max(criteria, 'response') + max_size = hv.get_max(criteria, "response") result = size_val <= max_size - self.HarCaptureAddon.add_verification_to_har(name, 'size', result) - if criteria.get('error_if_no_traffic', True) and hv.no_entries(): + self.HarCaptureAddon.add_verification_to_har(name, "size", result) + if criteria.get("error_if_no_traffic", True) and hv.no_entries(): self.respond_with_no_entries_error(resp, result) else: self.respond_with_bool(resp, result) -class SLAResource(VerifyResponseMixin, NoEntriesResponseMixin, ValidateMatchCriteriaMixin): +class SLAResource( + VerifyResponseMixin, NoEntriesResponseMixin, ValidateMatchCriteriaMixin +): def __init__(self, HarCaptureAddon): self.name = "harcapture" self.HarCaptureAddon = HarCaptureAddon @@ -482,16 +499,16 @@ def on_post(self, req, resp, time, name): criteria = req.media time_val = int(time) hv = HarVerifications(self.HarCaptureAddon.har) - val = hv.get_max(criteria, 'time') + val = hv.get_max(criteria, "time") result = time_val <= val - self.HarCaptureAddon.add_verification_to_har(name, 'sla', val) - if criteria.get('error_if_no_traffic', True) and hv.no_entries(): + self.HarCaptureAddon.add_verification_to_har(name, "sla", val) + if criteria.get("error_if_no_traffic", True) and hv.no_entries(): self.respond_with_no_entries_error(resp, result) else: self.respond_with_bool(resp, result) -class CounterResource(): +class CounterResource: def __init__(self, HarCaptureAddon): self.name = "harcapture" self.HarCaptureAddon = HarCaptureAddon @@ -529,12 +546,12 @@ def on_post(self, req, resp): except ValidationError as err: resp.status = falcon.HTTP_422 resp.content_type = falcon.MEDIA_JSON - resp.text = json.dumps({'error': err.messages}, ensure_ascii=False) + resp.text = json.dumps({"error": err.messages}, ensure_ascii=False) else: resp.status = falcon.HTTP_204 -class ErrorResource(): +class ErrorResource: def __init__(self, HarCaptureAddon): self.name = "harcapture" self.HarCaptureAddon = HarCaptureAddon @@ -572,6 +589,6 @@ def on_post(self, req, resp): except ValidationError as err: resp.status = falcon.HTTP_422 resp.content_type = falcon.MEDIA_JSON - resp.text = json.dumps({'error': err.messages}, ensure_ascii=False) + resp.text = json.dumps({"error": err.messages}, ensure_ascii=False) else: resp.status = falcon.HTTP_204 diff --git a/mitmproxy/addons/browserup/har/har_schemas.py b/mitmproxy/addons/browserup/har/har_schemas.py index 14619b3b38..5f88a4de72 100644 --- a/mitmproxy/addons/browserup/har/har_schemas.py +++ b/mitmproxy/addons/browserup/har/har_schemas.py @@ -1,8 +1,11 @@ -from marshmallow import Schema, fields +from marshmallow import fields +from marshmallow import Schema class VerifyResultSchema(Schema): - result = fields.Boolean(metadata={"optional": False, "description": "Result True / False"}) + result = fields.Boolean( + metadata={"optional": False, "description": "Result True / False"} + ) name = fields.Str(metadata={"optional": False, "description": "Name"}) type = fields.Str(metadata={"optional": False, "description": "Type"}) @@ -13,63 +16,211 @@ class NameValuePairSchema(Schema): class ErrorSchema(Schema): - name = fields.Str(metadata={"optional": False, "description": "Name of the Error to add. Stored in har under _errors"}) - details = fields.Str(metadata={"optional": False, "description": "Short details of the error"}) + name = fields.Str( + metadata={ + "optional": False, + "description": "Name of the Error to add. Stored in har under _errors", + } + ) + details = fields.Str( + metadata={"optional": False, "description": "Short details of the error"} + ) class CounterSchema(Schema): - name = fields.Str(metadata={"optional": False, "description": "Name of Custom Counter to add to the page under _counters"}) - value = fields.Number(metadata={"optional": False, "format": "double", "description": "Value for the counter"}) + name = fields.Str( + metadata={ + "optional": False, + "description": "Name of Custom Counter to add to the page under _counters", + } + ) + value = fields.Number( + metadata={ + "optional": False, + "format": "double", + "description": "Value for the counter", + } + ) class PageTimingSchema(Schema): - onContentLoad = fields.Number(metadata={"optional": False, "description": "onContentLoad per the browser"}) - onLoad = fields.Number(metadata={"optional": False, "description": "onLoad per the browser"}) - _firstInputDelay = fields.Number(metadata={"optional": True, "description": "firstInputDelay from the browser"}) - _firstPaint = fields.Number(metadata={"optional": True, "description": "firstPaint from the browser"}) - _cumulativeLayoutShift = fields.Number(metadata={"optional": True, "description": "cumulativeLayoutShift metric from the browser"}) - _largestContentfulPaint = fields.Number(metadata={"optional": True, "description": "largestContentfulPaint from the browser"}) - _domInteractive = fields.Number(metadata={"optional": True, "description": "domInteractive from the browser"}) - _firstContentfulPaint = fields.Number(metadata={"optional": True, "description": "firstContentfulPaint from the browser"}) - _dns = fields.Number(metadata={"optional": True, "description": "dns lookup time from the browser"}) - _ssl = fields.Number(metadata={"optional": True, "description": "Ssl connect time from the browser"}) - _timeToFirstByte = fields.Number(metadata={"optional": True, - "description": "Time to first byte of the page's first request per the browser"}) - _href = fields.Str(metadata={"optional": True, "description": "Top level href, including hashtag, etc per the browser"}) + onContentLoad = fields.Number( + metadata={"optional": False, "description": "onContentLoad per the browser"} + ) + onLoad = fields.Number( + metadata={"optional": False, "description": "onLoad per the browser"} + ) + _firstInputDelay = fields.Number( + metadata={"optional": True, "description": "firstInputDelay from the browser"} + ) + _firstPaint = fields.Number( + metadata={"optional": True, "description": "firstPaint from the browser"} + ) + _cumulativeLayoutShift = fields.Number( + metadata={ + "optional": True, + "description": "cumulativeLayoutShift metric from the browser", + } + ) + _largestContentfulPaint = fields.Number( + metadata={ + "optional": True, + "description": "largestContentfulPaint from the browser", + } + ) + _domInteractive = fields.Number( + metadata={"optional": True, "description": "domInteractive from the browser"} + ) + _firstContentfulPaint = fields.Number( + metadata={ + "optional": True, + "description": "firstContentfulPaint from the browser", + } + ) + _dns = fields.Number( + metadata={"optional": True, "description": "dns lookup time from the browser"} + ) + _ssl = fields.Number( + metadata={"optional": True, "description": "Ssl connect time from the browser"} + ) + _timeToFirstByte = fields.Number( + metadata={ + "optional": True, + "description": "Time to first byte of the page's first request per the browser", + } + ) + _href = fields.Str( + metadata={ + "optional": True, + "description": "Top level href, including hashtag, etc per the browser", + } + ) class MatchCriteriaSchema(Schema): - url = fields.Str(metadata={"optional": True, "description": "Request URL regexp to match", "externalDocs": { - "description": "Python Regex", "url": "https://docs.python.org/3/howto/regex.html"}}) - page = fields.Str(metadata={"optional": True, "description": "current|all", "externalDocs": { - "description": "Python Regex", "url": "https://docs.python.org/3/howto/regex.html"}}) - status = fields.Str(metadata={"optional": True, "description": "HTTP Status code to match.", "externalDocs": { - "description": "Python Regex", "url": "https://docs.python.org/3/howto/regex.html"}}) - content = fields.Str(metadata={"optional": True, "description": "Body content regexp content to match", "externalDocs": { - "description": "Python Regex", "url": "https://docs.python.org/3/howto/regex.html"}}) - content_type = fields.Str(metadata={"optional": True, "description": "Content type", "externalDocs": { - "description": "Python Regex", "url": "https://docs.python.org/3/howto/regex.html"}}) - websocket_message = fields.Str(metadata={"optional": True, "description": "Websocket message text to match", "externalDocs": { - "description": "Python Regex", "url": "https://docs.python.org/3/howto/regex.html"}}) - request_header = fields.Nested(NameValuePairSchema, metadata={"optional": True, "externalDocs": { - "description": "Python Regex", "url": "https://docs.python.org/3/howto/regex.html"}}) - request_cookie = fields.Nested(NameValuePairSchema, metadata={"optional": True, "externalDocs": { - "description": "Python Regex", "url": "https://docs.python.org/3/howto/regex.html"}}) - response_header = fields.Nested(NameValuePairSchema, metadata={"optional": True, "externalDocs": { - "description": "Python Regex", "url": "https://docs.python.org/3/howto/regex.html"}}) - response_cookie = fields.Nested(NameValuePairSchema, metadata={"optional": True, "externalDocs": { - "description": "Python Regex", "url": "https://docs.python.org/3/howto/regex.html"}}) - json_valid = fields.Boolean(metadata={"optional": True, "description": "Is valid JSON"}) + url = fields.Str( + metadata={ + "optional": True, + "description": "Request URL regexp to match", + "externalDocs": { + "description": "Python Regex", + "url": "https://docs.python.org/3/howto/regex.html", + }, + } + ) + page = fields.Str( + metadata={ + "optional": True, + "description": "current|all", + "externalDocs": { + "description": "Python Regex", + "url": "https://docs.python.org/3/howto/regex.html", + }, + } + ) + status = fields.Str( + metadata={ + "optional": True, + "description": "HTTP Status code to match.", + "externalDocs": { + "description": "Python Regex", + "url": "https://docs.python.org/3/howto/regex.html", + }, + } + ) + content = fields.Str( + metadata={ + "optional": True, + "description": "Body content regexp content to match", + "externalDocs": { + "description": "Python Regex", + "url": "https://docs.python.org/3/howto/regex.html", + }, + } + ) + content_type = fields.Str( + metadata={ + "optional": True, + "description": "Content type", + "externalDocs": { + "description": "Python Regex", + "url": "https://docs.python.org/3/howto/regex.html", + }, + } + ) + websocket_message = fields.Str( + metadata={ + "optional": True, + "description": "Websocket message text to match", + "externalDocs": { + "description": "Python Regex", + "url": "https://docs.python.org/3/howto/regex.html", + }, + } + ) + request_header = fields.Nested( + NameValuePairSchema, + metadata={ + "optional": True, + "externalDocs": { + "description": "Python Regex", + "url": "https://docs.python.org/3/howto/regex.html", + }, + }, + ) + request_cookie = fields.Nested( + NameValuePairSchema, + metadata={ + "optional": True, + "externalDocs": { + "description": "Python Regex", + "url": "https://docs.python.org/3/howto/regex.html", + }, + }, + ) + response_header = fields.Nested( + NameValuePairSchema, + metadata={ + "optional": True, + "externalDocs": { + "description": "Python Regex", + "url": "https://docs.python.org/3/howto/regex.html", + }, + }, + ) + response_cookie = fields.Nested( + NameValuePairSchema, + metadata={ + "optional": True, + "externalDocs": { + "description": "Python Regex", + "url": "https://docs.python.org/3/howto/regex.html", + }, + }, + ) + json_valid = fields.Boolean( + metadata={"optional": True, "description": "Is valid JSON"} + ) json_path = fields.Str(metadata={"optional": True, "description": "Has JSON path"}) - json_schema = fields.Str(metadata={"optional": True, "description": "Validates against passed JSON schema"}) + json_schema = fields.Str( + metadata={ + "optional": True, + "description": "Validates against passed JSON schema", + } + ) error_if_no_traffic = fields.Boolean( metadata={ "optional": True, "default": True, - "description": "If the proxy has NO traffic at all, return error"}) + "description": "If the proxy has NO traffic at all, return error", + } + ) class Meta: ordered = True description = """A set of criteria for filtering HTTP Requests and Responses. Criteria are AND based, and use python regular expressions for string comparison""" - externalDocs = {"description": "Python Regex Doc", "url": "https://docs.python.org/3/howto/regex.html"} + externalDocs = { + "description": "Python Regex Doc", + "url": "https://docs.python.org/3/howto/regex.html", + } diff --git a/mitmproxy/addons/browserup/har/har_verifications.py b/mitmproxy/addons/browserup/har/har_verifications.py index b881a22236..fe0cee3a3e 100644 --- a/mitmproxy/addons/browserup/har/har_verifications.py +++ b/mitmproxy/addons/browserup/har/har_verifications.py @@ -3,11 +3,11 @@ from glom import glom from jsonpath_ng import parse -from jsonschema import ValidationError, validate +from jsonschema import validate +from jsonschema import ValidationError class HarVerifications: - def __init__(self, har): self.har = har @@ -37,11 +37,11 @@ def rmatch_key_val(self, items, kv): return False for item in items: - if 'name' in kv: - name = self.rmatch(item['name'], kv['name']) + if "name" in kv: + name = self.rmatch(item["name"], kv["name"]) - if 'value' in kv: - value = self.rmatch(kv['value'], item['value']) + if "value" in kv: + value = self.rmatch(kv["value"], item["value"]) if name and value: return True @@ -74,45 +74,94 @@ def has_json_path(self, json_str, json_path): return len(matches) > 0 def current_page(self): - return self.har['log']['pages'][-1]['id'] + return self.har["log"]["pages"][-1]["id"] def no_entries(self): - (self.har['log']['entries'] is None) or (len(self.har['log']['entries']) == 0) + (self.har["log"]["entries"] is None) or (len(self.har["log"]["entries"]) == 0) def entries(self, criteria=False): # Use glom to dig into the har entries, responses and websockets to get down to an array of something or others # (headers, websocket messages, content then we execute our test against that item # current, *, or filter - entry_list = self.har['log']['entries'] + entry_list = self.har["log"]["entries"] har_entry_filters = { - 'page': (lambda item, pgref: glom(item, 'pageref', default='') == pgref), - - 'status': (lambda item, status: self.rmatch(str(glom(item, 'response.status', default=None)), status)), - 'url': (lambda item, url_rxp: self.rmatch(str(glom(item, 'request.url', default=None)), url_rxp)), - 'content': (lambda item, content_rxp: self.rmatch(str(glom(item, 'response.content.text', default=None)), content_rxp)), - 'content_type': (lambda item, content_type_rxp: self.rmatch(str(glom(item, 'response.content.mimeType', default=None)), - content_type_rxp)), - 'request_header': (lambda item, match_rgxp: self.rmatch_key_val(glom(item, 'request.headers', default=[]), match_rgxp)), - 'response_header': (lambda item, match_rgxp: self.rmatch_key_val(glom(item, 'response.headers', default=[]), match_rgxp)), - 'request_cookie': (lambda item, match_rgxp: self.rmatch_key_val(glom(item, 'request.cookies', default=[]), match_rgxp)), - 'response_cookie': (lambda item, match_rgxp: self.rmatch_key_val(glom(item, 'response.cookies', default=[]), match_rgxp)), - 'websocket_message': (lambda item, ws_rxp: self.rmatch_any(glom(item, ('_webSocketMessages', ['data']), default=[]), ws_rxp)), - 'json_valid': (lambda item, _: self.valid_json(str(glom(item, 'response.content.text', default=None)))), - 'json_path': (lambda item, path: self.has_json_path(str(glom(item, 'response.content.text', default=None)), path)), - 'json_schema': (lambda item, schema: self.schema_validate(str(glom(item, 'response.content.text', default=None)), schema)), + "page": (lambda item, pgref: glom(item, "pageref", default="") == pgref), + "status": ( + lambda item, status: self.rmatch( + str(glom(item, "response.status", default=None)), status + ) + ), + "url": ( + lambda item, url_rxp: self.rmatch( + str(glom(item, "request.url", default=None)), url_rxp + ) + ), + "content": ( + lambda item, content_rxp: self.rmatch( + str(glom(item, "response.content.text", default=None)), content_rxp + ) + ), + "content_type": ( + lambda item, content_type_rxp: self.rmatch( + str(glom(item, "response.content.mimeType", default=None)), + content_type_rxp, + ) + ), + "request_header": ( + lambda item, match_rgxp: self.rmatch_key_val( + glom(item, "request.headers", default=[]), match_rgxp + ) + ), + "response_header": ( + lambda item, match_rgxp: self.rmatch_key_val( + glom(item, "response.headers", default=[]), match_rgxp + ) + ), + "request_cookie": ( + lambda item, match_rgxp: self.rmatch_key_val( + glom(item, "request.cookies", default=[]), match_rgxp + ) + ), + "response_cookie": ( + lambda item, match_rgxp: self.rmatch_key_val( + glom(item, "response.cookies", default=[]), match_rgxp + ) + ), + "websocket_message": ( + lambda item, ws_rxp: self.rmatch_any( + glom(item, ("_webSocketMessages", ["data"]), default=[]), ws_rxp + ) + ), + "json_valid": ( + lambda item, _: self.valid_json( + str(glom(item, "response.content.text", default=None)) + ) + ), + "json_path": ( + lambda item, path: self.has_json_path( + str(glom(item, "response.content.text", default=None)), path + ) + ), + "json_schema": ( + lambda item, schema: self.schema_validate( + str(glom(item, "response.content.text", default=None)), schema + ) + ), } for filter_name, target_value in criteria.items(): filter_lambda = har_entry_filters.get(filter_name, None) if filter_lambda is not None: - if filter_name == 'page' and target_value == 'current': + if filter_name == "page" and target_value == "current": target_value = self.current_page() - entry_list = [entry for entry in entry_list if filter_lambda(entry, target_value)] + entry_list = [ + entry for entry in entry_list if filter_lambda(entry, target_value) + ] return entry_list def gsize(self, item, path): - return self.not_neg(glom(item, 'request.headersSize', default=0)) + return self.not_neg(glom(item, "request.headersSize", default=0)) def not_neg(self, val): val = int(val) @@ -120,13 +169,19 @@ def not_neg(self, val): def measure(self, items, measurement): measurements = { - 'request_headers': (lambda item: self.gsize(item, 'request.headersSize')), - 'response_headers': (lambda item: self.gsize(item, 'response.headersSize')), - 'request_body': (lambda item: self.gsize(item, 'request.bodySize')), - 'response_body': (lambda item: self.gsize(item, 'request.bodySize')), - 'request': (lambda item: self.gsize(item, 'request.bodySize') + self.gsize(item, 'request.headerSize')), - 'response': (lambda item: self.gsize(item, 'response.bodySize') + self.gsize(item, 'response.headerSize')), - 'time': (lambda item: self.gsize(item, 'time')), + "request_headers": (lambda item: self.gsize(item, "request.headersSize")), + "response_headers": (lambda item: self.gsize(item, "response.headersSize")), + "request_body": (lambda item: self.gsize(item, "request.bodySize")), + "response_body": (lambda item: self.gsize(item, "request.bodySize")), + "request": ( + lambda item: self.gsize(item, "request.bodySize") + + self.gsize(item, "request.headerSize") + ), + "response": ( + lambda item: self.gsize(item, "response.bodySize") + + self.gsize(item, "response.headerSize") + ), + "time": (lambda item: self.gsize(item, "time")), } method = measurements[measurement] return list(map(method, items)) diff --git a/mitmproxy/addons/browserup/har_capture_addon.py b/mitmproxy/addons/browserup/har_capture_addon.py index 32bf03c097..775764fbc6 100644 --- a/mitmproxy/addons/browserup/har_capture_addon.py +++ b/mitmproxy/addons/browserup/har_capture_addon.py @@ -4,50 +4,54 @@ from mitmproxy.addons.browserup.har import flow_har_entry_patch from mitmproxy.addons.browserup.har.flow_capture import FlowCaptureMixin from mitmproxy.addons.browserup.har.har_manager import HarManagerMixin -from mitmproxy.addons.browserup.har.har_resources import ( - CounterResource, ErrorResource, HarCaptureTypesResource, HarPageResource, - HarResource, HealthCheckResource, NotPresentResource, PresentResource, - SizeResource, SLAResource) +from mitmproxy.addons.browserup.har.har_resources import CounterResource +from mitmproxy.addons.browserup.har.har_resources import ErrorResource +from mitmproxy.addons.browserup.har.har_resources import HarCaptureTypesResource +from mitmproxy.addons.browserup.har.har_resources import HarPageResource +from mitmproxy.addons.browserup.har.har_resources import HarResource +from mitmproxy.addons.browserup.har.har_resources import HealthCheckResource +from mitmproxy.addons.browserup.har.har_resources import NotPresentResource +from mitmproxy.addons.browserup.har.har_resources import PresentResource +from mitmproxy.addons.browserup.har.har_resources import SizeResource +from mitmproxy.addons.browserup.har.har_resources import SLAResource flow_har_entry_patch.patch_flow() # patch flow object with a har entry method class HarCaptureAddOn(FlowCaptureMixin, HarManagerMixin): - def load(self, l): - logging.info('Loading HarCaptureAddon') + logging.info("Loading HarCaptureAddon") l.add_option("harcapture", str, "", "HAR capture path.") def get_resources(self): - return [HarResource(self), - HarPageResource(self), - HarCaptureTypesResource(self), - PresentResource(self), - NotPresentResource(self), - SizeResource(self), - SLAResource(self), - ErrorResource(self), - CounterResource(self), - HealthCheckResource() - ] + return [ + HarResource(self), + HarPageResource(self), + HarCaptureTypesResource(self), + PresentResource(self), + NotPresentResource(self), + SizeResource(self), + SLAResource(self), + ErrorResource(self), + CounterResource(self), + HealthCheckResource(), + ] def websocket_message(self, flow: mitmproxy.http.HTTPFlow): - if 'blocklisted' in flow.metadata: + if "blocklisted" in flow.metadata: return self.capture_websocket_message(flow) def request(self, flow: mitmproxy.http.HTTPFlow): - if 'blocklisted' in flow.metadata: + if "blocklisted" in flow.metadata: return self.capture_request(flow) def response(self, flow: mitmproxy.http.HTTPFlow): - if 'blocklisted' in flow.metadata: - logging.debug('Blocklist filtered, return nothing.') + if "blocklisted" in flow.metadata: + logging.debug("Blocklist filtered, return nothing.") return self.capture_response(flow) -addons = [ - HarCaptureAddOn() -] +addons = [HarCaptureAddOn()] diff --git a/mitmproxy/addons/browserup/latency_addon.py b/mitmproxy/addons/browserup/latency_addon.py index 92d2afdee6..275ab47a49 100644 --- a/mitmproxy/addons/browserup/latency_addon.py +++ b/mitmproxy/addons/browserup/latency_addon.py @@ -2,7 +2,6 @@ class LatencyResource: - def addon_path(self): return "latency/{latency}" @@ -29,7 +28,6 @@ def on_put(self, req, resp, latency): class LatencyAddOn: - def __init__(self): self.num = 0 self.latency_ms = 0 @@ -42,6 +40,4 @@ def response(self, flow): sleep(self.latency_ms / 1000) -addons = [ - LatencyAddOn() -] +addons = [LatencyAddOn()] diff --git a/mitmproxy/addons/browserup/schemas/__init__.py b/mitmproxy/addons/browserup/schemas/__init__.py index 47d1474dff..1e58eeae92 100644 --- a/mitmproxy/addons/browserup/schemas/__init__.py +++ b/mitmproxy/addons/browserup/schemas/__init__.py @@ -1,10 +1,29 @@ -from mitmproxy.addons import (anticache, anticomp, block, blocklist, browser, - clientplayback, command_history, core, cut, - disable_h2c, export, maplocal, mapremote, - modifybody, modifyheaders, next_layer, - onboarding, proxyauth, proxyserver, save, script, - serverplayback, stickyauth, stickycookie, - tlsconfig, upstream_auth) +from mitmproxy.addons import anticache +from mitmproxy.addons import anticomp +from mitmproxy.addons import block +from mitmproxy.addons import blocklist +from mitmproxy.addons import browser +from mitmproxy.addons import clientplayback +from mitmproxy.addons import command_history +from mitmproxy.addons import core +from mitmproxy.addons import cut +from mitmproxy.addons import disable_h2c +from mitmproxy.addons import export +from mitmproxy.addons import maplocal +from mitmproxy.addons import mapremote +from mitmproxy.addons import modifybody +from mitmproxy.addons import modifyheaders +from mitmproxy.addons import next_layer +from mitmproxy.addons import onboarding +from mitmproxy.addons import proxyauth +from mitmproxy.addons import proxyserver +from mitmproxy.addons import save +from mitmproxy.addons import script +from mitmproxy.addons import serverplayback +from mitmproxy.addons import stickyauth +from mitmproxy.addons import stickycookie +from mitmproxy.addons import tlsconfig +from mitmproxy.addons import upstream_auth def default_addons(): diff --git a/mitmproxy/tools/browserup_proxy.py b/mitmproxy/tools/browserup_proxy.py index 51a863cdb4..76db960a0e 100644 --- a/mitmproxy/tools/browserup_proxy.py +++ b/mitmproxy/tools/browserup_proxy.py @@ -2,23 +2,25 @@ # Keep an eye on dump.py for updates to incorporate from mitmproxy import addons -from mitmproxy import options from mitmproxy import master - -from mitmproxy.addons import dumper, termlog, keepserving, readfile -from mitmproxy.addons.browserup import har_capture_addon, \ - browserup_addons_manager, latency_addon, browser_data_addon - +from mitmproxy import options +from mitmproxy.addons import dumper +from mitmproxy.addons import keepserving +from mitmproxy.addons import readfile +from mitmproxy.addons import termlog +from mitmproxy.addons.browserup import browser_data_addon +from mitmproxy.addons.browserup import browserup_addons_manager +from mitmproxy.addons.browserup import har_capture_addon +from mitmproxy.addons.browserup import latency_addon from mitmproxy.addons.errorcheck import ErrorCheck class BrowserupProxyMaster(master.Master): - def __init__( - self, - options: options.Options, - with_termlog=True, - with_dumper=True, + self, + options: options.Options, + with_termlog=True, + with_dumper=True, ) -> None: super().__init__(options) self.errorcheck = ErrorCheck() @@ -29,10 +31,12 @@ def __init__( self.addons.add(dumper.Dumper()) harCaptureAddon = har_capture_addon.HarCaptureAddOn() - self.addons.add(browserup_addons_manager.BrowserUpAddonsManagerAddOn(), harCaptureAddon, - browser_data_addon.BrowserDataAddOn(harCaptureAddon), latency_addon.LatencyAddOn()) self.addons.add( - keepserving.KeepServing(), - readfile.ReadFileStdin(), - self.errorcheck + browserup_addons_manager.BrowserUpAddonsManagerAddOn(), + harCaptureAddon, + browser_data_addon.BrowserDataAddOn(harCaptureAddon), + latency_addon.LatencyAddOn(), + ) + self.addons.add( + keepserving.KeepServing(), readfile.ReadFileStdin(), self.errorcheck ) diff --git a/release/cibuild.py b/release/cibuild.py index 586fbe7a39..5f95ba9f5a 100755 --- a/release/cibuild.py +++ b/release/cibuild.py @@ -13,7 +13,8 @@ import zipfile from dataclasses import dataclass from pathlib import Path -from typing import Optional, Union +from typing import Optional +from typing import Union import click import cryptography.fernet @@ -85,7 +86,9 @@ def from_env(cls) -> "BuildEnviron": if ref.startswith("refs/tags/"): tag = ref.replace("refs/tags/", "") - is_pull_request = os.environ.get("GITHUB_EVENT_NAME", "pull_request") == "pull_request" + is_pull_request = ( + os.environ.get("GITHUB_EVENT_NAME", "pull_request") == "pull_request" + ) return cls( system=platform.system(), @@ -98,7 +101,8 @@ def from_env(cls) -> "BuildEnviron": should_build_wininstaller=bool_from_env("CI_BUILD_WININSTALLER"), should_build_docker=bool_from_env("CI_BUILD_DOCKER"), has_aws_creds=bool_from_env("AWS_ACCESS_KEY_ID"), - has_twine_creds=bool_from_env("TWINE_USERNAME") and bool_from_env("TWINE_PASSWORD"), + has_twine_creds=bool_from_env("TWINE_USERNAME") + and bool_from_env("TWINE_PASSWORD"), docker_username=os.environ.get("DOCKER_USERNAME", None), docker_password=os.environ.get("DOCKER_PASSWORD", None), build_key=os.environ.get("CI_BUILD_KEY", None), @@ -169,7 +173,9 @@ def check_version(self) -> None: if self.is_prod_release: # For production releases, we require strict version equality if self.version != version: - raise ValueError(f"Tag is {self.tag}, but mitmproxy/version.py is {version}.") + raise ValueError( + f"Tag is {self.tag}, but mitmproxy/version.py is {version}." + ) elif not self.is_maintenance_branch: # Commits on maintenance branches don't need the dev suffix. This # allows us to incorporate and test commits between tagged releases. @@ -177,12 +183,14 @@ def check_version(self) -> None: # dev release. version_info = parver.Version.parse(version) if not version_info.is_devrelease: - raise ValueError(f"Non-production releases must have dev suffix: {version}") + raise ValueError( + f"Non-production releases must have dev suffix: {version}" + ) @property def is_maintenance_branch(self) -> bool: """ - Is this an untagged commit on a maintenance branch? + Is this an untagged commit on a maintenance branch? """ if not self.tag and self.branch and re.match(r"v\d+\.x", self.branch): return True @@ -214,26 +222,36 @@ def release_dir(self) -> Path: @property def should_upload_docker(self) -> bool: - return all([ - (self.is_prod_release or self.branch in ["main", "dockertest"]), - self.should_build_docker, - self.has_docker_creds, - ]) + return all( + [ + (self.is_prod_release or self.branch in ["main", "dockertest"]), + self.should_build_docker, + self.has_docker_creds, + ] + ) @property def should_upload_aws(self) -> bool: - return all([ - self.has_aws_creds, - (self.should_build_wheel or self.should_build_pyinstaller or self.should_build_wininstaller), - ]) + return all( + [ + self.has_aws_creds, + ( + self.should_build_wheel + or self.should_build_pyinstaller + or self.should_build_wininstaller + ), + ] + ) @property def should_upload_pypi(self) -> bool: - return all([ - self.is_prod_release, - self.should_build_wheel, - self.has_twine_creds, - ]) + return all( + [ + self.is_prod_release, + self.should_build_wheel, + self.has_twine_creds, + ] + ) @property def upload_dir(self) -> str: @@ -255,19 +273,24 @@ def version(self) -> str: elif self.branch: return self.branch else: - raise BuildError("We're on neither a tag nor a branch - could not establish version") + raise BuildError( + "We're on neither a tag nor a branch - could not establish version" + ) def build_wheel(be: BuildEnviron) -> None: # pragma: no cover click.echo("Building wheel...") - subprocess.check_call([ - "python", - "setup.py", - "-q", - "bdist_wheel", - "--dist-dir", be.dist_dir, - ]) - whl, = be.dist_dir.glob('mitmproxy-*-py3-none-any.whl') + subprocess.check_call( + [ + "python", + "setup.py", + "-q", + "bdist_wheel", + "--dist-dir", + be.dist_dir, + ] + ) + (whl,) = be.dist_dir.glob("mitmproxy-*-py3-none-any.whl") click.echo(f"Found wheel package: {whl}") subprocess.check_call(["tox", "-e", "wheeltest", "--", whl]) @@ -278,36 +301,55 @@ def build_wheel(be: BuildEnviron) -> None: # pragma: no cover def build_docker_image(be: BuildEnviron) -> None: # pragma: no cover click.echo("Building Docker images...") - whl, = be.dist_dir.glob('mitmproxy-*-py3-none-any.whl') + (whl,) = be.dist_dir.glob("mitmproxy-*-py3-none-any.whl") docker_build_dir = be.release_dir / "docker" shutil.copy(whl, docker_build_dir / whl.name) - subprocess.check_call([ - "docker", "buildx", "build", - "--tag", be.docker_tag, - "--platform", DOCKER_PLATFORMS, - "--build-arg", f"MITMPROXY_WHEEL={whl.name}", - "." - ], cwd=docker_build_dir) + subprocess.check_call( + [ + "docker", + "buildx", + "build", + "--tag", + be.docker_tag, + "--platform", + DOCKER_PLATFORMS, + "--build-arg", + f"MITMPROXY_WHEEL={whl.name}", + ".", + ], + cwd=docker_build_dir, + ) # smoke-test the newly built docker image # build again without --platform but with --load to make the tag available, # see https://github.com/docker/buildx/issues/59#issuecomment-616050491 - subprocess.check_call([ - "docker", "buildx", "build", - "--tag", be.docker_tag, - "--load", - "--build-arg", f"MITMPROXY_WHEEL={whl.name}", - "." - ], cwd=docker_build_dir) - r = subprocess.run([ - "docker", - "run", - "--rm", - be.docker_tag, - "mitmdump", - "--version", - ], check=True, capture_output=True) + subprocess.check_call( + [ + "docker", + "buildx", + "build", + "--tag", + be.docker_tag, + "--load", + "--build-arg", + f"MITMPROXY_WHEEL={whl.name}", + ".", + ], + cwd=docker_build_dir, + ) + r = subprocess.run( + [ + "docker", + "run", + "--rm", + be.docker_tag, + "mitmdump", + "--version", + ], + check=True, + capture_output=True, + ) print(r.stdout.decode()) assert "Mitmproxy: " in r.stdout.decode() @@ -332,9 +374,11 @@ def build_pyinstaller(be: BuildEnviron) -> None: # pragma: no cover [ "pyinstaller", "--clean", - "--workpath", PYINSTALLER_TEMP, - "--distpath", PYINSTALLER_DIST, - "./windows-dir.spec" + "--workpath", + PYINSTALLER_TEMP, + "--distpath", + PYINSTALLER_DIST, + "./windows-dir.spec", ] ) for tool in ["mitmproxy", "mitmdump", "mitmweb", "browserup-proxy"]: @@ -357,15 +401,19 @@ def build_pyinstaller(be: BuildEnviron) -> None: # pragma: no cover excludes.append("mitmproxy.tools.console") subprocess.check_call( - [ # type: ignore + [ # type: ignore "pyinstaller", "--clean", - "--workpath", PYINSTALLER_TEMP, - "--distpath", PYINSTALLER_DIST, - "--additional-hooks-dir", PYINSTALLER_HOOKS, + "--workpath", + PYINSTALLER_TEMP, + "--distpath", + PYINSTALLER_DIST, + "--additional-hooks-dir", + PYINSTALLER_HOOKS, "--onefile", "--console", - "--icon", "icon.ico", + "--icon", + "icon.ico", ] + [x for e in excludes for x in ["--exclude-module", e]] + [tool] @@ -398,7 +446,9 @@ def build_wininstaller(be: BuildEnviron) -> None: # pragma: no cover IB_SETUP_SHA256 = "2bc9f9945cb727ad176aa31fa2fa5a8c57a975bad879c169b93e312af9d05814" IB_DIR = be.release_dir / "installbuilder" IB_SETUP = IB_DIR / "setup" / f"{IB_VERSION}-installer.exe" - IB_CLI = Path(fr"C:\Program Files\VMware InstallBuilder Enterprise {IB_VERSION}\bin\builder-cli.exe") + IB_CLI = Path( + rf"C:\Program Files\VMware InstallBuilder Enterprise {IB_VERSION}\bin\builder-cli.exe" + ) IB_LICENSE = IB_DIR / "license.xml" if not IB_LICENSE.exists() and not be.build_key: @@ -418,7 +468,7 @@ def report(block, blocksize, total): urllib.request.urlretrieve( f"https://clients.bitrock.com/installbuilder/installbuilder-enterprise-{IB_VERSION}-windows-x64-installer.exe", tmp, - reporthook=report + reporthook=report, ) tmp.rename(IB_SETUP) @@ -433,27 +483,36 @@ def report(block, blocksize, total): raise RuntimeError("InstallBuilder hashes don't match.") click.echo("Install InstallBuilder...") - subprocess.run([IB_SETUP, "--mode", "unattended", "--unattendedmodeui", "none"], check=True) + subprocess.run( + [IB_SETUP, "--mode", "unattended", "--unattendedmodeui", "none"], check=True + ) assert IB_CLI.is_file() if not IB_LICENSE.exists(): assert be.build_key click.echo("Decrypt InstallBuilder license...") f = cryptography.fernet.Fernet(be.build_key.encode()) - with open(IB_LICENSE.with_suffix(".xml.enc"), "rb") as infile, \ - open(IB_LICENSE, "wb") as outfile: + with ( + open(IB_LICENSE.with_suffix(".xml.enc"), "rb") as infile, + open(IB_LICENSE, "wb") as outfile, + ): outfile.write(f.decrypt(infile.read())) click.echo("Run InstallBuilder...") - subprocess.run([ - IB_CLI, - "build", - str(IB_DIR / "mitmproxy.xml"), - "windows", - "--license", str(IB_LICENSE), - "--setvars", f"project.version={be.version}", - "--verbose" - ], check=True) + subprocess.run( + [ + IB_CLI, + "build", + str(IB_DIR / "mitmproxy.xml"), + "windows", + "--license", + str(IB_LICENSE), + "--setvars", + f"project.version={be.version}", + "--verbose", + ], + check=True, + ) assert (be.dist_dir / f"mitmproxy-{be.version}-windows-installer.exe").exists() @@ -468,7 +527,7 @@ def cli(): # pragma: no cover @cli.command("build") def build(): # pragma: no cover """ - Build a binary distribution + Build a binary distribution """ be = BuildEnviron.from_env() be.dump_info() @@ -489,11 +548,11 @@ def build(): # pragma: no cover @cli.command("upload") def upload(): # pragma: no cover """ - Upload build artifacts + Upload build artifacts - Uploads the wheels package to PyPi. - Uploads the Pyinstaller and wheels packages to the snapshot server. - Pushes the Docker image to Docker Hub. + Uploads the wheels package to PyPi. + Uploads the Pyinstaller and wheels packages to the snapshot server. + Pushes the Docker image to Docker Hub. """ be = BuildEnviron.from_env() be.dump_info() @@ -505,50 +564,75 @@ def upload(): # pragma: no cover if be.should_upload_aws: num_files = len([name for name in be.dist_dir.iterdir() if name.is_file()]) click.echo(f"Uploading {num_files} files to AWS dir {be.upload_dir}...") - subprocess.check_call([ - "aws", "s3", "cp", - "--acl", "public-read", - f"{be.dist_dir}/", - f"s3://snapshots.mitmproxy.org/{be.upload_dir}/", - "--recursive", - ]) + subprocess.check_call( + [ + "aws", + "s3", + "cp", + "--acl", + "public-read", + f"{be.dist_dir}/", + f"s3://snapshots.mitmproxy.org/{be.upload_dir}/", + "--recursive", + ] + ) if be.should_upload_pypi: - whl, = be.dist_dir.glob('mitmproxy-*-py3-none-any.whl') + (whl,) = be.dist_dir.glob("mitmproxy-*-py3-none-any.whl") click.echo(f"Uploading {whl} to PyPi...") subprocess.check_call(["twine", "upload", whl]) if be.should_upload_docker: click.echo(f"Uploading Docker image to tag={be.docker_tag}...") - subprocess.check_call([ - "docker", - "login", - "-u", be.docker_username, - "-p", be.docker_password, - ]) + subprocess.check_call( + [ + "docker", + "login", + "-u", + be.docker_username, + "-p", + be.docker_password, + ] + ) - whl, = be.dist_dir.glob('mitmproxy-*-py3-none-any.whl') + (whl,) = be.dist_dir.glob("mitmproxy-*-py3-none-any.whl") docker_build_dir = be.release_dir / "docker" shutil.copy(whl, docker_build_dir / whl.name) # buildx is a bit weird in that we need to reinvoke build, but oh well. - subprocess.check_call([ - "docker", "buildx", "build", - "--tag", be.docker_tag, - "--push", - "--platform", DOCKER_PLATFORMS, - "--build-arg", f"MITMPROXY_WHEEL={whl.name}", - "." - ], cwd=docker_build_dir) + subprocess.check_call( + [ + "docker", + "buildx", + "build", + "--tag", + be.docker_tag, + "--push", + "--platform", + DOCKER_PLATFORMS, + "--build-arg", + f"MITMPROXY_WHEEL={whl.name}", + ".", + ], + cwd=docker_build_dir, + ) if be.is_prod_release: - subprocess.check_call([ - "docker", "buildx", "build", - "--tag", "browserup/mitmproxy:latest", - "--push", - "--platform", DOCKER_PLATFORMS, - "--build-arg", f"MITMPROXY_WHEEL={whl.name}", - "." - ], cwd=docker_build_dir) + subprocess.check_call( + [ + "docker", + "buildx", + "build", + "--tag", + "browserup/mitmproxy:latest", + "--push", + "--platform", + DOCKER_PLATFORMS, + "--build-arg", + f"MITMPROXY_WHEEL={whl.name}", + ".", + ], + cwd=docker_build_dir, + ) if __name__ == "__main__": # pragma: no cover diff --git a/release/hooks/hook-mitmproxy.addons.onboardingapp.py b/release/hooks/hook-mitmproxy.addons.onboardingapp.py index 2b2fe06bac..8269d39509 100644 --- a/release/hooks/hook-mitmproxy.addons.onboardingapp.py +++ b/release/hooks/hook-mitmproxy.addons.onboardingapp.py @@ -1,3 +1,3 @@ from PyInstaller.utils.hooks import collect_data_files -datas = collect_data_files('mitmproxy.addons.onboardingapp') +datas = collect_data_files("mitmproxy.addons.onboardingapp") diff --git a/release/hooks/hook-mitmproxy.py b/release/hooks/hook-mitmproxy.py index f9351f9e0c..73c0bc3231 100644 --- a/release/hooks/hook-mitmproxy.py +++ b/release/hooks/hook-mitmproxy.py @@ -1,7 +1,6 @@ hiddenimports = [ "mitmproxy.script", - "mitmproxy.addons.browserup.*" - "cgi", + "mitmproxy.addons.browserup.*" "cgi", "http.cookies", "wsgiref.validate", "wsgiref.simple_server", @@ -26,5 +25,5 @@ "falcon.errors", "falcon.redirects", "falcon.http_error", - "falcon.http_status" -] \ No newline at end of file + "falcon.http_status", +] diff --git a/release/hooks/hook-mitmproxy.tools.web.py b/release/hooks/hook-mitmproxy.tools.web.py index 519c4c00e9..4078ded4d0 100644 --- a/release/hooks/hook-mitmproxy.tools.web.py +++ b/release/hooks/hook-mitmproxy.tools.web.py @@ -1,3 +1,3 @@ from PyInstaller.utils.hooks import collect_data_files -datas = collect_data_files('mitmproxy.tools.web') +datas = collect_data_files("mitmproxy.tools.web") diff --git a/test/mitmproxy/addons/browserup/test_api.py b/test/mitmproxy/addons/browserup/test_api.py index b837dd83c2..9e61b63f1e 100644 --- a/test/mitmproxy/addons/browserup/test_api.py +++ b/test/mitmproxy/addons/browserup/test_api.py @@ -7,12 +7,14 @@ import mitmproxy.addons.browserup.browserup_addons_manager from mitmproxy.addons.browserup import har_capture_addon -from mitmproxy.test import taddons, tflow, tutils +from mitmproxy.test import taddons +from mitmproxy.test import tflow +from mitmproxy.test import tutils from mitmproxy.utils import data class TestAPI: - def flow(self, resp_content=b'message'): + def flow(self, resp_content=b"message"): times = dict( timestamp_start=746203200, timestamp_end=746203290, @@ -20,8 +22,8 @@ def flow(self, resp_content=b'message'): # Create a dummy flow for testing return tflow.tflow( - req=tutils.treq(method=b'GET', **times), - resp=tutils.tresp(content=resp_content, **times) + req=tutils.treq(method=b"GET", **times), + resp=tutils.tresp(content=resp_content, **times), ) def client(self): @@ -36,58 +38,74 @@ def client(self): # pytest will inject the object returned by the "client" function # as an additional parameter. def test_healthcheck(self, hc): - response = self.client().simulate_get('/healthcheck') + response = self.client().simulate_get("/healthcheck") assert response.status == falcon.HTTP_OK def test_verify_present(self, hc): - response = self.client().simulate_post('/verify/present/FindMyName', json={}) + response = self.client().simulate_post("/verify/present/FindMyName", json={}) assert response.status == falcon.HTTP_OK def test_verify_not_present(self, hc): - response = self.client().simulate_post('/verify/not_present/DontFindMyName', json={}) + response = self.client().simulate_post( + "/verify/not_present/DontFindMyName", json={} + ) assert response.status == falcon.HTTP_OK def test_verify_sla(self, hc): - response = self.client().simulate_post('/verify/sla/10/LoadsFast', json={}) + response = self.client().simulate_post("/verify/sla/10/LoadsFast", json={}) assert response.status == falcon.HTTP_OK def test_verify_size(self, hc): - response = self.client().simulate_post('/verify/size/100/NotTooLarge', json={'error_if_no_traffic': True}) + response = self.client().simulate_post( + "/verify/size/100/NotTooLarge", json={"error_if_no_traffic": True} + ) assert response.status == falcon.HTTP_OK def test_verify_size_bad_match_criteria(self, hc): - response = self.client().simulate_post('/verify/size/100/NotTooLarge', json={'foo': True}) + response = self.client().simulate_post( + "/verify/size/100/NotTooLarge", json={"foo": True} + ) assert response.status == falcon.HTTP_422 def test_add_float_counter(self, hc): - response = self.client().simulate_post('/har/counters', json={'name': 'fooAmount', 'value': 5.0}) + response = self.client().simulate_post( + "/har/counters", json={"name": "fooAmount", "value": 5.0} + ) assert response.status == falcon.HTTP_204 def test_add_integer_counter(self, hc): - response = self.client().simulate_post('/har/counters', json={'name': 'fooAmount', 'value': 5}) + response = self.client().simulate_post( + "/har/counters", json={"name": "fooAmount", "value": 5} + ) assert response.status == falcon.HTTP_204 def test_add_counter_schema_wrong_string_instead_of_number(self, hc): - response = self.client().simulate_post('/har/counters', json={'name': 3, 'value': 'nope'}) + response = self.client().simulate_post( + "/har/counters", json={"name": 3, "value": "nope"} + ) assert response.status == falcon.HTTP_422 def test_add_counter_schema_wrong(self, hc): - response = self.client().simulate_post('/har/counters', json={'name': 3}) + response = self.client().simulate_post("/har/counters", json={"name": 3}) assert response.status == falcon.HTTP_422 def test_add_error(self, hc): - response = self.client().simulate_post('/har/errors', json={'name': 'BadError', 'details': 'Woops, super bad'}) + response = self.client().simulate_post( + "/har/errors", json={"name": "BadError", "details": "Woops, super bad"} + ) assert response.status == falcon.HTTP_204 def test_add_error_schema_wrong(self, hc): - response = self.client().simulate_post('/har/errors', json={'name': 'sdfsd', 'foo': 'Bar'}) + response = self.client().simulate_post( + "/har/errors", json={"name": "sdfsd", "foo": "Bar"} + ) assert response.status == falcon.HTTP_422 @pytest.fixture() def path(tmpdir): d = tempfile.TemporaryDirectory().name - return os.path.join(d, 'test.har') + return os.path.join(d, "test.har") @pytest.fixture() diff --git a/test/mitmproxy/addons/browserup/test_counters.py b/test/mitmproxy/addons/browserup/test_counters.py index 2065b6dae3..05a92a5c68 100644 --- a/test/mitmproxy/addons/browserup/test_counters.py +++ b/test/mitmproxy/addons/browserup/test_counters.py @@ -2,53 +2,54 @@ from mitmproxy import http from mitmproxy.addons.browserup import har_capture_addon -from mitmproxy.test import taddons, tflow, tutils +from mitmproxy.test import taddons +from mitmproxy.test import tflow +from mitmproxy.test import tutils class TestHARCounters: - def test_counter_added(self, hc, flow): - hc.add_counter_to_har({'name': 'time-to-first-paint', 'value': 3}) - assert (len(hc.get_or_create_current_page().get('_counters')) == 1) + hc.add_counter_to_har({"name": "time-to-first-paint", "value": 3}) + assert len(hc.get_or_create_current_page().get("_counters")) == 1 def test_valid_counters_added(self, hc, flow): - hc.add_counter_to_har({'name': 'time-to-first-byte', 'value': 1}) - hc.add_counter_to_har({'name': 'time-to-first-paint', 'value': 2}) - counters = hc.get_or_create_current_page().get('_counters') - assert (len(counters) == 2) - assert (counters[0].get('name') == 'time-to-first-byte') - assert (counters[0].get('value') == 1) - assert (counters[1].get('name') == 'time-to-first-paint') - assert (counters[1].get('value') == 2) + hc.add_counter_to_har({"name": "time-to-first-byte", "value": 1}) + hc.add_counter_to_har({"name": "time-to-first-paint", "value": 2}) + counters = hc.get_or_create_current_page().get("_counters") + assert len(counters) == 2 + assert counters[0].get("name") == "time-to-first-byte" + assert counters[0].get("value") == 1 + assert counters[1].get("name") == "time-to-first-paint" + assert counters[1].get("value") == 2 def test_valid_counter_added_then_reset(self, hc, flow): - hc.add_counter_to_har({'name': 'time-to-first-byte', 'value': 1}) - hc.add_counter_to_har({'name': 'time-to-first-paint', 'value': 2}) - hc.new_page('page1', 'New Page!') - assert (hc.get_or_create_current_page().get('_counters') is None) - hc.add_counter_to_har({'name': 'time-to-first-byte', 'value': 1}) - counters = hc.get_or_create_current_page().get('_counters') - assert (len(counters) == 1) + hc.add_counter_to_har({"name": "time-to-first-byte", "value": 1}) + hc.add_counter_to_har({"name": "time-to-first-paint", "value": 2}) + hc.new_page("page1", "New Page!") + assert hc.get_or_create_current_page().get("_counters") is None + hc.add_counter_to_har({"name": "time-to-first-byte", "value": 1}) + counters = hc.get_or_create_current_page().get("_counters") + assert len(counters) == 1 def test_new_har_empty_counters(self, hc, flow): - hc.add_counter_to_har({'name': 'time-to-first-byte', 'value': 1}) - hc.add_counter_to_har({'name': 'time-to-first-paint', 'value': 2}) + hc.add_counter_to_har({"name": "time-to-first-byte", "value": 1}) + hc.add_counter_to_har({"name": "time-to-first-paint", "value": 2}) hc.reset_har_and_return_old_har() - hc.new_page('page1', 'New Page!') - assert (hc.get_or_create_current_page().get('_counters') is None) + hc.new_page("page1", "New Page!") + assert hc.get_or_create_current_page().get("_counters") is None @pytest.fixture() def flow(): - resp_content = b'message' + resp_content = b"message" times = dict( timestamp_start=746203200, timestamp_end=746203290, ) return tflow.tflow( - req=tutils.treq(method=b'GET', **times), - resp=tutils.tresp(content=resp_content, **times) + req=tutils.treq(method=b"GET", **times), + resp=tutils.tresp(content=resp_content, **times), ) @@ -60,9 +61,17 @@ def json_flow(): ) return tflow.tflow( - req=tutils.treq(method=b'GET', path=b"/path/foo.json", **times), - resp=tutils.tresp(content=b'{"foo": "bar"}', - headers=http.Headers(((b"header-response", b"svalue"), (b"content-type", b"application/json"))), **times) + req=tutils.treq(method=b"GET", path=b"/path/foo.json", **times), + resp=tutils.tresp( + content=b'{"foo": "bar"}', + headers=http.Headers( + ( + (b"header-response", b"svalue"), + (b"content-type", b"application/json"), + ) + ), + **times, + ), ) diff --git a/test/mitmproxy/addons/browserup/test_errors.py b/test/mitmproxy/addons/browserup/test_errors.py index 38436bd201..b6a001425b 100644 --- a/test/mitmproxy/addons/browserup/test_errors.py +++ b/test/mitmproxy/addons/browserup/test_errors.py @@ -2,53 +2,54 @@ from mitmproxy import http from mitmproxy.addons.browserup import har_capture_addon -from mitmproxy.test import taddons, tflow, tutils +from mitmproxy.test import taddons +from mitmproxy.test import tflow +from mitmproxy.test import tutils class TestHARErrors: - def test_valid_error_added(self, hc, flow): - hc.add_error_to_har({'name': 'time-to-first-paint', 'value': 3}) - assert (len(hc.get_or_create_current_page().get('_errors')) == 1) + hc.add_error_to_har({"name": "time-to-first-paint", "value": 3}) + assert len(hc.get_or_create_current_page().get("_errors")) == 1 def test_valid_errors_added(self, hc, flow): - hc.add_error_to_har({'name': 'time-to-first-byte', 'value': 1}) - hc.add_error_to_har({'name': 'time-to-first-paint', 'value': 2}) - errors = hc.get_or_create_current_page().get('_errors') - assert (len(errors) == 2) - assert (errors[0].get('name') == 'time-to-first-byte') - assert (errors[0].get('value') == 1) - assert (errors[1].get('name') == 'time-to-first-paint') - assert (errors[1].get('value') == 2) + hc.add_error_to_har({"name": "time-to-first-byte", "value": 1}) + hc.add_error_to_har({"name": "time-to-first-paint", "value": 2}) + errors = hc.get_or_create_current_page().get("_errors") + assert len(errors) == 2 + assert errors[0].get("name") == "time-to-first-byte" + assert errors[0].get("value") == 1 + assert errors[1].get("name") == "time-to-first-paint" + assert errors[1].get("value") == 2 def test_valid_error_added_then_reset(self, hc, flow): - hc.add_error_to_har({'name': 'time-to-first-byte', 'value': 1}) - hc.add_error_to_har({'name': 'time-to-first-paint', 'value': 2}) - hc.new_page('page1', 'New Page!') - assert (hc.get_or_create_current_page().get('_errors') is None) - hc.add_error_to_har({'name': 'time-to-first-byte', 'value': 1}) - errors = hc.get_or_create_current_page().get('_errors') - assert (len(errors) == 1) + hc.add_error_to_har({"name": "time-to-first-byte", "value": 1}) + hc.add_error_to_har({"name": "time-to-first-paint", "value": 2}) + hc.new_page("page1", "New Page!") + assert hc.get_or_create_current_page().get("_errors") is None + hc.add_error_to_har({"name": "time-to-first-byte", "value": 1}) + errors = hc.get_or_create_current_page().get("_errors") + assert len(errors) == 1 def test_new_har_empty_errors(self, hc, flow): - hc.add_error_to_har({'name': 'time-to-first-byte', 'value': 1}) - hc.add_error_to_har({'name': 'time-to-first-paint', 'value': 2}) + hc.add_error_to_har({"name": "time-to-first-byte", "value": 1}) + hc.add_error_to_har({"name": "time-to-first-paint", "value": 2}) hc.reset_har_and_return_old_har() - hc.new_page('page1', 'New Page!') - assert (hc.get_or_create_current_page().get('_errors') is None) + hc.new_page("page1", "New Page!") + assert hc.get_or_create_current_page().get("_errors") is None @pytest.fixture() def flow(): - resp_content = b'message' + resp_content = b"message" times = dict( timestamp_start=746203200, timestamp_end=746203290, ) return tflow.tflow( - req=tutils.treq(method=b'GET', **times), - resp=tutils.tresp(content=resp_content, **times) + req=tutils.treq(method=b"GET", **times), + resp=tutils.tresp(content=resp_content, **times), ) @@ -60,9 +61,17 @@ def json_flow(): ) return tflow.tflow( - req=tutils.treq(method=b'GET', path=b"/path/foo.json", **times), - resp=tutils.tresp(content=b'{"foo": "bar"}', - headers=http.Headers(((b"header-response", b"svalue"), (b"content-type", b"application/json"))), **times) + req=tutils.treq(method=b"GET", path=b"/path/foo.json", **times), + resp=tutils.tresp( + content=b'{"foo": "bar"}', + headers=http.Headers( + ( + (b"header-response", b"svalue"), + (b"content-type", b"application/json"), + ) + ), + **times, + ), ) diff --git a/test/mitmproxy/addons/browserup/test_har_capture.py b/test/mitmproxy/addons/browserup/test_har_capture.py index 0922e62453..3a05313dd3 100644 --- a/test/mitmproxy/addons/browserup/test_har_capture.py +++ b/test/mitmproxy/addons/browserup/test_har_capture.py @@ -5,18 +5,20 @@ import pytest from wsproto.frame_protocol import Opcode -from mitmproxy import http, websocket +from mitmproxy import http +from mitmproxy import websocket from mitmproxy.addons.browserup import har_capture_addon from mitmproxy.addons.browserup.har.har_capture_types import HarCaptureTypes from mitmproxy.net.http import cookies -from mitmproxy.test import taddons, tflow, tutils +from mitmproxy.test import taddons +from mitmproxy.test import tflow +from mitmproxy.test import tutils from mitmproxy.test.tflow import twebsocketflow from mitmproxy.utils import data class TestHARCapture: - - def flow(self, resp_content=b'message'): + def flow(self, resp_content=b"message"): times = dict( timestamp_start=746203200, timestamp_end=746203290, @@ -24,8 +26,8 @@ def flow(self, resp_content=b'message'): # Create a dummy flow for testing return tflow.tflow( - req=tutils.treq(method=b'GET', **times), - resp=tutils.tresp(content=resp_content, **times) + req=tutils.treq(method=b"GET", **times), + resp=tutils.tresp(content=resp_content, **times), ) def tvideoflow(self): @@ -33,10 +35,7 @@ def tvideoflow(self): req = http.Request.make( "GET", "http://example.com/video.mp4", - headers={ - "Host": "example.com", - "User-Agent": "TestAgent" - } + headers={"Host": "example.com", "User-Agent": "TestAgent"}, ) # Create a response object @@ -45,8 +44,8 @@ def tvideoflow(self): b"video binary data here", # video content (truncated for example) { "Content-Type": "video/mp4", - "Content-Length": "1234567" # replace with actual content length - } + "Content-Length": "1234567", # replace with actual content length + }, ) flow = tflow.tflow(req=req, resp=resp) return flow @@ -58,15 +57,18 @@ def test_capture_dynamic_response_content(self, hc): f_dynamic.response.content = b"Hello World" hc.har_capture_types = [HarCaptureTypes.RESPONSE_DYNAMIC_CONTENT] hc.response(f_dynamic) - assert (hc.har['log']['entries'][0]['response']['content']['text'] == "Hello World") + assert ( + hc.har["log"]["entries"][0]["response"]["content"]["text"] + == "Hello World" + ) # Clear entries for the next test - hc.har['log']['entries'].clear() + hc.har["log"]["entries"].clear() # Test non-dynamic content (Video) f_video = self.tvideoflow() hc.response(f_video) - assert (hc.har['log']['entries'][0]['response']['content']['text'] == "") + assert hc.har["log"]["entries"][0]["response"]["content"]["text"] == "" def test_simple(self, hc, path): # is invoked if there are exceptions @@ -75,40 +77,50 @@ def test_simple(self, hc, path): hc.response(self.flow()) with tempfile.TemporaryDirectory() as tmpdirname: - print('Created temporary directory:', tmpdirname) - file_path = os.path.join(tmpdirname, 'testbase64.har') + print("Created temporary directory:", tmpdirname) + file_path = os.path.join(tmpdirname, "testbase64.har") hc.save_current_har_to_path(file_path) with open(file_path) as inp: har = json.load(inp) assert len(har["log"]["entries"]) == 1 def test_base64(self, hc): - hc.har_capture_types = [HarCaptureTypes.RESPONSE_BINARY_CONTENT, HarCaptureTypes.RESPONSE_CONTENT] + hc.har_capture_types = [ + HarCaptureTypes.RESPONSE_BINARY_CONTENT, + HarCaptureTypes.RESPONSE_CONTENT, + ] - hc.response(self.flow(resp_content=b"foo" + b"\xFF" * 10)) + hc.response(self.flow(resp_content=b"foo" + b"\xff" * 10)) with tempfile.TemporaryDirectory() as tmpdirname: - print('Created temporary directory:', tmpdirname) - file_path = os.path.join(tmpdirname, 'testbase64.har') + print("Created temporary directory:", tmpdirname) + file_path = os.path.join(tmpdirname, "testbase64.har") hc.save_current_har_to_path(file_path) with open(file_path) as inp: har = json.load(inp) - assert har["log"]["entries"][0]["response"]["content"]["encoding"] == "base64" + assert ( + har["log"]["entries"][0]["response"]["content"]["encoding"] + == "base64" + ) def test_format_cookies(self, hc): CA = cookies.CookieAttrs f = hc.format_cookies([("n", "v", CA([("k", "v")]))])[0] - assert f['name'] == "n" - assert f['value'] == "v" - assert not f['httpOnly'] - assert not f['secure'] + assert f["name"] == "n" + assert f["value"] == "v" + assert not f["httpOnly"] + assert not f["secure"] - f = hc.format_cookies([("n", "v", CA([("httponly", None), ("secure", None)]))])[0] - assert f['httpOnly'] - assert f['secure'] + f = hc.format_cookies([("n", "v", CA([("httponly", None), ("secure", None)]))])[ + 0 + ] + assert f["httpOnly"] + assert f["secure"] - f = hc.format_cookies([("n", "v", CA([("expires", "Mon, 24-Aug-2037 00:00:00 GMT")]))])[0] - assert f['expires'] + f = hc.format_cookies( + [("n", "v", CA([("expires", "Mon, 24-Aug-2037 00:00:00 GMT")]))] + )[0] + assert f["expires"] def test_binary(self, hc, path): f = self.flow() @@ -120,7 +132,7 @@ def test_binary(self, hc, path): hc.response(f) with tempfile.TemporaryDirectory() as tmpdirname: - file_path = os.path.join(tmpdirname, 'testbase64.har') + file_path = os.path.join(tmpdirname, "testbase64.har") hc.save_current_har_to_path(file_path) with open(file_path) as inp: har = json.load(inp) @@ -129,45 +141,48 @@ def test_binary(self, hc, path): def test_capture_cookies_on(self, hc): f = self.flow() f.request.headers["cookie"] = "foo=bar" - hc.har_capture_types = [HarCaptureTypes.REQUEST_COOKIES, HarCaptureTypes.REQUEST_CAPTURE_TYPES.REQUEST_CONTENT] + hc.har_capture_types = [ + HarCaptureTypes.REQUEST_COOKIES, + HarCaptureTypes.REQUEST_CAPTURE_TYPES.REQUEST_CONTENT, + ] hc.request(f) - assert (hc.har['log']['entries'][0]['request']['cookies'][0]['name'] == 'foo') - assert (hc.har['log']['entries'][0]['request']['cookies'][0]['value'] == 'bar') + assert hc.har["log"]["entries"][0]["request"]["cookies"][0]["name"] == "foo" + assert hc.har["log"]["entries"][0]["request"]["cookies"][0]["value"] == "bar" def test_capture_cookies_off(self, hc): f = self.flow() f.request.headers["cookie"] = "foo=bar" hc.har_capture_types = [HarCaptureTypes.REQUEST_CAPTURE_TYPES.REQUEST_CONTENT] hc.request(f) - assert (hc.har['log']['entries'][0]['request']['cookies'] == []) + assert hc.har["log"]["entries"][0]["request"]["cookies"] == [] def test_capture_request_headers_on(self, hc): f = self.flow() f.request.headers["boo"] = "baz" hc.har_capture_types = [HarCaptureTypes.REQUEST_CAPTURE_TYPES.REQUEST_HEADERS] hc.request(f) - assert (hc.har['log']['entries'][0]['request']['headers'][2]['name'] == 'boo') + assert hc.har["log"]["entries"][0]["request"]["headers"][2]["name"] == "boo" def test_capture_request_headers_off(self, hc): f = self.flow() f.request.headers["cookie"] = "foo=bar" hc.har_capture_types = [] hc.request(f) - assert (hc.har['log']['entries'][0]['request']['headers'] == []) + assert hc.har["log"]["entries"][0]["request"]["headers"] == [] def test_capture_response_headers_on(self, hc): f = self.flow() f.response.headers["bee"] = "bazl" hc.har_capture_types = [HarCaptureTypes.RESPONSE_HEADERS] hc.response(f) - assert (hc.har['log']['entries'][0]['response']['headers'][2]['name'] == 'bee') + assert hc.har["log"]["entries"][0]["response"]["headers"][2]["name"] == "bee" def test_capture_response_headers_off(self, hc): f = self.flow() f.response.headers["bee"] = "bazl" hc.har_capture_types = [] hc.response(f) - assert (hc.har['log']['entries'][0]['response']['headers'] == []) + assert hc.har["log"]["entries"][0]["response"]["headers"] == [] def test_websocket_messages_capture_off(self, hc): f = twebsocketflow() @@ -175,7 +190,7 @@ def test_websocket_messages_capture_off(self, hc): hc.response(f) hc.websocket_message(f) - assert (len(hc.har['log']['entries'][0]['_webSocketMessages']) == 0) + assert len(hc.har["log"]["entries"][0]["_webSocketMessages"]) == 0 def test_websocket_messages_capture_on(self, hc): f = twebsocketflow() @@ -187,22 +202,22 @@ def test_websocket_messages_capture_on(self, hc): hc.websocket_message(f) f.websocket.messages = [ websocket.WebSocketMessage(Opcode.BINARY, True, b"hello binary", 946681203), - websocket.WebSocketMessage(Opcode.TEXT, True, b"hello text", 946681204) + websocket.WebSocketMessage(Opcode.TEXT, True, b"hello text", 946681204), ] hc.websocket_message(f) - assert (hc.har['log']['entries'][0]['_webSocketMessages']) + assert hc.har["log"]["entries"][0]["_webSocketMessages"] def test_capture_response_on(self, hc): f = self.flow() hc.har_capture_types = [HarCaptureTypes.RESPONSE_CONTENT] hc.response(f) - assert (hc.har['log']['entries'][0]['response']['content']['text'] != "") + assert hc.har["log"]["entries"][0]["response"]["content"]["text"] != "" def test_capture_response_off(self, hc): f = self.flow() hc.har_capture_types = [] hc.response(f) - assert (hc.har['log']['entries'][0]['response']['content']['text'] == "") + assert hc.har["log"]["entries"][0]["response"]["content"]["text"] == "" # if har is cleared, where do existing flow har_entries point? def test_new_har_clears_har(self, hc): @@ -210,62 +225,59 @@ def test_new_har_clears_har(self, hc): hc.har_capture_types = [] hc.response(f) hc.reset_har_and_return_old_har() - assert (len(hc.har['log']['entries']) == 0) - f = tflow.tflow( - req=tutils.treq(method=b'GET'), - resp=tutils.tresp() - ) + assert len(hc.har["log"]["entries"]) == 0 + f = tflow.tflow(req=tutils.treq(method=b"GET"), resp=tutils.tresp()) hc.request(f) - assert (len(hc.har['log']['pages']) == 1) + assert len(hc.har["log"]["pages"]) == 1 def test_blank_default_page(self, hc): f = self.flow() hc.request(f) - assert (hc.har['log']['pages'][0]['id'] == "page_1") - assert (hc.har['log']['pages'][0]['title'] == "Default") + assert hc.har["log"]["pages"][0]["id"] == "page_1" + assert hc.har["log"]["pages"][0]["title"] == "Default" hc.reset_har_and_return_old_har() - assert (len(hc.har['log']['pages']) == 1) + assert len(hc.har["log"]["pages"]) == 1 def test_har_entries_timings(self, hc): f = self.flow() hc.request(f) - assert (hc.har['log']['pages'][0]['id'] == "page_1") + assert hc.har["log"]["pages"][0]["id"] == "page_1" def test_reset_har_removes_pages_and_entries(self, hc): f = self.flow() hc.request(f) hc.reset_har_and_return_old_har() - assert (len(hc.har['log']['pages']) == 1) - assert (len(hc.har['log']['entries']) == 0) + assert len(hc.har["log"]["pages"]) == 1 + assert len(hc.har["log"]["entries"]) == 0 # test reset returns old har def test_reset_returns_old_har(self, hc): f = self.flow() hc.request(f) old_har = hc.reset_har_and_return_old_har() - assert (len(old_har['log']['pages']) == 1) - assert (len(old_har['log']['entries']) == 1) + assert len(old_har["log"]["pages"]) == 1 + assert len(old_har["log"]["entries"]) == 1 def test_reset_inits_empty_first_page(self, hc): f = self.flow() hc.request(f) hc.reset_har_and_return_old_har() - assert (len(hc.har['log']['pages']) == 1) - assert (len(hc.har['log']['entries']) == 0) + assert len(hc.har["log"]["pages"]) == 1 + assert len(hc.har["log"]["entries"]) == 0 def test_filter_submitted_entries(self, hc): f = self.flow() hc.request(f) hc.reset_har_and_return_old_har() - assert (len(hc.har['log']['pages']) == 1) - assert (len(hc.har['log']['entries']) == 0) + assert len(hc.har["log"]["pages"]) == 1 + assert len(hc.har["log"]["entries"]) == 0 def test_clean_har(self, hc): f = self.flow() hc.request(f) hc.reset_har_and_return_old_har() - assert (len(hc.har['log']['pages']) == 1) - assert (len(hc.har['log']['entries']) == 0) + assert len(hc.har["log"]["pages"]) == 1 + assert len(hc.har["log"]["entries"]) == 0 def test_uncleaned_video_har_entries_still_there(self, hc): f = self.tvideoflow() @@ -273,15 +285,15 @@ def test_uncleaned_video_har_entries_still_there(self, hc): hc.response(f) h = hc.create_filtered_har_and_track_submitted() - assert (len(h['log']['entries']) == 1) + assert len(h["log"]["entries"]) == 1 - assert (hc.har['log']['entries'][0]['request']['_submitted'] is True) - assert (not hc.har['log']['entries'][0]['response'].get('_submitted')) + assert hc.har["log"]["entries"][0]["request"]["_submitted"] is True + assert not hc.har["log"]["entries"][0]["response"].get("_submitted") # test filtering hc.reset_har_and_return_old_har() - assert (len(hc.har['log']['pages']) == 1) - assert (len(hc.har['log']['entries']) == 0) + assert len(hc.har["log"]["pages"]) == 1 + assert len(hc.har["log"]["entries"]) == 0 def test_uncleaned_websocket_har_entries_still_there(self, hc): f = self.flow() @@ -297,22 +309,22 @@ def test_uncleaned_websocket_har_entries_still_there(self, hc): hc.websocket_message(f) f.websocket.messages = [ websocket.WebSocketMessage(Opcode.BINARY, True, b"hello binary", 946681203), - websocket.WebSocketMessage(Opcode.TEXT, True, b"hello text", 946681204) + websocket.WebSocketMessage(Opcode.TEXT, True, b"hello text", 946681204), ] hc.websocket_message(f) hc.create_filtered_har_and_track_submitted() - assert (len(hc.har['log']['entries']) == 2) - assert (hc.har['log']['entries'][0]['request'].get('_submitted')) + assert len(hc.har["log"]["entries"]) == 2 + assert hc.har["log"]["entries"][0]["request"].get("_submitted") - assert (hc.har['log']['entries'][1]['request'].get('_submitted')) - assert (not hc.har['log']['entries'][1]['response'].get('_submitted')) + assert hc.har["log"]["entries"][1]["request"].get("_submitted") + assert not hc.har["log"]["entries"][1]["response"].get("_submitted") # test filtering hc.reset_har_and_return_old_har() - assert (len(hc.har['log']['pages']) == 1) - assert (len(hc.har['log']['entries']) == 0) + assert len(hc.har["log"]["pages"]) == 1 + assert len(hc.har["log"]["entries"]) == 0 def test_full_submit(self, hc): # combine video and websocket flows and regular flow. @@ -329,28 +341,28 @@ def test_full_submit(self, hc): hc.request(f) f = self.flow() - filtered_result = hc.create_filtered_har_and_track_submitted(report_last_page = True, - include_websockets = True, - include_videos = True) + filtered_result = hc.create_filtered_har_and_track_submitted( + report_last_page=True, include_websockets=True, include_videos=True + ) - assert (len(filtered_result['log']['entries']) == 3) + assert len(filtered_result["log"]["entries"]) == 3 # loop through har entries and assert that they are all submitted - for entry in hc.har['log']['entries']: - assert (entry['request'].get('_submitted')) - assert (entry['response'].get('_submitted')) + for entry in hc.har["log"]["entries"]: + assert entry["request"].get("_submitted") + assert entry["response"].get("_submitted") # loop through har pages and assert that they are all submitted - for page in hc.har['log']['pages']: - assert (page.get('_submitted')) + for page in hc.har["log"]["pages"]: + assert page.get("_submitted") old_har = hc.reset_har_and_return_old_har() - assert (len(old_har['log']['entries']) == 3) + assert len(old_har["log"]["entries"]) == 3 - assert (len(hc.har['log']['entries']) == 0) + assert len(hc.har["log"]["entries"]) == 0 - assert (len(hc.har['log']['pages']) == 1) - assert (hc.har['log']['pages'][0]['id'] == "page_1") + assert len(hc.har["log"]["pages"]) == 1 + assert hc.har["log"]["pages"][0]["id"] == "page_1" @pytest.fixture() @@ -369,4 +381,4 @@ def tdata(): @pytest.fixture() def path(tmpdir): d = tempfile.TemporaryDirectory().name - return os.path.join(d, 'test.har') + return os.path.join(d, "test.har") diff --git a/test/mitmproxy/addons/browserup/test_har_verifications.py b/test/mitmproxy/addons/browserup/test_har_verifications.py index 30bc811761..122cd86bd5 100644 --- a/test/mitmproxy/addons/browserup/test_har_verifications.py +++ b/test/mitmproxy/addons/browserup/test_har_verifications.py @@ -1,112 +1,139 @@ import pytest from wsproto.frame_protocol import Opcode -from mitmproxy import http, websocket +from mitmproxy import http +from mitmproxy import websocket from mitmproxy.addons.browserup import har_capture_addon from mitmproxy.addons.browserup.har.har_capture_types import HarCaptureTypes from mitmproxy.addons.browserup.har.har_verifications import HarVerifications -from mitmproxy.test import taddons, tflow, tutils +from mitmproxy.test import taddons +from mitmproxy.test import tflow +from mitmproxy.test import tutils from mitmproxy.test.tflow import twebsocketflow class TestHARVerifications: - def test_response_missing_fails(self, hc, flow): hv = HarVerifications(hc.har) - assert (hv.present({'status': '200'}) is False) + assert hv.present({"status": "200"}) is False def test_response_present_succeeds(self, hc, flow): hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200'})) + assert hv.present({"status": "200"}) def test_page_response_present_succeeds(self, hc, flow): hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'page': 'page_1'})) + assert hv.present({"status": "200", "page": "page_1"}) def test_page_response_missing_page(self, hc, flow): hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'page': 'NoSuch'}) is False) + assert hv.present({"status": "200", "page": "NoSuch"}) is False def test_page_response_page_current(self, hc, flow): hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'page': 'current'})) + assert hv.present({"status": "200", "page": "current"}) def test_response_present_url_succeeds(self, hc, flow): hc.request(flow) hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'url': r'/path'})) + assert hv.present({"status": "200", "url": r"/path"}) def test_response_present_url_false(self, hc, flow): hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'url': r'nope'}) is False) + assert hv.present({"status": "200", "url": r"nope"}) is False def test_response_content_present(self, hc, flow): hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'content': r'message'})) + assert hv.present({"status": "200", "content": r"message"}) def test_response_content_not_present(self, hc, flow): hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'content': r'notThere'}) is False) + assert hv.present({"status": "200", "content": r"notThere"}) is False def test_response_present_false(self, hc, flow): hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '300'}) is False) + assert hv.present({"status": "300"}) is False def test_response_not_present(self, hc, flow): hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.not_present({'status': '200'}) is False) + assert hv.not_present({"status": "200"}) is False def test_response_present_header_missing(self, hc, flow): hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'response_header': {'name': 'Nothere'}}) is False) + assert ( + hv.present({"status": "200", "response_header": {"name": "Nothere"}}) + is False + ) def test_request_present_cookie(self, hc, flow): - flow.request.headers["Cookie"] = b'foo=bar' + flow.request.headers["Cookie"] = b"foo=bar" hc.request(flow) hv = HarVerifications(hc.har) - assert (hv.present({'request_cookie': {'name': 'foo'}})) + assert hv.present({"request_cookie": {"name": "foo"}}) def test_response_header_match(self, hc, flow): hc.har_capture_types hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'response_header': {'name': r'content-length'}})) + assert hv.present( + {"status": "200", "response_header": {"name": r"content-length"}} + ) def test_header_key_val_both_match(self, hc, flow): hc.har_capture_types hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'response_header': {'name': r'content-length', 'value': '7'}})) + assert hv.present( + { + "status": "200", + "response_header": {"name": r"content-length", "value": "7"}, + } + ) def test_request_header_key_val_both_match(self, hc, flow): hc.har_capture_types hc.request(flow) hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'request_header': {'name': r'content-length', 'value': '7'}})) + assert hv.present( + { + "status": "200", + "request_header": {"name": r"content-length", "value": "7"}, + } + ) def test_header_key_no_val_match(self, hc, flow): hc.har_capture_types hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'response_header': {'name': r'content-length', 'value': '9'}}) is False) + assert ( + hv.present( + { + "status": "200", + "response_header": {"name": r"content-length", "value": "9"}, + } + ) + is False + ) def test_header_no_match(self, hc, flow): hc.har_capture_types hc.response(flow) hv = HarVerifications(hc.har) - assert (hv.present({'status': '200', 'response_header': {'name': r'nope'}}) is False) + assert ( + hv.present({"status": "200", "response_header": {"name": r"nope"}}) is False + ) def test_websocket_messages_match(self, hc): f = twebsocketflow() @@ -118,78 +145,78 @@ def test_websocket_messages_match(self, hc): hc.websocket_message(f) f.websocket.messages = [ websocket.WebSocketMessage(Opcode.BINARY, True, b"hello binary", 946681203), - websocket.WebSocketMessage(Opcode.TEXT, True, "hello text", 946681204) + websocket.WebSocketMessage(Opcode.TEXT, True, "hello text", 946681204), ] hc.websocket_message(f) hv = HarVerifications(hc.har) - assert (hv.present({'websocket_message': 'hello'})) + assert hv.present({"websocket_message": "hello"}) def test_websocket_messages_no_match(self, hc): hv = HarVerifications(hc.har) - assert (hv.present({'websocket_message': 'hello'}) is False) + assert hv.present({"websocket_message": "hello"}) is False def test_content_type(self, hc, json_flow): hc.response(json_flow) hv = HarVerifications(hc.har) - assert (hv.present({'content_type': 'application/json'})) + assert hv.present({"content_type": "application/json"}) def test_json_valid(self, hc, json_flow): hc.request(json_flow) hc.response(json_flow) hv = HarVerifications(hc.har) - assert (hv.present({'json_valid': True})) + assert hv.present({"json_valid": True}) def test_json_path(self, hc, json_flow): hc.request(json_flow) hc.response(json_flow) hv = HarVerifications(hc.har) - assert (hv.present({'json_path': '$.foo'})) + assert hv.present({"json_path": "$.foo"}) def test_missing_json_path(self, hc, json_flow): hc.request(json_flow) hc.response(json_flow) hv = HarVerifications(hc.har) - assert (hv.present({'json_path': '$.nope'}) is False) + assert hv.present({"json_path": "$.nope"}) is False def test_json_schema(self, hc, json_flow): hc.request(json_flow) hc.response(json_flow) hv = HarVerifications(hc.har) schema = {"type": "object", "properties": {"foo": {"type": "string"}}} - assert (hv.present({'json_schema': schema})) + assert hv.present({"json_schema": schema}) def test_json_schema_not_valid(self, hc, json_flow): hc.request(json_flow) hc.response(json_flow) hv = HarVerifications(hc.har) schema = {"type": "object", "properties": {"foo": {"type": "integer"}}} - assert (hv.present({'json_schema': schema}) is False) + assert hv.present({"json_schema": schema}) is False def test_time_max(self, hc, json_flow): hc.request(json_flow) hc.response(json_flow) hv = HarVerifications(hc.har) - assert (hv.get_max({'status': '200'}, 'time')) + assert hv.get_max({"status": "200"}, "time") def test_size_max(self, hc, json_flow): hc.request(json_flow) hc.response(json_flow) hv = HarVerifications(hc.har) - assert (hv.get_max({'status': '200'}, 'response')) + assert hv.get_max({"status": "200"}, "response") @pytest.fixture() def flow(): - resp_content = b'message' + resp_content = b"message" times = dict( timestamp_start=746203200, timestamp_end=746203290, ) return tflow.tflow( - req=tutils.treq(method=b'GET', **times), - resp=tutils.tresp(content=resp_content, **times) + req=tutils.treq(method=b"GET", **times), + resp=tutils.tresp(content=resp_content, **times), ) @@ -201,9 +228,17 @@ def json_flow(): ) return tflow.tflow( - req=tutils.treq(method=b'GET', path=b"/path/foo.json", **times), - resp=tutils.tresp(content=b'{"foo": "bar"}', - headers=http.Headers(((b"header-response", b"svalue"), (b"content-type", b"application/json"))), **times) + req=tutils.treq(method=b"GET", path=b"/path/foo.json", **times), + resp=tutils.tresp( + content=b'{"foo": "bar"}', + headers=http.Headers( + ( + (b"header-response", b"svalue"), + (b"content-type", b"application/json"), + ) + ), + **times, + ), ) From 3acd016c0c25f290a075f555c65ba26101ab3117 Mon Sep 17 00:00:00 2001 From: "Kirill.T" Date: Sun, 26 Jan 2025 17:53:13 +0100 Subject: [PATCH 3/5] formatting --- clients/python/BrowserUpMitmProxyClient/api_client.py | 4 ++-- clients/python/BrowserUpMitmProxyClient/models/har.py | 3 ++- .../BrowserUpMitmProxyClient/models/har_entry_request.py | 4 ++-- .../BrowserUpMitmProxyClient/models/har_entry_response.py | 4 ++-- .../models/largest_contentful_paint.py | 4 ++-- clients/python/BrowserUpMitmProxyClient/models/page.py | 4 ++-- .../python/BrowserUpMitmProxyClient/models/page_timings.py | 3 ++- clients/python/BrowserUpMitmProxyClient/rest.py | 1 - mitmproxy/addons/browserup/browserup_addons_manager.py | 4 ++-- mitmproxy/addons/browserup/har_capture_addon.py | 4 ++-- mitmproxy/tools/main.py | 2 +- 11 files changed, 19 insertions(+), 18 deletions(-) diff --git a/clients/python/BrowserUpMitmProxyClient/api_client.py b/clients/python/BrowserUpMitmProxyClient/api_client.py index c24e8b5026..aed4b10518 100644 --- a/clients/python/BrowserUpMitmProxyClient/api_client.py +++ b/clients/python/BrowserUpMitmProxyClient/api_client.py @@ -349,7 +349,7 @@ def __deserialize(self, data, klass): if data is None: return None - if type(klass) == str: + if type(klass) is str: if klass.startswith("List["): sub_kls = re.match(r"List\[(.*)]", klass).group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] @@ -366,7 +366,7 @@ def __deserialize(self, data, klass): if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) - elif klass == object: + elif klass is object: return self.__deserialize_object(data) elif klass == datetime.date: return self.__deserialize_date(data) diff --git a/clients/python/BrowserUpMitmProxyClient/models/har.py b/clients/python/BrowserUpMitmProxyClient/models/har.py index 12a12f2e3a..f1fb8a162e 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har.py @@ -17,6 +17,7 @@ import json import pprint import re # noqa: F401 +from typing import Any from pydantic import BaseModel from pydantic import Field @@ -30,7 +31,7 @@ class Har(BaseModel): """ log: HarLog = Field(...) - additional_properties: Dict[str, Any] = {} + additional_properties: dict[str, Any] = {} __properties = ["log"] class Config: diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py index 5344079c3e..5d856e5e49 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py @@ -17,7 +17,7 @@ import json import pprint import re # noqa: F401 -from typing import Optional +from typing import Optional, Any from pydantic import BaseModel from pydantic import conlist @@ -54,7 +54,7 @@ class HarEntryRequest(BaseModel): headers_size: StrictInt = Field(..., alias="headersSize") body_size: StrictInt = Field(..., alias="bodySize") comment: Optional[StrictStr] = None - additional_properties: Dict[str, Any] = {} + additional_properties: dict[str, Any] = {} __properties = [ "method", "url", diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py index 21e15bf6ad..b9f0cf677b 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py @@ -17,7 +17,7 @@ import json import pprint import re # noqa: F401 -from typing import Optional +from typing import Optional, Any from pydantic import BaseModel from pydantic import conlist @@ -49,7 +49,7 @@ class HarEntryResponse(BaseModel): headers_size: StrictInt = Field(..., alias="headersSize") body_size: StrictInt = Field(..., alias="bodySize") comment: Optional[StrictStr] = None - additional_properties: Dict[str, Any] = {} + additional_properties: dict[str, Any] = {} __properties = [ "status", "statusText", diff --git a/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py b/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py index e878485a31..7cb5964fe3 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py +++ b/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py @@ -17,7 +17,7 @@ import json import pprint import re # noqa: F401 -from typing import Optional +from typing import Optional, Any from pydantic import BaseModel from pydantic import conint @@ -34,7 +34,7 @@ class LargestContentfulPaint(BaseModel): size: Optional[conint(strict=True, ge=-1)] = -1 dom_path: Optional[StrictStr] = Field("", alias="domPath") tag: Optional[StrictStr] = "" - additional_properties: Dict[str, Any] = {} + additional_properties: dict[str, Any] = {} __properties = ["startTime", "size", "domPath", "tag"] class Config: diff --git a/clients/python/BrowserUpMitmProxyClient/models/page.py b/clients/python/BrowserUpMitmProxyClient/models/page.py index c85c1706c9..0403571053 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/page.py +++ b/clients/python/BrowserUpMitmProxyClient/models/page.py @@ -18,7 +18,7 @@ import pprint import re # noqa: F401 from datetime import datetime -from typing import Optional +from typing import Optional, Any from pydantic import BaseModel from pydantic import conlist @@ -44,7 +44,7 @@ class Page(BaseModel): errors: Optional[conlist(Error)] = Field(None, alias="_errors") page_timings: PageTimings = Field(..., alias="pageTimings") comment: Optional[StrictStr] = None - additional_properties: Dict[str, Any] = {} + additional_properties: dict[str, Any] = {} __properties = [ "startedDateTime", "id", diff --git a/clients/python/BrowserUpMitmProxyClient/models/page_timings.py b/clients/python/BrowserUpMitmProxyClient/models/page_timings.py index 1241fc425e..ccd8fa1a92 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/page_timings.py +++ b/clients/python/BrowserUpMitmProxyClient/models/page_timings.py @@ -17,6 +17,7 @@ import json import pprint import re # noqa: F401 +from typing import Any from typing import Optional from typing import Union @@ -61,7 +62,7 @@ class PageTimings(BaseModel): -1, alias="_firstContentfulPaint" ) comment: Optional[StrictStr] = None - additional_properties: Dict[str, Any] = {} + additional_properties: dict[str, Any] = {} __properties = [ "onContentLoad", "onLoad", diff --git a/clients/python/BrowserUpMitmProxyClient/rest.py b/clients/python/BrowserUpMitmProxyClient/rest.py index 06c1fdebb7..a59bd9c646 100644 --- a/clients/python/BrowserUpMitmProxyClient/rest.py +++ b/clients/python/BrowserUpMitmProxyClient/rest.py @@ -145,7 +145,6 @@ def request( headers = headers or {} # url already contains the URL query string # so reset query_params to empty dict - query_params = {} timeout = None if _request_timeout: diff --git a/mitmproxy/addons/browserup/browserup_addons_manager.py b/mitmproxy/addons/browserup/browserup_addons_manager.py index db2659e5ab..c5304ae901 100644 --- a/mitmproxy/addons/browserup/browserup_addons_manager.py +++ b/mitmproxy/addons/browserup/browserup_addons_manager.py @@ -29,13 +29,13 @@ class BrowserUpAddonsManagerAddOn: initialized = False - def load(self, l): + def load(self, loader): logging.info("Loading BrowserUpAddonsManagerAddOn") logging.info("Version {}".format(VERSION)) ctx.options.update(listen_port=48080) - l.add_option( + loader.add_option( name="addons_management_port", typespec=Optional[int], default=48088, diff --git a/mitmproxy/addons/browserup/har_capture_addon.py b/mitmproxy/addons/browserup/har_capture_addon.py index 775764fbc6..b00916186e 100644 --- a/mitmproxy/addons/browserup/har_capture_addon.py +++ b/mitmproxy/addons/browserup/har_capture_addon.py @@ -19,9 +19,9 @@ class HarCaptureAddOn(FlowCaptureMixin, HarManagerMixin): - def load(self, l): + def load(self, loader): logging.info("Loading HarCaptureAddon") - l.add_option("harcapture", str, "", "HAR capture path.") + loader.add_option("harcapture", str, "", "HAR capture path.") def get_resources(self): return [ diff --git a/mitmproxy/tools/main.py b/mitmproxy/tools/main.py index 232af9c1da..f0fb3ecaec 100644 --- a/mitmproxy/tools/main.py +++ b/mitmproxy/tools/main.py @@ -168,7 +168,7 @@ def mitmweb(args=None) -> int | None: # pragma: no cover return None -def browserupproxy(args=None) -> Optional[int]: # pragma: no cover +def browserupproxy(args=None) -> int | None: # pragma: no cover from mitmproxy.tools import browserup_proxy def extra(args): From 11384166ef0de0ad18c4855d65985ff3b5d297aa Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sun, 26 Jan 2025 16:54:39 +0000 Subject: [PATCH 4/5] [autofix.ci] apply automated fixes --- .../BrowserUpMitmProxyClient/models/har_entry_request.py | 3 ++- .../BrowserUpMitmProxyClient/models/har_entry_response.py | 3 ++- .../models/largest_contentful_paint.py | 3 ++- clients/python/BrowserUpMitmProxyClient/models/page.py | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py index 5d856e5e49..de5a90d93b 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_request.py @@ -17,7 +17,8 @@ import json import pprint import re # noqa: F401 -from typing import Optional, Any +from typing import Any +from typing import Optional from pydantic import BaseModel from pydantic import conlist diff --git a/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py b/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py index b9f0cf677b..7cdcd71774 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py +++ b/clients/python/BrowserUpMitmProxyClient/models/har_entry_response.py @@ -17,7 +17,8 @@ import json import pprint import re # noqa: F401 -from typing import Optional, Any +from typing import Any +from typing import Optional from pydantic import BaseModel from pydantic import conlist diff --git a/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py b/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py index 7cb5964fe3..71f3f0d52e 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py +++ b/clients/python/BrowserUpMitmProxyClient/models/largest_contentful_paint.py @@ -17,7 +17,8 @@ import json import pprint import re # noqa: F401 -from typing import Optional, Any +from typing import Any +from typing import Optional from pydantic import BaseModel from pydantic import conint diff --git a/clients/python/BrowserUpMitmProxyClient/models/page.py b/clients/python/BrowserUpMitmProxyClient/models/page.py index 0403571053..8412cff2e5 100644 --- a/clients/python/BrowserUpMitmProxyClient/models/page.py +++ b/clients/python/BrowserUpMitmProxyClient/models/page.py @@ -18,7 +18,8 @@ import pprint import re # noqa: F401 from datetime import datetime -from typing import Optional, Any +from typing import Any +from typing import Optional from pydantic import BaseModel from pydantic import conlist From 32c8e841d1d3f77efa5ec8de09b7ef5af035af53 Mon Sep 17 00:00:00 2001 From: "Kirill.T" Date: Sun, 26 Jan 2025 18:02:43 +0100 Subject: [PATCH 5/5] CI update --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 0b7a709d1f..93d34b7137 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -21,7 +21,7 @@ jobs: lint: uses: mhils/workflows/.github/workflows/python-tox.yml@v11 with: - cmd: tox -e lint || true + cmd: tox -e lint filename-matching: uses: mhils/workflows/.github/workflows/python-tox.yml@v11