././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1737581761.1987824 hyperframe-6.1.0/0000755000076500000240000000000014744262301013224 5ustar00kriechistaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1732306692.0 hyperframe-6.1.0/.gitmodules0000644000076500000240000000021114720163404015371 0ustar00kriechistaff[submodule "test/http2-frame-test-case"] path = tests/http2-frame-test-case url = https://github.com/http2jp/http2-frame-test-case.git ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1737580381.0 hyperframe-6.1.0/CHANGELOG.rst0000644000076500000240000001603714744257535015271 0ustar00kriechistaffRelease History =============== 6.1.0 (2025-01-22) ------------------ **API Changes (Backward Incompatible)** - Support for Python 3.6 has been removed. - Support for Python 3.7 has been removed. - Support for Python 3.8 has been removed. **API Changes (Backward Compatible)** - Support for Python 3.10 has been added. - Support for Python 3.11 has been added. - Support for Python 3.12 has been added. - Support for Python 3.13 has been added. - Updated packaging and testing infrastructure. - Code cleanup and linting. - Improved type hints. 6.0.1 (2021-04-17) ------------------ **API Changes (Backward Compatible)** - Added support for Python 3.9. - Added type hints. 6.0.0 (2020-09-06) ------------------ **API Changes (Backward Incompatible)** - Introduce ``HyperframeError`` base exception class for all errors raised within hyperframe. - Change exception base class of ``UnknownFrameError`` to ``HyperframeError`` - Change exception base class of ``InvalidPaddingError`` to ``HyperframeError`` - Change exception base class of ``InvalidFrameError`` to ``HyperframeError`` - Invalid frames with wrong stream id (zero vs. non-zero) now raise ``InvalidDataError``. - Invalid SETTINGS frames (non-empty but ACK) now raise ``InvalidDataError``. - Invalid ALTSVC frames with non-bytestring field or origin now raise ``InvalidDataError``. **API Changes (Backward Compatible)** - Deprecate ``total_padding`` - use `pad_length` instead. - Improve repr() output for all frame classes. - Introduce Frame.explain(data) for quick introspection of raw data. **Bugfixes** - Fixed padding parsing for ``PushPromiseFrame``. - Fixed unchecked frame length for ``PriorityFrame``. It now correctly raises ``InvalidFrameError``. - Fixed promised stream id validation for ``PushPromiseFrame``. It now raises ``InvalidDataError``. - Fixed unchecked frame length for ``WindowUpdateFrame``. It now correctly raises ``InvalidFrameError``. - Fixed window increment value range validation. It now raises ``InvalidDataError``. - Fixed parsing of ``SettingsFrame`` with mutual exclusion of ACK flag and payload. **Other Changes** - Removed support for Python 2.7, 3.4, 3.5, pypy. - Added support for Python 3.8. 5.2.0 (2019-01-18) ------------------ **API Changes (Backward Compatible)** - Add a new ENABLE_CONNECT_PROTOCOL settings parameter. **Other Changes** - Fix collections.abc deprecation. - Drop support for Python 3.3 and support 3.7. 5.1.0 (2017-04-24) ------------------ **API Changes (Backward Compatible)** - Added support for ``DataFrame.data`` being a ``memoryview`` object. 5.0.0 (2017-03-07) ------------------ **Backwards Incompatible API Changes** - Added support for unknown extension frames. These will be returned in the new ``ExtensionFrame`` object. The flag information for these frames is persisted in ``flag_byte`` if needed. 4.0.2 (2017-02-20) ------------------ **Bugfixes** - Fixed AltSvc stream association, which was incorrectly set to ``'both'``: should have been ``'either'``. - Fixed a bug where stream IDs on received frames were allowed to be 32-bit, instead of 31-bit. - Fixed a bug with frames that had the ``PADDING`` flag set but zero-length padding, whose flow-controlled length was calculated wrongly. - Miscellaneous performance improvements to serialization and parsing logic. 4.0.1 (2016-03-13) ------------------ **Bugfixes** - Fixed bug with the repr of ``AltSvcFrame``, where building it could throw exceptions if the frame had been received from the network. 4.0.0 (2016-03-13) ------------------ **Backwards Incompatible API Changes** - Updated old ALTSVC frame definition to match the newly specified RFC 7838. - Remove BLOCKED frame, which was never actually specified. - Removed previously deprecated ``SettingsFrame.SETTINGS_MAX_FRAME_SIZE`` and ``SettingsFrame.SETTINGS_MAX_HEADER_LIST_SIZE``. 3.2.0 (2016-02-02) ------------------ **API Changes (Backward Compatible)** - Invalid PING frame bodies now raise ``InvalidFrameError``, not ``ValueError``. Note that ``InvalidFrameError`` is a ``ValueError`` subclass. - Invalid RST_STREAM frame bodies now raise ``InvalidFramError``, not ``ValueError``. Note that ``InvalidFrameError`` is a ``ValueError`` subclass. - Canonicalized the names of ``SettingsFrame.SETTINGS_MAX_FRAME_SIZE`` and ``SettingsFrame.SETTINGS_MAX_HEADER_LIST_SIZE`` to match their peers, by adding new properties ``SettingsFrame.MAX_FRAME_SIZE`` and ``SettingsFrame.SETTINGS_MAX_HEADER_LIST_SIZE``. The old names are still present, but will be deprecated in 4.0.0. **Bugfixes** - The change in ``3.1.0`` that ensured that ``InvalidFrameError`` would be thrown did not affect certain invalid values in ALT_SVC frames. This has been fixed: ``ValueError`` will no longer be thrown from invalid ALT_SVC bodies. 3.1.1 (2016-01-18) ------------------ **Bugfixes** - Correctly error when receiving Ping frames that have insufficient data. 3.1.0 (2016-01-13) ------------------ **API Changes** - Added new ``InvalidFrameError`` that is thrown instead of ``struct.error`` when parsing a frame. **Bugfixes** - Fixed error when trying to serialize frames that use Priority information with the defaults for that information. - Fixed errors when displaying the repr of frames with non-printable bodies. 3.0.1 (2016-01-08) ------------------ **Bugfixes** - Fix issue where unpadded DATA, PUSH_PROMISE and HEADERS frames that had empty bodies would raise ``InvalidPaddingError`` exceptions when parsed. 3.0.0 (2016-01-08) ------------------ **Backwards Incompatible API Changes** - Parsing padded frames that have invalid padding sizes now throws an ``InvalidPaddingError``. 2.2.0 (2015-10-15) ------------------ **API Changes** - When an unknown frame is encountered, ``parse_frame_header`` now throws a ``ValueError`` subclass: ``UnknownFrameError``. This subclass contains the frame type and the length of the frame body. 2.1.0 (2015-10-06) ------------------ **API Changes** - Frames parsed from binary data now carry a ``body_len`` attribute that matches the frame length (minus the frame header). 2.0.0 (2015-09-21) ------------------ **API Changes** - Attempting to parse unrecognised frames now throws ``ValueError`` instead of ``KeyError``. Thanks to @Kriechi! - Flags are now validated for correctness, preventing setting flags that ``hyperframe`` does not recognise and that would not serialize. Thanks to @mhils! - Frame properties can now be initialized in the constructors. Thanks to @mhils and @Kriechi! - Frames that cannot be sent on a stream now have their stream ID defaulted to ``0``. Thanks to @Kriechi! **Other Changes** - Frames have a more useful repr. Thanks to @mhils! 1.1.1 (2015-07-20) ------------------ - Fix a bug where ``FRAME_MAX_LEN`` was one byte too small. 1.1.0 (2015-06-28) ------------------ - Add ``body_len`` property to frames to enable introspection of the actual frame length. Thanks to @jdecuyper! 1.0.1 (2015-06-27) ------------------ - Fix bug where the frame header would have an incorrect length added to it. 1.0.0 (2015-04-12) ------------------ - Initial extraction from hyper. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1543747825.0 hyperframe-6.1.0/CONTRIBUTORS.rst0000644000076500000240000000226313400734361015714 0ustar00kriechistaffHyper is written and maintained by Cory Benfield and various contributors: Development Lead ```````````````` - Cory Benfield Contributors ```````````` In chronological order: - Sriram Ganesan (@elricL) - Implemented the Huffman encoding/decoding logic. - Alek Storm (@alekstorm) - Implemented Python 2.7 support. - Implemented HTTP/2 draft 10 support. - Implemented server push. - Tetsuya Morimoto (@t2y) - Fixed a bug where large or incomplete frames were not handled correctly. - Added hyper command-line tool. - General code cleanups. - Jerome De Cuyper (@jdecuyper) - Updated documentation and tests. - Maximilian Hils (@mhils) - Added repr for frames. - Improved frame initialization code. - Added flag validation. - Thomas Kriechbaumer (@Kriechi) - Improved initialization code. - Fixed bugs in frame initialization code. - Improved frame repr for frames with non-printable bodies. - Davey Shafik (@dshafik) - Fixed Alt Svc frame stream association. - Seth Michael Larson (@SethMichaelLarson) - Performance improvements to serialization and parsing. - Fred Thomsen (@fredthomsen) - Support for memoryview in DataFrames. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1442653833.0 hyperframe-6.1.0/LICENSE0000644000076500000240000000207012577223211014227 0ustar00kriechistaffThe MIT License (MIT) Copyright (c) 2014 Cory Benfield Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734718572.0 hyperframe-6.1.0/MANIFEST.in0000644000076500000240000000036514731332154014766 0ustar00kriechistaffgraft src/hyperframe graft docs graft tests prune docs/build prune tests/http2-frame-test-case include README.rst LICENSE CHANGELOG.rst CONTRIBUTORS.rst pyproject.toml .gitmodules global-exclude *.pyc *.pyo *.swo *.swp *.map *.yml *.DS_Store ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1737581761.1985624 hyperframe-6.1.0/PKG-INFO0000644000076500000240000001036314744262301014324 0ustar00kriechistaffMetadata-Version: 2.2 Name: hyperframe Version: 6.1.0 Summary: Pure-Python HTTP/2 framing Author-email: Cory Benfield Maintainer-email: Thomas Kriechbaumer License: The MIT License (MIT) Copyright (c) 2014 Cory Benfield Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Project-URL: Homepage, https://github.com/python-hyper/hyperframe/ Project-URL: Bug Reports, https://github.com/python-hyper/hyperframe/issues Project-URL: Source, https://github.com/python-hyper/hyperframe/ Project-URL: Documentation, https://python-hyper.org/ Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=3.9 Description-Content-Type: text/x-rst License-File: LICENSE ====================================== hyperframe: Pure-Python HTTP/2 framing ====================================== .. image:: https://github.com/python-hyper/hyperframe/workflows/CI/badge.svg :target: https://github.com/python-hyper/hyperframe/actions :alt: Build Status .. image:: https://codecov.io/gh/python-hyper/hyperframe/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-hyper/hyperframe :alt: Code Coverage .. image:: https://readthedocs.org/projects/hyperframe/badge/?version=latest :target: https://hyperframe.readthedocs.io/en/latest/ :alt: Documentation Status .. image:: https://img.shields.io/badge/chat-join_now-brightgreen.svg :target: https://gitter.im/python-hyper/community :alt: Chat community This library contains the HTTP/2 framing code used in the `hyper`_ project. It provides a pure-Python codebase that is capable of decoding a binary stream into HTTP/2 frames. This library is used directly by `hyper`_ and a number of other projects to provide HTTP/2 frame decoding logic. Contributing ============ hyperframe welcomes contributions from anyone! Unlike many other projects we are happy to accept cosmetic contributions and small contributions, in addition to large feature requests and changes. Before you contribute (either by opening an issue or filing a pull request), please `read the contribution guidelines`_. .. _read the contribution guidelines: http://hyper.readthedocs.org/en/development/contributing.html License ======= hyperframe is made available under the MIT License. For more details, see the ``LICENSE`` file in the repository. Authors ======= hyperframe is maintained by Cory Benfield, with contributions from others. For more details about the contributors, please see ``CONTRIBUTORS.rst``. .. _hyper: http://python-hyper.org/ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1596060960.0 hyperframe-6.1.0/README.rst0000644000076500000240000000346013710372440014714 0ustar00kriechistaff====================================== hyperframe: Pure-Python HTTP/2 framing ====================================== .. image:: https://github.com/python-hyper/hyperframe/workflows/CI/badge.svg :target: https://github.com/python-hyper/hyperframe/actions :alt: Build Status .. image:: https://codecov.io/gh/python-hyper/hyperframe/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-hyper/hyperframe :alt: Code Coverage .. image:: https://readthedocs.org/projects/hyperframe/badge/?version=latest :target: https://hyperframe.readthedocs.io/en/latest/ :alt: Documentation Status .. image:: https://img.shields.io/badge/chat-join_now-brightgreen.svg :target: https://gitter.im/python-hyper/community :alt: Chat community This library contains the HTTP/2 framing code used in the `hyper`_ project. It provides a pure-Python codebase that is capable of decoding a binary stream into HTTP/2 frames. This library is used directly by `hyper`_ and a number of other projects to provide HTTP/2 frame decoding logic. Contributing ============ hyperframe welcomes contributions from anyone! Unlike many other projects we are happy to accept cosmetic contributions and small contributions, in addition to large feature requests and changes. Before you contribute (either by opening an issue or filing a pull request), please `read the contribution guidelines`_. .. _read the contribution guidelines: http://hyper.readthedocs.org/en/development/contributing.html License ======= hyperframe is made available under the MIT License. For more details, see the ``LICENSE`` file in the repository. Authors ======= hyperframe is maintained by Cory Benfield, with contributions from others. For more details about the contributors, please see ``CONTRIBUTORS.rst``. .. _hyper: http://python-hyper.org/ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1737581761.1955488 hyperframe-6.1.0/docs/0000755000076500000240000000000014744262301014154 5ustar00kriechistaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1596385019.0 hyperframe-6.1.0/docs/Makefile0000644000076500000240000000117613711563373015627 0ustar00kriechistaff# Minimal makefile for Sphinx documentation # # You can set these variables from the command line, and also # from the environment for the first two. SPHINXOPTS ?= SPHINXBUILD ?= sphinx-build SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1596385019.0 hyperframe-6.1.0/docs/make.bat0000644000076500000240000000143713711563373015574 0ustar00kriechistaff@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=source set BUILDDIR=build if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% :end popd ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1737581761.1959815 hyperframe-6.1.0/docs/source/0000755000076500000240000000000014744262301015454 5ustar00kriechistaff././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1737581761.1962683 hyperframe-6.1.0/docs/source/_static/0000755000076500000240000000000014744262301017102 5ustar00kriechistaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734780961.0 hyperframe-6.1.0/docs/source/_static/.keep0000644000076500000240000000000014731524041020013 0ustar00kriechistaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1597873402.0 hyperframe-6.1.0/docs/source/api.rst0000644000076500000240000000415313717316372016771 0ustar00kriechistaffhyperframe API ============== This document provides the hyperframe API. All frame classes are subclasses of :class:`Frame `, and provide the methods and attributes defined there. Additionally, some frames use the :class:`Priority ` and :class:`Padding ` mixins, and make the methods and attributes defined on *those* mixins available as well. Rather than clutter up the documentation repeatedly documenting those methods and objects, we explicitly show the inheritance hierarchy of the frames: don't forget to consult the parent classes before deciding if a method or attribute you need is not present! .. autoclass:: hyperframe.frame.Frame :members: .. autoclass:: hyperframe.frame.Padding :members: .. autoclass:: hyperframe.frame.Priority :members: .. autoclass:: hyperframe.frame.DataFrame :show-inheritance: :members: .. autoclass:: hyperframe.frame.PriorityFrame :show-inheritance: :members: .. autoclass:: hyperframe.frame.RstStreamFrame :show-inheritance: :members: .. autoclass:: hyperframe.frame.SettingsFrame :show-inheritance: :members: .. autoclass:: hyperframe.frame.PushPromiseFrame :show-inheritance: :members: .. autoclass:: hyperframe.frame.PingFrame :show-inheritance: :members: .. autoclass:: hyperframe.frame.GoAwayFrame :show-inheritance: :members: .. autoclass:: hyperframe.frame.WindowUpdateFrame :show-inheritance: :members: .. autoclass:: hyperframe.frame.HeadersFrame :show-inheritance: :members: .. autoclass:: hyperframe.frame.ContinuationFrame :show-inheritance: :members: .. autoclass:: hyperframe.frame.ExtensionFrame :show-inheritance: :members: .. autodata:: hyperframe.frame.FRAMES Exceptions ---------- .. autoclass:: hyperframe.exceptions.HyperframeError :members: .. autoclass:: hyperframe.exceptions.UnknownFrameError :members: .. autoclass:: hyperframe.exceptions.InvalidPaddingError :members: .. autoclass:: hyperframe.exceptions.InvalidFrameError :members: .. autoclass:: hyperframe.exceptions.InvalidDataError :members: ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1599387576.0 hyperframe-6.1.0/docs/source/conf.py0000644000076500000240000000455213725133670016765 0ustar00kriechistaff# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys import re sys.path.insert(0, os.path.abspath('../..')) PROJECT_ROOT = os.path.dirname(__file__) # Get the version version_regex = r'__version__ = ["\']([^"\']*)["\']' with open(os.path.join(PROJECT_ROOT, '../../', 'src/hyperframe/__init__.py')) as file_: text = file_.read() match = re.search(version_regex, text) version = match.group(1) # -- Project information ----------------------------------------------------- project = 'hyperframe' copyright = '2020, Cory Benfield' author = 'Cory Benfield' release = version # -- General configuration --------------------------------------------------- # 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.intersphinx', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'python': ('https://docs.python.org/', None), } master_doc = 'index' # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'default' # 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'] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1595410293.0 hyperframe-6.1.0/docs/source/index.rst0000644000076500000240000000156013706003565017321 0ustar00kriechistaffhyperframe: HTTP/2 Framing for Python ===================================== hyperframe is a pure-Python tool for working with HTTP/2 frames. This library allows you to create, serialize, and parse HTTP/2 frames. Working with it is easy: .. code-block:: python import hyperframe.frame f = hyperframe.frame.DataFrame(stream_id=5) f.data = b'some binary data' f.flags.add('END_STREAM') f.flags.add('PADDED') f.padding_length = 30 data = f.serialize() new_frame, length = hyperframe.frame.Frame.parse_frame_header(data[:9]) new_frame.parse_body(memoryview(data[9:9 + length])) hyperframe is pure-Python, contains no external dependencies, and runs on a wide variety of Python interpreters and platforms. Made available under the MIT license, why write your own frame parser? Contents: .. toctree:: :maxdepth: 2 installation api ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1452447789.0 hyperframe-6.1.0/docs/source/installation.rst0000644000076500000240000000074512644514055020720 0ustar00kriechistaffInstalling hyperframe ===================== hyperframe is trivial to install from the Python Package Index. Simply run: .. code-block:: console $ pip install hyperframe Alternatively, feel free to download one of the release tarballs from `our GitHub page`_, extract it to your favourite directory, and then run .. code-block:: console $ python setup.py install hyperframe has no external dependencies. .. _our GitHub page: https://github.com/python-hyper/hyperframe ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1737581730.0 hyperframe-6.1.0/pyproject.toml0000644000076500000240000001164414744262242016152 0ustar00kriechistaff# https://packaging.python.org/en/latest/guides/writing-pyproject-toml/ # https://packaging.python.org/en/latest/specifications/pyproject-toml/ [build-system] requires = ["setuptools>=75.6.0"] build-backend = "setuptools.build_meta" [project] name = "hyperframe" description = "Pure-Python HTTP/2 framing" readme = { file = "README.rst", content-type = "text/x-rst" } license = { file = "LICENSE" } authors = [ { name = "Cory Benfield", email = "cory@lukasa.co.uk" } ] maintainers = [ { name = "Thomas Kriechbaumer", email = "thomas@kriechbaumer.name" }, ] requires-python = ">=3.9" dependencies = [] dynamic = ["version"] # For a list of valid classifiers, see https://pypi.org/classifiers/ classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ] [project.urls] "Homepage" = "https://github.com/python-hyper/hyperframe/" "Bug Reports" = "https://github.com/python-hyper/hyperframe/issues" "Source" = "https://github.com/python-hyper/hyperframe/" "Documentation" = "https://python-hyper.org/" [dependency-groups] dev = [ { include-group = "testing" }, { include-group = "linting" }, { include-group = "packaging" }, { include-group = "docs" }, ] testing = [ "pytest>=8.3.3,<9", "pytest-cov>=6.0.0,<7", "pytest-xdist>=3.6.1,<4", ] linting = [ "ruff>=0.8.0,<1", "mypy>=1.13.0,<2", ] packaging = [ "check-manifest==0.50", "readme-renderer==44.0", "build>=1.2.2,<2", "twine>=5.1.1,<6", "wheel>=0.45.0,<1", ] docs = [ "sphinx>=7.4.7,<9", ] [tool.setuptools.packages.find] where = [ "src" ] [tool.setuptools.package-data] hyperframe = [ "py.typed" ] [tool.setuptools.dynamic] version = { attr = "hyperframe.__version__" } [tool.check-manifest] ignore = [ "Makefile", "tests/http2-frame-test-case", ] [tool.ruff] line-length = 150 target-version = "py39" format.preview = true format.docstring-code-line-length = 100 format.docstring-code-format = true lint.select = [ "ALL", ] lint.ignore = [ "ANN401", # kwargs with typing.Any "CPY", # not required "D101", # docs readability "D102", # docs readability "D105", # docs readability "D107", # docs readability "D200", # docs readability "D205", # docs readability "D205", # docs readability "D203", # docs readability "D212", # docs readability "D400", # docs readability "D401", # docs readability "D415", # docs readability "PLR2004", # readability "SIM108", # readability "RUF012", # readability "FBT001", # readability "FBT002", # readability "PGH003", # readability ] lint.isort.required-imports = [ "from __future__ import annotations" ] [tool.mypy] show_error_codes = true strict = true [tool.coverage.run] branch = true source = [ "hyperframe" ] [tool.coverage.report] fail_under = 100 show_missing = true exclude_lines = [ "pragma: no cover", "raise NotImplementedError", ] [tool.coverage.paths] source = [ "src/", ".tox/**/site-packages/", ] [tool.tox] min_version = "4.23.2" env_list = [ "py39", "py310", "py311", "py312", "py313", "pypy3", "lint", "docs", "packaging" ] [tool.tox.gh-actions] python = """ 3.9: py39, h2spec, lint, docs, packaging 3.10: py310 3.11: py311 3.12: py312 3.13: py313 pypy3: pypy3 """ [tool.tox.env_run_base] pass_env = [ "GITHUB_*", ] dependency_groups = ["testing"] commands = [ ["pytest", "--cov-report=xml", "--cov-report=term", "--cov=hyperframe", { replace = "posargs", extend = true }] ] [tool.tox.env.pypy3] # temporarily disable coverage testing on PyPy due to performance problems commands = [ ["pytest", { replace = "posargs", extend = true }] ] [tool.tox.env.lint] dependency_groups = ["linting"] commands = [ ["ruff", "check", "src/"], ["mypy", "src/"], ] [tool.tox.env.docs] dependency_groups = ["docs"] allowlist_externals = ["make"] changedir = "{toxinidir}/docs" commands = [ ["make", "clean"], ["make", "html"], ] [tool.tox.env.packaging] base_python = ["python39"] dependency_groups = ["packaging"] allowlist_externals = ["rm"] commands = [ ["rm", "-rf", "dist/"], ["check-manifest"], ["python", "-m", "build", "--outdir", "dist/"], ["twine", "check", "dist/*"], ] [tool.tox.env.publish] base_python = ["{[tool.tox.env.packaging]base_python}"] dependency_groups = ["{[tool.tox.env.packaging]dependency_groups}"] allowlist_externals = "{[tool.tox.env.packaging]allowlist_externals}" commands = [ "{[testenv:packaging]commands}", ["twine", "upload", "dist/*"], ] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1737581761.1988266 hyperframe-6.1.0/setup.cfg0000644000076500000240000000004614744262301015045 0ustar00kriechistaff[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1737581761.1943529 hyperframe-6.1.0/src/0000755000076500000240000000000014744262301014013 5ustar00kriechistaff././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1737581761.1969569 hyperframe-6.1.0/src/hyperframe/0000755000076500000240000000000014744262301016155 5ustar00kriechistaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734781034.0 hyperframe-6.1.0/src/hyperframe/__init__.py0000644000076500000240000000015714731524152020272 0ustar00kriechistaff""" Provides a pure-Python HTTP/2 framing layer. """ from __future__ import annotations __version__ = "6.1.0" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734780961.0 hyperframe-6.1.0/src/hyperframe/exceptions.py0000644000076500000240000000275414731524041020716 0ustar00kriechistaff""" Exceptions that can be thrown by hyperframe. """ from __future__ import annotations class HyperframeError(Exception): """ The base class for all exceptions for the hyperframe module. .. versionadded:: 6.0.0 """ class UnknownFrameError(HyperframeError): """ A frame of unknown type was received. .. versionchanged:: 6.0.0 Changed base class from `ValueError` to :class:`HyperframeError` """ def __init__(self, frame_type: int, length: int) -> None: #: The type byte of the unknown frame that was received. self.frame_type = frame_type #: The length of the data portion of the unknown frame. self.length = length def __str__(self) -> str: return ( f"UnknownFrameError: Unknown frame type 0x{self.frame_type:X} received, length {self.length} bytes" ) class InvalidPaddingError(HyperframeError): """ A frame with invalid padding was received. .. versionchanged:: 6.0.0 Changed base class from `ValueError` to :class:`HyperframeError` """ class InvalidFrameError(HyperframeError): """ Parsing a frame failed because the data was not laid out appropriately. .. versionadded:: 3.0.2 .. versionchanged:: 6.0.0 Changed base class from `ValueError` to :class:`HyperframeError` """ class InvalidDataError(HyperframeError): """ Content or data of a frame was is invalid or violates the specification. .. versionadded:: 6.0.0 """ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734780961.0 hyperframe-6.1.0/src/hyperframe/flags.py0000644000076500000240000000241614731524041017624 0ustar00kriechistaff""" Basic Flag and Flags data structures. """ from __future__ import annotations from collections.abc import Iterable, Iterator, MutableSet from typing import NamedTuple class Flag(NamedTuple): name: str bit: int class Flags(MutableSet): # type: ignore """ A simple MutableSet implementation that will only accept known flags as elements. Will behave like a regular set(), except that a ValueError will be thrown when .add()ing unexpected flags. """ def __init__(self, defined_flags: Iterable[Flag]) -> None: self._valid_flags = {flag.name for flag in defined_flags} self._flags: set[str] = set() def __repr__(self) -> str: return repr(sorted(self._flags)) def __contains__(self, x: object) -> bool: return self._flags.__contains__(x) def __iter__(self) -> Iterator[str]: return self._flags.__iter__() def __len__(self) -> int: return self._flags.__len__() def discard(self, value: str) -> None: return self._flags.discard(value) def add(self, value: str) -> None: if value not in self._valid_flags: msg = f"Unexpected flag: {value}. Valid flags are: {self._valid_flags}" raise ValueError(msg) return self._flags.add(value) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734780961.0 hyperframe-6.1.0/src/hyperframe/frame.py0000644000076500000240000007565314731524041017637 0ustar00kriechistaff""" Framing logic for HTTP/2. Provides both classes to represent framed data and logic for aiding the connection when it comes to reading from the socket. """ from __future__ import annotations import binascii import struct from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from collections.abc import Iterable # pragma: no cover from .exceptions import InvalidDataError, InvalidFrameError, InvalidPaddingError, UnknownFrameError from .flags import Flag, Flags # The maximum initial length of a frame. Some frames have shorter maximum # lengths. FRAME_MAX_LEN = (2 ** 14) # The maximum allowed length of a frame. FRAME_MAX_ALLOWED_LEN = (2 ** 24) - 1 # Stream association enumerations. _STREAM_ASSOC_HAS_STREAM = "has-stream" _STREAM_ASSOC_NO_STREAM = "no-stream" _STREAM_ASSOC_EITHER = "either" # Structs for packing and unpacking _STRUCT_HBBBL = struct.Struct(">HBBBL") _STRUCT_LL = struct.Struct(">LL") _STRUCT_HL = struct.Struct(">HL") _STRUCT_LB = struct.Struct(">LB") _STRUCT_L = struct.Struct(">L") _STRUCT_H = struct.Struct(">H") _STRUCT_B = struct.Struct(">B") class Frame: """ The base class for all HTTP/2 frames. """ #: The flags defined on this type of frame. defined_flags: list[Flag] = [] #: The byte used to define the type of the frame. type: int | None = None # If 'has-stream', the frame's stream_id must be non-zero. If 'no-stream', # it must be zero. If 'either', it's not checked. stream_association: str | None = None def __init__(self, stream_id: int, flags: Iterable[str] = ()) -> None: #: The stream identifier for the stream this frame was received on. #: Set to 0 for frames sent on the connection (stream-id 0). self.stream_id = stream_id #: The flags set for this frame. self.flags = Flags(self.defined_flags) #: The frame length, excluding the nine-byte header. self.body_len = 0 for flag in flags: self.flags.add(flag) if not self.stream_id and self.stream_association == _STREAM_ASSOC_HAS_STREAM: msg = f"Stream ID must be non-zero for {type(self).__name__}" raise InvalidDataError(msg) if self.stream_id and self.stream_association == _STREAM_ASSOC_NO_STREAM: msg = f"Stream ID must be zero for {type(self).__name__} with stream_id={self.stream_id}" raise InvalidDataError(msg) def __repr__(self) -> str: return ( f"{type(self).__name__}(stream_id={self.stream_id}, flags={self.flags!r}): {self._body_repr()}" ) def _body_repr(self) -> str: # More specific implementation may be provided by subclasses of Frame. # This fallback shows the serialized (and truncated) body content. return _raw_data_repr(self.serialize_body()) @staticmethod def explain(data: memoryview) -> tuple[Frame, int]: """ Takes a bytestring and tries to parse a single frame and print it. This function is only provided for debugging purposes. :param data: A memoryview object containing the raw data of at least one complete frame (header and body). .. versionadded:: 6.0.0 """ frame, length = Frame.parse_frame_header(data[:9]) frame.parse_body(data[9:9 + length]) print(frame) # noqa: T201 return frame, length @staticmethod def parse_frame_header(header: memoryview, strict: bool = False) -> tuple[Frame, int]: """ Takes a 9-byte frame header and returns a tuple of the appropriate Frame object and the length that needs to be read from the socket. This populates the flags field, and determines how long the body is. :param header: A memoryview object containing the 9-byte frame header data of a frame. Must not contain more or less. :param strict: Whether to raise an exception when encountering a frame not defined by spec and implemented by hyperframe. :raises hyperframe.exceptions.UnknownFrameError: If a frame of unknown type is received. .. versionchanged:: 5.0.0 Added ``strict`` parameter to accommodate :class:`ExtensionFrame` """ try: fields = _STRUCT_HBBBL.unpack(header) except struct.error as err: msg = "Invalid frame header" raise InvalidFrameError(msg) from err # First 24 bits are frame length. length = (fields[0] << 8) + fields[1] typ_e = fields[2] flags = fields[3] stream_id = fields[4] & 0x7FFFFFFF try: frame = FRAMES[typ_e](stream_id) except KeyError as err: if strict: raise UnknownFrameError(typ_e, length) from err frame = ExtensionFrame(type=typ_e, stream_id=stream_id) frame.parse_flags(flags) return (frame, length) def parse_flags(self, flag_byte: int) -> Flags: for flag, flag_bit in self.defined_flags: if flag_byte & flag_bit: self.flags.add(flag) return self.flags def serialize(self) -> bytes: """ Convert a frame into a bytestring, representing the serialized form of the frame. """ body = self.serialize_body() self.body_len = len(body) # Build the common frame header. # First, get the flags. flags = 0 for flag, flag_bit in self.defined_flags: if flag in self.flags: flags |= flag_bit header = _STRUCT_HBBBL.pack( (self.body_len >> 8) & 0xFFFF, # Length spread over top 24 bits self.body_len & 0xFF, self.type, flags, self.stream_id & 0x7FFFFFFF, # Stream ID is 32 bits. ) return header + body def serialize_body(self) -> bytes: raise NotImplementedError def parse_body(self, data: memoryview) -> None: """ Given the body of a frame, parses it into frame data. This populates the non-header parts of the frame: that is, it does not populate the stream ID or flags. :param data: A memoryview object containing the body data of the frame. Must not contain *more* data than the length returned by :meth:`parse_frame_header `. """ raise NotImplementedError class Padding: """ Mixin for frames that contain padding. Defines extra fields that can be used and set by frames that can be padded. """ def __init__(self, stream_id: int, pad_length: int = 0, **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) # type: ignore #: The length of the padding to use. self.pad_length = pad_length def serialize_padding_data(self) -> bytes: if "PADDED" in self.flags: # type: ignore return _STRUCT_B.pack(self.pad_length) return b"" def parse_padding_data(self, data: memoryview) -> int: if "PADDED" in self.flags: # type: ignore try: self.pad_length = struct.unpack("!B", data[:1])[0] except struct.error as err: msg = "Invalid Padding data" raise InvalidFrameError(msg) from err return 1 return 0 #: .. deprecated:: 5.2.1 #: Use self.pad_length instead. @property def total_padding(self) -> int: # pragma: no cover import warnings warnings.warn( "total_padding contains the same information as pad_length.", DeprecationWarning, stacklevel=2, ) return self.pad_length class Priority: """ Mixin for frames that contain priority data. Defines extra fields that can be used and set by frames that contain priority data. """ def __init__(self, stream_id: int, depends_on: int = 0x0, stream_weight: int = 0x0, exclusive: bool = False, **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) # type: ignore #: The stream ID of the stream on which this stream depends. self.depends_on = depends_on #: The weight of the stream. This is an integer between 0 and 256. self.stream_weight = stream_weight #: Whether the exclusive bit was set. self.exclusive = exclusive def serialize_priority_data(self) -> bytes: return _STRUCT_LB.pack( self.depends_on + (0x80000000 if self.exclusive else 0), self.stream_weight, ) def parse_priority_data(self, data: memoryview) -> int: try: self.depends_on, self.stream_weight = _STRUCT_LB.unpack(data[:5]) except struct.error as err: msg = "Invalid Priority data" raise InvalidFrameError(msg) from err self.exclusive = bool(self.depends_on >> 31) self.depends_on &= 0x7FFFFFFF return 5 class DataFrame(Padding, Frame): """ DATA frames convey arbitrary, variable-length sequences of octets associated with a stream. One or more DATA frames are used, for instance, to carry HTTP request or response payloads. """ #: The flags defined for DATA frames. defined_flags = [ Flag("END_STREAM", 0x01), Flag("PADDED", 0x08), ] #: The type byte for data frames. type = 0x0 stream_association = _STREAM_ASSOC_HAS_STREAM def __init__(self, stream_id: int, data: bytes = b"", **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) #: The data contained on this frame. self.data = data def serialize_body(self) -> bytes: padding_data = self.serialize_padding_data() padding = b"\0" * self.pad_length if isinstance(self.data, memoryview): self.data = self.data.tobytes() return b"".join([padding_data, self.data, padding]) def parse_body(self, data: memoryview) -> None: padding_data_length = self.parse_padding_data(data) self.data = ( data[padding_data_length:len(data)-self.pad_length].tobytes() ) self.body_len = len(data) if self.pad_length and self.pad_length >= self.body_len: msg = "Padding is too long." raise InvalidPaddingError(msg) @property def flow_controlled_length(self) -> int: """ The length of the frame that needs to be accounted for when considering flow control. """ padding_len = 0 if "PADDED" in self.flags: # Account for extra 1-byte padding length field, which is still # present if possibly zero-valued. padding_len = self.pad_length + 1 return len(self.data) + padding_len class PriorityFrame(Priority, Frame): """ The PRIORITY frame specifies the sender-advised priority of a stream. It can be sent at any time for an existing stream. This enables reprioritisation of existing streams. """ #: The flags defined for PRIORITY frames. defined_flags: list[Flag] = [] #: The type byte defined for PRIORITY frames. type = 0x02 stream_association = _STREAM_ASSOC_HAS_STREAM def _body_repr(self) -> str: return f"exclusive={self.exclusive}, depends_on={self.depends_on}, stream_weight={self.stream_weight}" def serialize_body(self) -> bytes: return self.serialize_priority_data() def parse_body(self, data: memoryview) -> None: if len(data) > 5: msg = f"PRIORITY must have 5 byte body: actual length {len(data)}." raise InvalidFrameError(msg) self.parse_priority_data(data) self.body_len = 5 class RstStreamFrame(Frame): """ The RST_STREAM frame allows for abnormal termination of a stream. When sent by the initiator of a stream, it indicates that they wish to cancel the stream or that an error condition has occurred. When sent by the receiver of a stream, it indicates that either the receiver is rejecting the stream, requesting that the stream be cancelled or that an error condition has occurred. """ #: The flags defined for RST_STREAM frames. defined_flags: list[Flag] = [] #: The type byte defined for RST_STREAM frames. type = 0x03 stream_association = _STREAM_ASSOC_HAS_STREAM def __init__(self, stream_id: int, error_code: int = 0, **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) #: The error code used when resetting the stream. self.error_code = error_code def _body_repr(self) -> str: return f"error_code={self.error_code}" def serialize_body(self) -> bytes: return _STRUCT_L.pack(self.error_code) def parse_body(self, data: memoryview) -> None: if len(data) != 4: msg = f"RST_STREAM must have 4 byte body: actual length {len(data)}." raise InvalidFrameError(msg) try: self.error_code = _STRUCT_L.unpack(data)[0] except struct.error as err: # pragma: no cover msg = "Invalid RST_STREAM body" raise InvalidFrameError(msg) from err self.body_len = 4 class SettingsFrame(Frame): """ The SETTINGS frame conveys configuration parameters that affect how endpoints communicate. The parameters are either constraints on peer behavior or preferences. Settings are not negotiated. Settings describe characteristics of the sending peer, which are used by the receiving peer. Different values for the same setting can be advertised by each peer. For example, a client might set a high initial flow control window, whereas a server might set a lower value to conserve resources. """ #: The flags defined for SETTINGS frames. defined_flags = [Flag("ACK", 0x01)] #: The type byte defined for SETTINGS frames. type = 0x04 stream_association = _STREAM_ASSOC_NO_STREAM # We need to define the known settings, they may as well be class # attributes. #: The byte that signals the SETTINGS_HEADER_TABLE_SIZE setting. HEADER_TABLE_SIZE = 0x01 #: The byte that signals the SETTINGS_ENABLE_PUSH setting. ENABLE_PUSH = 0x02 #: The byte that signals the SETTINGS_MAX_CONCURRENT_STREAMS setting. MAX_CONCURRENT_STREAMS = 0x03 #: The byte that signals the SETTINGS_INITIAL_WINDOW_SIZE setting. INITIAL_WINDOW_SIZE = 0x04 #: The byte that signals the SETTINGS_MAX_FRAME_SIZE setting. MAX_FRAME_SIZE = 0x05 #: The byte that signals the SETTINGS_MAX_HEADER_LIST_SIZE setting. MAX_HEADER_LIST_SIZE = 0x06 #: The byte that signals SETTINGS_ENABLE_CONNECT_PROTOCOL setting. ENABLE_CONNECT_PROTOCOL = 0x08 def __init__(self, stream_id: int = 0, settings: dict[int, int] | None = None, **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) if settings and "ACK" in kwargs.get("flags", ()): msg = "Settings must be empty if ACK flag is set." raise InvalidDataError(msg) #: A dictionary of the setting type byte to the value of the setting. self.settings: dict[int, int] = settings or {} def _body_repr(self) -> str: return f"settings={self.settings}" def serialize_body(self) -> bytes: return b"".join([_STRUCT_HL.pack(setting & 0xFF, value) for setting, value in self.settings.items()]) def parse_body(self, data: memoryview) -> None: if "ACK" in self.flags and len(data) > 0: msg = f"SETTINGS ack frame must not have payload: got {len(data)} bytes" raise InvalidDataError(msg) body_len = 0 for i in range(0, len(data), 6): try: name, value = _STRUCT_HL.unpack(data[i:i+6]) except struct.error as err: msg = "Invalid SETTINGS body" raise InvalidFrameError(msg) from err self.settings[name] = value body_len += 6 self.body_len = body_len class PushPromiseFrame(Padding, Frame): """ The PUSH_PROMISE frame is used to notify the peer endpoint in advance of streams the sender intends to initiate. """ #: The flags defined for PUSH_PROMISE frames. defined_flags = [ Flag("END_HEADERS", 0x04), Flag("PADDED", 0x08), ] #: The type byte defined for PUSH_PROMISE frames. type = 0x05 stream_association = _STREAM_ASSOC_HAS_STREAM def __init__(self, stream_id: int, promised_stream_id: int = 0, data: bytes = b"", **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) #: The stream ID that is promised by this frame. self.promised_stream_id = promised_stream_id #: The HPACK-encoded header block for the simulated request on the new #: stream. self.data = data def _body_repr(self) -> str: return f"promised_stream_id={self.promised_stream_id}, data={_raw_data_repr(self.data)}" def serialize_body(self) -> bytes: padding_data = self.serialize_padding_data() padding = b"\0" * self.pad_length data = _STRUCT_L.pack(self.promised_stream_id) return b"".join([padding_data, data, self.data, padding]) def parse_body(self, data: memoryview) -> None: padding_data_length = self.parse_padding_data(data) try: self.promised_stream_id = _STRUCT_L.unpack( data[padding_data_length:padding_data_length + 4], )[0] except struct.error as err: msg = "Invalid PUSH_PROMISE body" raise InvalidFrameError(msg) from err self.data = ( data[padding_data_length + 4:len(data)-self.pad_length].tobytes() ) self.body_len = len(data) if self.promised_stream_id == 0 or self.promised_stream_id % 2 != 0: msg = f"Invalid PUSH_PROMISE promised stream id: {self.promised_stream_id}" raise InvalidDataError(msg) if self.pad_length and self.pad_length >= self.body_len: msg = "Padding is too long." raise InvalidPaddingError(msg) class PingFrame(Frame): """ The PING frame is a mechanism for measuring a minimal round-trip time from the sender, as well as determining whether an idle connection is still functional. PING frames can be sent from any endpoint. """ #: The flags defined for PING frames. defined_flags = [Flag("ACK", 0x01)] #: The type byte defined for PING frames. type = 0x06 stream_association = _STREAM_ASSOC_NO_STREAM def __init__(self, stream_id: int = 0, opaque_data: bytes = b"", **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) #: The opaque data sent in this PING frame, as a bytestring. self.opaque_data = opaque_data def _body_repr(self) -> str: return f"opaque_data={self.opaque_data!r}" def serialize_body(self) -> bytes: if len(self.opaque_data) > 8: msg = f"PING frame may not have more than 8 bytes of data, got {len(self.opaque_data)}" raise InvalidFrameError(msg) data = self.opaque_data data += b"\x00" * (8 - len(self.opaque_data)) return data def parse_body(self, data: memoryview) -> None: if len(data) != 8: msg = f"PING frame must have 8 byte length: got {len(data)}" raise InvalidFrameError(msg) self.opaque_data = data.tobytes() self.body_len = 8 class GoAwayFrame(Frame): """ The GOAWAY frame informs the remote peer to stop creating streams on this connection. It can be sent from the client or the server. Once sent, the sender will ignore frames sent on new streams for the remainder of the connection. """ #: The flags defined for GOAWAY frames. defined_flags: list[Flag] = [] #: The type byte defined for GOAWAY frames. type = 0x07 stream_association = _STREAM_ASSOC_NO_STREAM def __init__(self, stream_id: int = 0, last_stream_id: int = 0, error_code: int = 0, additional_data: bytes = b"", **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) #: The last stream ID definitely seen by the remote peer. self.last_stream_id = last_stream_id #: The error code for connection teardown. self.error_code = error_code #: Any additional data sent in the GOAWAY. self.additional_data = additional_data def _body_repr(self) -> str: return f"last_stream_id={self.last_stream_id}, error_code={self.error_code}, additional_data={self.additional_data!r}" def serialize_body(self) -> bytes: data = _STRUCT_LL.pack( self.last_stream_id & 0x7FFFFFFF, self.error_code, ) data += self.additional_data return data def parse_body(self, data: memoryview) -> None: try: self.last_stream_id, self.error_code = _STRUCT_LL.unpack( data[:8], ) except struct.error as err: msg = "Invalid GOAWAY body." raise InvalidFrameError(msg) from err self.body_len = len(data) if len(data) > 8: self.additional_data = data[8:].tobytes() class WindowUpdateFrame(Frame): """ The WINDOW_UPDATE frame is used to implement flow control. Flow control operates at two levels: on each individual stream and on the entire connection. Both types of flow control are hop by hop; that is, only between the two endpoints. Intermediaries do not forward WINDOW_UPDATE frames between dependent connections. However, throttling of data transfer by any receiver can indirectly cause the propagation of flow control information toward the original sender. """ #: The flags defined for WINDOW_UPDATE frames. defined_flags: list[Flag] = [] #: The type byte defined for WINDOW_UPDATE frames. type = 0x08 stream_association = _STREAM_ASSOC_EITHER def __init__(self, stream_id: int, window_increment: int = 0, **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) #: The amount the flow control window is to be incremented. self.window_increment = window_increment def _body_repr(self) -> str: return f"window_increment={self.window_increment}" def serialize_body(self) -> bytes: return _STRUCT_L.pack(self.window_increment & 0x7FFFFFFF) def parse_body(self, data: memoryview) -> None: if len(data) > 4: msg = f"WINDOW_UPDATE frame must have 4 byte length: got {len(data)}" raise InvalidFrameError(msg) try: self.window_increment = _STRUCT_L.unpack(data)[0] except struct.error as err: msg = "Invalid WINDOW_UPDATE body" raise InvalidFrameError(msg) from err if not 1 <= self.window_increment <= 2**31-1: msg = "WINDOW_UPDATE increment must be between 1 to 2^31-1" raise InvalidDataError(msg) self.body_len = 4 class HeadersFrame(Padding, Priority, Frame): """ The HEADERS frame carries name-value pairs. It is used to open a stream. HEADERS frames can be sent on a stream in the "open" or "half closed (remote)" states. The HeadersFrame class is actually basically a data frame in this implementation, because of the requirement to control the sizes of frames. A header block fragment that doesn't fit in an entire HEADERS frame needs to be followed with CONTINUATION frames. From the perspective of the frame building code the header block is an opaque data segment. """ #: The flags defined for HEADERS frames. defined_flags = [ Flag("END_STREAM", 0x01), Flag("END_HEADERS", 0x04), Flag("PADDED", 0x08), Flag("PRIORITY", 0x20), ] #: The type byte defined for HEADERS frames. type = 0x01 stream_association = _STREAM_ASSOC_HAS_STREAM def __init__(self, stream_id: int, data: bytes = b"", **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) #: The HPACK-encoded header block. self.data = data def _body_repr(self) -> str: return f"exclusive={self.exclusive}, depends_on={self.depends_on}, stream_weight={self.stream_weight}, data={_raw_data_repr(self.data)}" def serialize_body(self) -> bytes: padding_data = self.serialize_padding_data() padding = b"\0" * self.pad_length if "PRIORITY" in self.flags: priority_data = self.serialize_priority_data() else: priority_data = b"" return b"".join([padding_data, priority_data, self.data, padding]) def parse_body(self, data: memoryview) -> None: padding_data_length = self.parse_padding_data(data) data = data[padding_data_length:] if "PRIORITY" in self.flags: priority_data_length = self.parse_priority_data(data) else: priority_data_length = 0 self.body_len = len(data) self.data = ( data[priority_data_length:len(data)-self.pad_length].tobytes() ) if self.pad_length and self.pad_length >= self.body_len: msg = "Padding is too long." raise InvalidPaddingError(msg) class ContinuationFrame(Frame): """ The CONTINUATION frame is used to continue a sequence of header block fragments. Any number of CONTINUATION frames can be sent on an existing stream, as long as the preceding frame on the same stream is one of HEADERS, PUSH_PROMISE or CONTINUATION without the END_HEADERS flag set. Much like the HEADERS frame, hyper treats this as an opaque data frame with different flags and a different type. """ #: The flags defined for CONTINUATION frames. defined_flags = [Flag("END_HEADERS", 0x04)] #: The type byte defined for CONTINUATION frames. type = 0x09 stream_association = _STREAM_ASSOC_HAS_STREAM def __init__(self, stream_id: int, data: bytes = b"", **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) #: The HPACK-encoded header block. self.data = data def _body_repr(self) -> str: return f"data={_raw_data_repr(self.data)}" def serialize_body(self) -> bytes: return self.data def parse_body(self, data: memoryview) -> None: self.data = data.tobytes() self.body_len = len(data) class AltSvcFrame(Frame): """ The ALTSVC frame is used to advertise alternate services that the current host, or a different one, can understand. This frame is standardised as part of RFC 7838. This frame does no work to validate that the ALTSVC field parameter is acceptable per the rules of RFC 7838. .. note:: If the ``stream_id`` of this frame is nonzero, the origin field must have zero length. Conversely, if the ``stream_id`` of this frame is zero, the origin field must have nonzero length. Put another way, a valid ALTSVC frame has ``stream_id != 0`` XOR ``len(origin) != 0``. """ type = 0x0A stream_association = _STREAM_ASSOC_EITHER def __init__(self, stream_id: int, origin: bytes = b"", field: bytes = b"", **kwargs: Any) -> None: super().__init__(stream_id, **kwargs) if not isinstance(origin, bytes): msg = "AltSvc origin must be a bytestring." raise InvalidDataError(msg) if not isinstance(field, bytes): msg = "AltSvc field must be a bytestring." raise InvalidDataError(msg) self.origin = origin self.field = field def _body_repr(self) -> str: return f"origin={self.origin!r}, field={self.field!r}" def serialize_body(self) -> bytes: origin_len = _STRUCT_H.pack(len(self.origin)) return b"".join([origin_len, self.origin, self.field]) def parse_body(self, data: memoryview) -> None: try: origin_len = _STRUCT_H.unpack(data[0:2])[0] self.origin = data[2:2+origin_len].tobytes() if len(self.origin) != origin_len: msg = "Invalid ALTSVC frame body." raise InvalidFrameError(msg) self.field = data[2+origin_len:].tobytes() except (struct.error, ValueError) as err: msg = "Invalid ALTSVC frame body." raise InvalidFrameError(msg) from err self.body_len = len(data) class ExtensionFrame(Frame): """ ExtensionFrame is used to wrap frames which are not natively interpretable by hyperframe. Although certain byte prefixes are ordained by specification to have certain contextual meanings, frames with other prefixes are not prohibited, and may be used to communicate arbitrary meaning between HTTP/2 peers. Thus, hyperframe, rather than raising an exception when such a frame is encountered, wraps it in a generic frame to be properly acted upon by upstream consumers which might have additional context on how to use it. .. versionadded:: 5.0.0 """ stream_association = _STREAM_ASSOC_EITHER def __init__(self, type: int, stream_id: int, flag_byte: int = 0x0, body: bytes = b"", **kwargs: Any) -> None: # noqa: A002 super().__init__(stream_id, **kwargs) self.type = type self.flag_byte = flag_byte self.body = body def _body_repr(self) -> str: return f"type={self.type}, flag_byte={self.flag_byte}, body={_raw_data_repr(self.body)}" def parse_flags(self, flag_byte: int) -> None: # type: ignore """ For extension frames, we parse the flags by just storing a flag byte. """ self.flag_byte = flag_byte def parse_body(self, data: memoryview) -> None: self.body = data.tobytes() self.body_len = len(data) def serialize(self) -> bytes: """ A broad override of the serialize method that ensures that the data comes back out exactly as it came in. This should not be used in most user code: it exists only as a helper method if frames need to be reconstituted. """ # Build the frame header. # First, get the flags. flags = self.flag_byte header = _STRUCT_HBBBL.pack( (self.body_len >> 8) & 0xFFFF, # Length spread over top 24 bits self.body_len & 0xFF, self.type, flags, self.stream_id & 0x7FFFFFFF, # Stream ID is 32 bits. ) return header + self.body def _raw_data_repr(data: bytes | None) -> str: if not data: return "None" r = binascii.hexlify(data).decode("ascii") if len(r) > 20: r = r[:20] + "..." return "" _FRAME_CLASSES: list[type[Frame]] = [ DataFrame, HeadersFrame, PriorityFrame, RstStreamFrame, SettingsFrame, PushPromiseFrame, PingFrame, GoAwayFrame, WindowUpdateFrame, ContinuationFrame, AltSvcFrame, ] #: FRAMES maps the type byte for each frame to the class used to represent that #: frame. FRAMES = {cls.type: cls for cls in _FRAME_CLASSES} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1618659711.0 hyperframe-6.1.0/src/hyperframe/py.typed0000644000076500000240000000000014036544577017656 0ustar00kriechistaff././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1737581761.1982508 hyperframe-6.1.0/src/hyperframe.egg-info/0000755000076500000240000000000014744262301017647 5ustar00kriechistaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1737581761.0 hyperframe-6.1.0/src/hyperframe.egg-info/PKG-INFO0000644000076500000240000001036314744262301020747 0ustar00kriechistaffMetadata-Version: 2.2 Name: hyperframe Version: 6.1.0 Summary: Pure-Python HTTP/2 framing Author-email: Cory Benfield Maintainer-email: Thomas Kriechbaumer License: The MIT License (MIT) Copyright (c) 2014 Cory Benfield Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Project-URL: Homepage, https://github.com/python-hyper/hyperframe/ Project-URL: Bug Reports, https://github.com/python-hyper/hyperframe/issues Project-URL: Source, https://github.com/python-hyper/hyperframe/ Project-URL: Documentation, https://python-hyper.org/ Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=3.9 Description-Content-Type: text/x-rst License-File: LICENSE ====================================== hyperframe: Pure-Python HTTP/2 framing ====================================== .. image:: https://github.com/python-hyper/hyperframe/workflows/CI/badge.svg :target: https://github.com/python-hyper/hyperframe/actions :alt: Build Status .. image:: https://codecov.io/gh/python-hyper/hyperframe/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-hyper/hyperframe :alt: Code Coverage .. image:: https://readthedocs.org/projects/hyperframe/badge/?version=latest :target: https://hyperframe.readthedocs.io/en/latest/ :alt: Documentation Status .. image:: https://img.shields.io/badge/chat-join_now-brightgreen.svg :target: https://gitter.im/python-hyper/community :alt: Chat community This library contains the HTTP/2 framing code used in the `hyper`_ project. It provides a pure-Python codebase that is capable of decoding a binary stream into HTTP/2 frames. This library is used directly by `hyper`_ and a number of other projects to provide HTTP/2 frame decoding logic. Contributing ============ hyperframe welcomes contributions from anyone! Unlike many other projects we are happy to accept cosmetic contributions and small contributions, in addition to large feature requests and changes. Before you contribute (either by opening an issue or filing a pull request), please `read the contribution guidelines`_. .. _read the contribution guidelines: http://hyper.readthedocs.org/en/development/contributing.html License ======= hyperframe is made available under the MIT License. For more details, see the ``LICENSE`` file in the repository. Authors ======= hyperframe is maintained by Cory Benfield, with contributions from others. For more details about the contributors, please see ``CONTRIBUTORS.rst``. .. _hyper: http://python-hyper.org/ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1737581761.0 hyperframe-6.1.0/src/hyperframe.egg-info/SOURCES.txt0000644000076500000240000000113614744262301021534 0ustar00kriechistaff.gitmodules CHANGELOG.rst CONTRIBUTORS.rst LICENSE MANIFEST.in README.rst pyproject.toml docs/Makefile docs/make.bat docs/source/api.rst docs/source/conf.py docs/source/index.rst docs/source/installation.rst docs/source/_static/.keep src/hyperframe/__init__.py src/hyperframe/exceptions.py src/hyperframe/flags.py src/hyperframe/frame.py src/hyperframe/py.typed src/hyperframe.egg-info/PKG-INFO src/hyperframe.egg-info/SOURCES.txt src/hyperframe.egg-info/dependency_links.txt src/hyperframe.egg-info/top_level.txt tests/__init__.py tests/test_external_collection.py tests/test_flags.py tests/test_frames.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1737581761.0 hyperframe-6.1.0/src/hyperframe.egg-info/dependency_links.txt0000644000076500000240000000000114744262301023715 0ustar00kriechistaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1737581761.0 hyperframe-6.1.0/src/hyperframe.egg-info/top_level.txt0000644000076500000240000000001314744262301022373 0ustar00kriechistaffhyperframe ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1737581761.1980376 hyperframe-6.1.0/tests/0000755000076500000240000000000014744262301014366 5ustar00kriechistaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1544712076.0 hyperframe-6.1.0/tests/__init__.py0000644000076500000240000000000013404467614016473 0ustar00kriechistaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1596060960.0 hyperframe-6.1.0/tests/test_external_collection.py0000644000076500000240000000617413710372440022042 0ustar00kriechistaff# https://github.com/http2jp/http2-frame-test-case import os import json import pytest from hyperframe.frame import Frame tc_filepaths = [] root = os.path.dirname(__file__) path = os.walk(os.path.join(root, "http2-frame-test-case")) for dirpath, dirnames, filenames in path: for filename in filenames: if os.path.splitext(filename)[1] != ".json": continue tc_filepaths.append( os.path.relpath(os.path.join(dirpath, filename), root) ) def check_valid_frame(tc, data): # noqa: C901 new_frame, length = Frame.parse_frame_header(data[:9], strict=True) new_frame.parse_body(memoryview(data[9:9 + length])) assert tc["frame"]["length"] == length assert tc["frame"]["stream_identifier"] == new_frame.stream_id assert tc["frame"]["type"] == new_frame.type flags = 0 for flag, flag_bit in new_frame.defined_flags: if flag in new_frame.flags: flags |= flag_bit assert tc["frame"]["flags"] == flags p = tc["frame"]["frame_payload"] if "header_block_fragment" in p: assert p["header_block_fragment"] == new_frame.data.decode() if "data" in p: assert p["data"] == new_frame.data.decode() if "padding" in p: # the padding data itself is not retained by hyperframe after parsing pass if "padding_length" in p and p["padding_length"]: assert p["padding_length"] == new_frame.pad_length if "error_code" in p: assert p["error_code"] == new_frame.error_code if "additional_debug_data" in p: assert p["additional_debug_data"].encode() == new_frame.additional_data if "last_stream_id" in p: assert p["last_stream_id"] == new_frame.last_stream_id if "stream_dependency" in p: assert p["stream_dependency"] or 0 == new_frame.depends_on if "weight" in p and p["weight"]: assert p["weight"] - 1 == new_frame.stream_weight if "exclusive" in p: assert (p["exclusive"] or False) == new_frame.exclusive if "opaque_data" in p: assert p["opaque_data"].encode() == new_frame.opaque_data if "promised_stream_id" in p: assert p["promised_stream_id"] == new_frame.promised_stream_id if "settings" in p: assert dict(p["settings"]) == new_frame.settings if "window_size_increment" in p: assert p["window_size_increment"] == new_frame.window_increment class TestExternalCollection: @pytest.mark.parametrize('tc_filepath', tc_filepaths) def test(self, tc_filepath): with open(os.path.join(root, tc_filepath)) as f: tc = json.load(f) data = bytes.fromhex(tc["wire"]) if tc["error"] is None and tc["frame"]: check_valid_frame(tc, data) elif tc["error"] and tc["frame"] is None: with pytest.raises(Exception): new_frame, length = Frame.parse_frame_header( data[:9], strict=True ) new_frame.parse_body(memoryview(data[9:9 + length])) assert length == new_frame.body_len else: pytest.fail("unexpected test case: {} {}".format(tc_filepath, tc)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734780961.0 hyperframe-6.1.0/tests/test_flags.py0000644000076500000240000000231114731524041017066 0ustar00kriechistafffrom hyperframe.frame import ( Flags, Flag, ) import pytest class TestFlags: def test_add(self): flags = Flags([Flag("VALID_FLAG", 0x00)]) assert not flags flags.add("VALID_FLAG") flags.add("VALID_FLAG") assert "VALID_FLAG" in flags assert list(flags) == ["VALID_FLAG"] assert len(flags) == 1 def test_remove(self): flags = Flags([Flag("VALID_FLAG", 0x00)]) flags.add("VALID_FLAG") flags.discard("VALID_FLAG") assert "VALID_FLAG" not in flags assert list(flags) == [] assert len(flags) == 0 # discarding elements not in the set should not throw an exception flags.discard("END_STREAM") def test_validation(self): flags = Flags([Flag("VALID_FLAG", 0x00)]) flags.add("VALID_FLAG") with pytest.raises(ValueError): flags.add("INVALID_FLAG") def test_repr(self): flags = Flags([Flag("VALID_FLAG", 0x00), Flag("OTHER_FLAG", 0x01)]) assert repr(flags) == "[]" flags.add("VALID_FLAG") assert repr(flags) == "['VALID_FLAG']" flags.add("OTHER_FLAG") assert repr(flags) == "['OTHER_FLAG', 'VALID_FLAG']" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734780961.0 hyperframe-6.1.0/tests/test_frames.py0000644000076500000240000007355614731524041017272 0ustar00kriechistafffrom hyperframe.frame import ( Frame, Flags, DataFrame, PriorityFrame, RstStreamFrame, SettingsFrame, PushPromiseFrame, PingFrame, GoAwayFrame, WindowUpdateFrame, HeadersFrame, ContinuationFrame, AltSvcFrame, ExtensionFrame ) from hyperframe.exceptions import ( UnknownFrameError, InvalidPaddingError, InvalidFrameError, InvalidDataError ) import pytest def decode_frame(frame_data): f, length = Frame.parse_frame_header(frame_data[:9]) f.parse_body(memoryview(frame_data[9:9 + length])) assert 9 + length == len(frame_data) return f class TestGeneralFrameBehaviour: def test_base_frame_ignores_flags(self): f = Frame(0) flags = f.parse_flags(0xFF) assert not flags assert isinstance(flags, Flags) def test_base_frame_cant_serialize(self): f = Frame(0) with pytest.raises(NotImplementedError): f.serialize() def test_base_frame_cant_parse_body(self): data = b'' f = Frame(0) with pytest.raises(NotImplementedError): f.parse_body(data) def test_parse_frame_header_unknown_type_strict(self): with pytest.raises(UnknownFrameError) as excinfo: Frame.parse_frame_header( b'\x00\x00\x59\xFF\x00\x00\x00\x00\x01', strict=True ) exception = excinfo.value assert exception.frame_type == 0xFF assert exception.length == 0x59 assert str(exception) == ( "UnknownFrameError: Unknown frame type 0xFF received, " "length 89 bytes" ) def test_parse_frame_header_ignore_first_bit_of_stream_id(self): s = b'\x00\x00\x00\x06\x01\x80\x00\x00\x00' f, _ = Frame.parse_frame_header(s) assert f.stream_id == 0 def test_parse_frame_header_unknown_type(self): frame, length = Frame.parse_frame_header( b'\x00\x00\x59\xFF\x00\x00\x00\x00\x01' ) assert frame.type == 0xFF assert length == 0x59 assert isinstance(frame, ExtensionFrame) assert frame.stream_id == 1 def test_flags_are_persisted(self): frame, length = Frame.parse_frame_header( b'\x00\x00\x59\xFF\x09\x00\x00\x00\x01' ) assert frame.type == 0xFF assert length == 0x59 assert frame.flag_byte == 0x09 def test_parse_body_unknown_type(self): frame = decode_frame( b'\x00\x00\x0C\xFF\x00\x00\x00\x00\x01hello world!' ) assert frame.body == b'hello world!' assert frame.body_len == 12 assert frame.stream_id == 1 def test_can_round_trip_unknown_frames(self): frame_data = b'\x00\x00\x0C\xFF\x00\x00\x00\x00\x01hello world!' f = decode_frame(frame_data) assert f.serialize() == frame_data def test_repr(self, monkeypatch): f = Frame(0) monkeypatch.setattr(Frame, "serialize_body", lambda _: b"body") assert repr(f) == ( "Frame(stream_id=0, flags=[]): " ) f.stream_id = 42 f.flags = ["END_STREAM", "PADDED"] assert repr(f) == ( "Frame(stream_id=42, flags=['END_STREAM', 'PADDED']): " ) monkeypatch.setattr(Frame, "serialize_body", lambda _: b"A"*25) assert repr(f) == ( "Frame(stream_id=42, flags=['END_STREAM', 'PADDED']): ".format("41"*10) ) def test_frame_explain(self, capsys): d = b'\x00\x00\x08\x00\x01\x00\x00\x00\x01testdata' Frame.explain(memoryview(d)) captured = capsys.readouterr() assert captured.out.strip() == "DataFrame(stream_id=1, flags=['END_STREAM']): " def test_cannot_parse_invalid_frame_header(self): with pytest.raises(InvalidFrameError): Frame.parse_frame_header(b'\x00\x00\x08\x00\x01\x00\x00\x00') class TestDataFrame: payload = b'\x00\x00\x08\x00\x01\x00\x00\x00\x01testdata' payload_with_padding = ( b'\x00\x00\x13\x00\x09\x00\x00\x00\x01\x0Atestdata' + b'\0' * 10 ) def test_repr(self): f = DataFrame(1, b"testdata") assert repr(f).endswith("") def test_data_frame_has_correct_flags(self): f = DataFrame(1) flags = f.parse_flags(0xFF) assert flags == set([ 'END_STREAM', 'PADDED' ]) @pytest.mark.parametrize('data', [ b'testdata', memoryview(b'testdata') ]) def test_data_frame_serializes_properly(self, data): f = DataFrame(1) f.flags = set(['END_STREAM']) f.data = data s = f.serialize() assert s == self.payload def test_data_frame_with_padding_serializes_properly(self): f = DataFrame(1) f.flags = set(['END_STREAM', 'PADDED']) f.data = b'testdata' f.pad_length = 10 s = f.serialize() assert s == self.payload_with_padding def test_data_frame_parses_properly(self): f = decode_frame(self.payload) assert isinstance(f, DataFrame) assert f.flags == set(['END_STREAM']) assert f.pad_length == 0 assert f.data == b'testdata' assert f.body_len == 8 def test_data_frame_with_padding_parses_properly(self): f = decode_frame(self.payload_with_padding) assert isinstance(f, DataFrame) assert f.flags == set(['END_STREAM', 'PADDED']) assert f.pad_length == 10 assert f.data == b'testdata' assert f.body_len == 19 def test_data_frame_with_invalid_padding_errors(self): with pytest.raises(InvalidFrameError): decode_frame(self.payload_with_padding[:9]) def test_data_frame_with_padding_calculates_flow_control_len(self): f = DataFrame(1) f.flags = set(['PADDED']) f.data = b'testdata' f.pad_length = 10 assert f.flow_controlled_length == 19 def test_data_frame_zero_length_padding_calculates_flow_control_len(self): f = DataFrame(1) f.flags = set(['PADDED']) f.data = b'testdata' f.pad_length = 0 assert f.flow_controlled_length == len(b'testdata') + 1 def test_data_frame_without_padding_calculates_flow_control_len(self): f = DataFrame(1) f.data = b'testdata' assert f.flow_controlled_length == 8 def test_data_frame_comes_on_a_stream(self): with pytest.raises(InvalidDataError): DataFrame(0) def test_long_data_frame(self): f = DataFrame(1) # Use more than 256 bytes of data to force setting higher bits. f.data = b'\x01' * 300 data = f.serialize() # The top three bytes should be numerically equal to 300. That means # they should read 00 01 2C. # The weird double index trick is to ensure this test behaves equally # on Python 2 and Python 3. assert data[0] == b'\x00'[0] assert data[1] == b'\x01'[0] assert data[2] == b'\x2C'[0] def test_body_length_behaves_correctly(self): f = DataFrame(1) f.data = b'\x01' * 300 # Initially the body length is zero. For now this is incidental, but # I'm going to test it to ensure that the behaviour is codified. We # should change this test if we change that. assert f.body_len == 0 f.serialize() assert f.body_len == 300 def test_data_frame_with_invalid_padding_fails_to_parse(self): # This frame has a padding length of 6 bytes, but a total length of # only 5. data = b'\x00\x00\x05\x00\x0b\x00\x00\x00\x01\x06\x54\x65\x73\x74' with pytest.raises(InvalidPaddingError): decode_frame(data) def test_data_frame_with_no_length_parses(self): # Fixes issue with empty data frames raising InvalidPaddingError. f = DataFrame(1) f.data = b'' data = f.serialize() new_frame = decode_frame(data) assert new_frame.data == b'' class TestPriorityFrame: payload = b'\x00\x00\x05\x02\x00\x00\x00\x00\x01\x80\x00\x00\x04\x40' def test_repr(self): f = PriorityFrame(1) assert repr(f).endswith("exclusive=False, depends_on=0, stream_weight=0") f.exclusive = True f.depends_on = 0x04 f.stream_weight = 64 assert repr(f).endswith("exclusive=True, depends_on=4, stream_weight=64") def test_priority_frame_has_no_flags(self): f = PriorityFrame(1) flags = f.parse_flags(0xFF) assert flags == set() assert isinstance(flags, Flags) def test_priority_frame_default_serializes_properly(self): f = PriorityFrame(1) assert f.serialize() == ( b'\x00\x00\x05\x02\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00' ) def test_priority_frame_with_all_data_serializes_properly(self): f = PriorityFrame(1) f.depends_on = 0x04 f.stream_weight = 64 f.exclusive = True assert f.serialize() == self.payload def test_priority_frame_with_all_data_parses_properly(self): f = decode_frame(self.payload) assert isinstance(f, PriorityFrame) assert f.flags == set() assert f.depends_on == 4 assert f.stream_weight == 64 assert f.exclusive is True assert f.body_len == 5 def test_priority_frame_invalid(self): with pytest.raises(InvalidFrameError): decode_frame( b'\x00\x00\x06\x02\x00\x00\x00\x00\x01\x80\x00\x00\x04\x40\xFF' ) def test_priority_frame_comes_on_a_stream(self): with pytest.raises(InvalidDataError): PriorityFrame(0) def test_short_priority_frame_errors(self): with pytest.raises(InvalidFrameError): decode_frame(self.payload[:-2]) class TestRstStreamFrame: def test_repr(self): f = RstStreamFrame(1) assert repr(f).endswith("error_code=0") f.error_code = 420 assert repr(f).endswith("error_code=420") def test_rst_stream_frame_has_no_flags(self): f = RstStreamFrame(1) flags = f.parse_flags(0xFF) assert not flags assert isinstance(flags, Flags) def test_rst_stream_frame_serializes_properly(self): f = RstStreamFrame(1) f.error_code = 420 s = f.serialize() assert s == b'\x00\x00\x04\x03\x00\x00\x00\x00\x01\x00\x00\x01\xa4' def test_rst_stream_frame_parses_properly(self): s = b'\x00\x00\x04\x03\x00\x00\x00\x00\x01\x00\x00\x01\xa4' f = decode_frame(s) assert isinstance(f, RstStreamFrame) assert f.flags == set() assert f.error_code == 420 assert f.body_len == 4 def test_rst_stream_frame_comes_on_a_stream(self): with pytest.raises(InvalidDataError): RstStreamFrame(0) def test_rst_stream_frame_must_have_body_length_four(self): f = RstStreamFrame(1) with pytest.raises(InvalidFrameError): f.parse_body(b'\x01') class TestSettingsFrame: serialized = ( b'\x00\x00\x2A\x04\x01\x00\x00\x00\x00' + # Frame header b'\x00\x01\x00\x00\x10\x00' + # HEADER_TABLE_SIZE b'\x00\x02\x00\x00\x00\x00' + # ENABLE_PUSH b'\x00\x03\x00\x00\x00\x64' + # MAX_CONCURRENT_STREAMS b'\x00\x04\x00\x00\xFF\xFF' + # INITIAL_WINDOW_SIZE b'\x00\x05\x00\x00\x40\x00' + # MAX_FRAME_SIZE b'\x00\x06\x00\x00\xFF\xFF' + # MAX_HEADER_LIST_SIZE b'\x00\x08\x00\x00\x00\x01' # ENABLE_CONNECT_PROTOCOL ) settings = { SettingsFrame.HEADER_TABLE_SIZE: 4096, SettingsFrame.ENABLE_PUSH: 0, SettingsFrame.MAX_CONCURRENT_STREAMS: 100, SettingsFrame.INITIAL_WINDOW_SIZE: 65535, SettingsFrame.MAX_FRAME_SIZE: 16384, SettingsFrame.MAX_HEADER_LIST_SIZE: 65535, SettingsFrame.ENABLE_CONNECT_PROTOCOL: 1, } def test_repr(self): f = SettingsFrame() assert repr(f).endswith("settings={}") f.settings[SettingsFrame.MAX_FRAME_SIZE] = 16384 assert repr(f).endswith("settings={5: 16384}") def test_settings_frame_has_only_one_flag(self): f = SettingsFrame() flags = f.parse_flags(0xFF) assert flags == set(['ACK']) def test_settings_frame_serializes_properly(self): f = SettingsFrame() f.parse_flags(0xFF) f.settings = self.settings s = f.serialize() assert s == self.serialized def test_settings_frame_with_settings(self): f = SettingsFrame(settings=self.settings) assert f.settings == self.settings def test_settings_frame_without_settings(self): f = SettingsFrame() assert f.settings == {} def test_settings_frame_with_ack(self): f = SettingsFrame(flags=('ACK',)) assert 'ACK' in f.flags def test_settings_frame_ack_and_settings(self): with pytest.raises(InvalidDataError): SettingsFrame(settings=self.settings, flags=('ACK',)) with pytest.raises(InvalidDataError): decode_frame(self.serialized) def test_settings_frame_parses_properly(self): # unset the ACK flag to allow correct parsing data = self.serialized[:4] + b"\x00" + self.serialized[5:] f = decode_frame(data) assert isinstance(f, SettingsFrame) assert f.flags == set() assert f.settings == self.settings assert f.body_len == 42 def test_settings_frame_invalid_body_length(self): with pytest.raises(InvalidFrameError): decode_frame( b'\x00\x00\x2A\x04\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF' ) def test_settings_frames_never_have_streams(self): with pytest.raises(InvalidDataError): SettingsFrame(1) def test_short_settings_frame_errors(self): with pytest.raises(InvalidDataError): decode_frame(self.serialized[:-2]) class TestPushPromiseFrame: def test_repr(self): f = PushPromiseFrame(1) assert repr(f).endswith("promised_stream_id=0, data=None") f.promised_stream_id = 4 f.data = b"testdata" assert repr(f).endswith("promised_stream_id=4, data=") def test_push_promise_frame_flags(self): f = PushPromiseFrame(1) flags = f.parse_flags(0xFF) assert flags == set(['END_HEADERS', 'PADDED']) def test_push_promise_frame_serializes_properly(self): f = PushPromiseFrame(1) f.flags = set(['END_HEADERS']) f.promised_stream_id = 4 f.data = b'hello world' s = f.serialize() assert s == ( b'\x00\x00\x0F\x05\x04\x00\x00\x00\x01' + b'\x00\x00\x00\x04' + b'hello world' ) def test_push_promise_frame_parses_properly(self): s = ( b'\x00\x00\x0F\x05\x04\x00\x00\x00\x01' + b'\x00\x00\x00\x04' + b'hello world' ) f = decode_frame(s) assert isinstance(f, PushPromiseFrame) assert f.flags == set(['END_HEADERS']) assert f.promised_stream_id == 4 assert f.data == b'hello world' assert f.body_len == 15 def test_push_promise_frame_with_padding(self): s = ( b'\x00\x00\x17\x05\x0C\x00\x00\x00\x01' + b'\x07\x00\x00\x00\x04' + b'hello world' + b'padding' ) f = decode_frame(s) assert isinstance(f, PushPromiseFrame) assert f.flags == set(['END_HEADERS', 'PADDED']) assert f.promised_stream_id == 4 assert f.data == b'hello world' assert f.body_len == 23 def test_push_promise_frame_with_invalid_padding_fails_to_parse(self): # This frame has a padding length of 6 bytes, but a total length of # only 5. data = b'\x00\x00\x05\x05\x08\x00\x00\x00\x01\x06\x54\x65\x73\x74' with pytest.raises(InvalidPaddingError): decode_frame(data) def test_push_promise_frame_with_no_length_parses(self): # Fixes issue with empty data frames raising InvalidPaddingError. f = PushPromiseFrame(1, 2) f.data = b'' data = f.serialize() new_frame = decode_frame(data) assert new_frame.data == b'' def test_push_promise_frame_invalid(self): data = PushPromiseFrame(1, 0).serialize() with pytest.raises(InvalidDataError): decode_frame(data) data = PushPromiseFrame(1, 3).serialize() with pytest.raises(InvalidDataError): decode_frame(data) def test_short_push_promise_errors(self): s = ( b'\x00\x00\x0F\x05\x04\x00\x00\x00\x01' + b'\x00\x00\x00' # One byte short ) with pytest.raises(InvalidFrameError): decode_frame(s) class TestPingFrame: def test_repr(self): f = PingFrame() assert repr(f).endswith("opaque_data=b''") f.opaque_data = b'hello' assert repr(f).endswith("opaque_data=b'hello'") def test_ping_frame_has_only_one_flag(self): f = PingFrame() flags = f.parse_flags(0xFF) assert flags == set(['ACK']) def test_ping_frame_serializes_properly(self): f = PingFrame() f.parse_flags(0xFF) f.opaque_data = b'\x01\x02' s = f.serialize() assert s == ( b'\x00\x00\x08\x06\x01\x00\x00\x00\x00\x01\x02\x00\x00\x00\x00\x00' b'\x00' ) def test_no_more_than_8_octets(self): f = PingFrame() f.opaque_data = b'\x01\x02\x03\x04\x05\x06\x07\x08\x09' with pytest.raises(InvalidFrameError): f.serialize() def test_ping_frame_parses_properly(self): s = ( b'\x00\x00\x08\x06\x01\x00\x00\x00\x00\x01\x02\x00\x00\x00\x00\x00' b'\x00' ) f = decode_frame(s) assert isinstance(f, PingFrame) assert f.flags == set(['ACK']) assert f.opaque_data == b'\x01\x02\x00\x00\x00\x00\x00\x00' assert f.body_len == 8 def test_ping_frame_never_has_a_stream(self): with pytest.raises(InvalidDataError): PingFrame(1) def test_ping_frame_has_no_more_than_body_length_8(self): f = PingFrame() with pytest.raises(InvalidFrameError): f.parse_body(b'\x01\x02\x03\x04\x05\x06\x07\x08\x09') def test_ping_frame_has_no_less_than_body_length_8(self): f = PingFrame() with pytest.raises(InvalidFrameError): f.parse_body(b'\x01\x02\x03\x04\x05\x06\x07') class TestGoAwayFrame: def test_repr(self): f = GoAwayFrame() assert repr(f).endswith("last_stream_id=0, error_code=0, additional_data=b''") f.last_stream_id = 64 f.error_code = 32 f.additional_data = b'hello' assert repr(f).endswith("last_stream_id=64, error_code=32, additional_data=b'hello'") def test_go_away_has_no_flags(self): f = GoAwayFrame() flags = f.parse_flags(0xFF) assert not flags assert isinstance(flags, Flags) def test_goaway_serializes_properly(self): f = GoAwayFrame() f.last_stream_id = 64 f.error_code = 32 f.additional_data = b'hello' s = f.serialize() assert s == ( b'\x00\x00\x0D\x07\x00\x00\x00\x00\x00' + # Frame header b'\x00\x00\x00\x40' + # Last Stream ID b'\x00\x00\x00\x20' + # Error Code b'hello' # Additional data ) def test_goaway_frame_parses_properly(self): s = ( b'\x00\x00\x0D\x07\x00\x00\x00\x00\x00' + # Frame header b'\x00\x00\x00\x40' + # Last Stream ID b'\x00\x00\x00\x20' + # Error Code b'hello' # Additional data ) f = decode_frame(s) assert isinstance(f, GoAwayFrame) assert f.flags == set() assert f.additional_data == b'hello' assert f.body_len == 13 s = ( b'\x00\x00\x08\x07\x00\x00\x00\x00\x00' + # Frame header b'\x00\x00\x00\x40' + # Last Stream ID b'\x00\x00\x00\x20' + # Error Code b'' # Additional data ) f = decode_frame(s) assert isinstance(f, GoAwayFrame) assert f.flags == set() assert f.additional_data == b'' assert f.body_len == 8 def test_goaway_frame_never_has_a_stream(self): with pytest.raises(InvalidDataError): GoAwayFrame(1) def test_short_goaway_frame_errors(self): s = ( b'\x00\x00\x0D\x07\x00\x00\x00\x00\x00' + # Frame header b'\x00\x00\x00\x40' + # Last Stream ID b'\x00\x00\x00' # short Error Code ) with pytest.raises(InvalidFrameError): decode_frame(s) class TestWindowUpdateFrame: def test_repr(self): f = WindowUpdateFrame(0) assert repr(f).endswith("window_increment=0") f.stream_id = 1 f.window_increment = 512 assert repr(f).endswith("window_increment=512") def test_window_update_has_no_flags(self): f = WindowUpdateFrame(0) flags = f.parse_flags(0xFF) assert not flags assert isinstance(flags, Flags) def test_window_update_serializes_properly(self): f = WindowUpdateFrame(0) f.window_increment = 512 s = f.serialize() assert s == b'\x00\x00\x04\x08\x00\x00\x00\x00\x00\x00\x00\x02\x00' def test_windowupdate_frame_parses_properly(self): s = b'\x00\x00\x04\x08\x00\x00\x00\x00\x00\x00\x00\x02\x00' f = decode_frame(s) assert isinstance(f, WindowUpdateFrame) assert f.flags == set() assert f.window_increment == 512 assert f.body_len == 4 def test_short_windowupdate_frame_errors(self): s = b'\x00\x00\x04\x08\x00\x00\x00\x00\x00\x00\x00\x02' # -1 byte with pytest.raises(InvalidFrameError): decode_frame(s) s = b'\x00\x00\x05\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02' with pytest.raises(InvalidFrameError): decode_frame(s) with pytest.raises(InvalidDataError): decode_frame(WindowUpdateFrame(0).serialize()) with pytest.raises(InvalidDataError): decode_frame(WindowUpdateFrame(2**31).serialize()) class TestHeadersFrame: def test_repr(self): f = HeadersFrame(1) assert repr(f).endswith("exclusive=False, depends_on=0, stream_weight=0, data=None") f.data = b'hello' f.exclusive = True f.depends_on = 42 f.stream_weight = 64 assert repr(f).endswith("exclusive=True, depends_on=42, stream_weight=64, data=") def test_headers_frame_flags(self): f = HeadersFrame(1) flags = f.parse_flags(0xFF) assert flags == set(['END_STREAM', 'END_HEADERS', 'PADDED', 'PRIORITY']) def test_headers_frame_serializes_properly(self): f = HeadersFrame(1) f.flags = set(['END_STREAM', 'END_HEADERS']) f.data = b'hello world' s = f.serialize() assert s == ( b'\x00\x00\x0B\x01\x05\x00\x00\x00\x01' + b'hello world' ) def test_headers_frame_parses_properly(self): s = ( b'\x00\x00\x0B\x01\x05\x00\x00\x00\x01' + b'hello world' ) f = decode_frame(s) assert isinstance(f, HeadersFrame) assert f.flags == set(['END_STREAM', 'END_HEADERS']) assert f.data == b'hello world' assert f.body_len == 11 def test_headers_frame_with_priority_parses_properly(self): # This test also tests that we can receive a HEADERS frame with no # actual headers on it. This is technically possible. s = ( b'\x00\x00\x05\x01\x20\x00\x00\x00\x01' + b'\x80\x00\x00\x04\x40' ) f = decode_frame(s) assert isinstance(f, HeadersFrame) assert f.flags == set(['PRIORITY']) assert f.data == b'' assert f.depends_on == 4 assert f.stream_weight == 64 assert f.exclusive is True assert f.body_len == 5 def test_headers_frame_with_priority_serializes_properly(self): # This test also tests that we can receive a HEADERS frame with no # actual headers on it. This is technically possible. s = ( b'\x00\x00\x05\x01\x20\x00\x00\x00\x01' + b'\x80\x00\x00\x04\x40' ) f = HeadersFrame(1) f.flags = set(['PRIORITY']) f.data = b'' f.depends_on = 4 f.stream_weight = 64 f.exclusive = True assert f.serialize() == s def test_headers_frame_with_invalid_padding_fails_to_parse(self): # This frame has a padding length of 6 bytes, but a total length of # only 5. data = b'\x00\x00\x05\x01\x08\x00\x00\x00\x01\x06\x54\x65\x73\x74' with pytest.raises(InvalidPaddingError): decode_frame(data) def test_headers_frame_with_no_length_parses(self): # Fixes issue with empty data frames raising InvalidPaddingError. f = HeadersFrame(1) f.data = b'' data = f.serialize() new_frame = decode_frame(data) assert new_frame.data == b'' class TestContinuationFrame: def test_repr(self): f = ContinuationFrame(1) assert repr(f).endswith("data=None") f.data = b'hello' assert repr(f).endswith("data=") def test_continuation_frame_flags(self): f = ContinuationFrame(1) flags = f.parse_flags(0xFF) assert flags == set(['END_HEADERS']) def test_continuation_frame_serializes(self): f = ContinuationFrame(1) f.parse_flags(0x04) f.data = b'hello world' s = f.serialize() assert s == ( b'\x00\x00\x0B\x09\x04\x00\x00\x00\x01' + b'hello world' ) def test_continuation_frame_parses_properly(self): s = b'\x00\x00\x0B\x09\x04\x00\x00\x00\x01hello world' f = decode_frame(s) assert isinstance(f, ContinuationFrame) assert f.flags == set(['END_HEADERS']) assert f.data == b'hello world' assert f.body_len == 11 class TestAltSvcFrame: payload_with_origin = ( b'\x00\x00\x31' # Length b'\x0A' # Type b'\x00' # Flags b'\x00\x00\x00\x00' # Stream ID b'\x00\x0B' # Origin len b'example.com' # Origin b'h2="alt.example.com:8000", h2=":443"' # Field Value ) payload_without_origin = ( b'\x00\x00\x13' # Length b'\x0A' # Type b'\x00' # Flags b'\x00\x00\x00\x01' # Stream ID b'\x00\x00' # Origin len b'' # Origin b'h2=":8000"; ma=60' # Field Value ) payload_with_origin_and_stream = ( b'\x00\x00\x36' # Length b'\x0A' # Type b'\x00' # Flags b'\x00\x00\x00\x01' # Stream ID b'\x00\x0B' # Origin len b'example.com' # Origin b'Alt-Svc: h2=":443"; ma=2592000; persist=1' # Field Value ) def test_repr(self): f = AltSvcFrame(0) assert repr(f).endswith("origin=b'', field=b''") f.field = b'h2="alt.example.com:8000", h2=":443"' assert repr(f).endswith("origin=b'', field=b'h2=\"alt.example.com:8000\", h2=\":443\"'") f.origin = b'example.com' assert repr(f).endswith("origin=b'example.com', field=b'h2=\"alt.example.com:8000\", h2=\":443\"'") def test_altsvc_frame_flags(self): f = AltSvcFrame(0) flags = f.parse_flags(0xFF) assert flags == set() def test_altsvc_frame_with_origin_serializes_properly(self): f = AltSvcFrame(0) f.origin = b'example.com' f.field = b'h2="alt.example.com:8000", h2=":443"' s = f.serialize() assert s == self.payload_with_origin def test_altsvc_frame_with_origin_parses_properly(self): f = decode_frame(self.payload_with_origin) assert isinstance(f, AltSvcFrame) assert f.origin == b'example.com' assert f.field == b'h2="alt.example.com:8000", h2=":443"' assert f.body_len == 49 assert f.stream_id == 0 def test_altsvc_frame_without_origin_serializes_properly(self): f = AltSvcFrame(1, origin=b'', field=b'h2=":8000"; ma=60') s = f.serialize() assert s == self.payload_without_origin def test_altsvc_frame_without_origin_parses_properly(self): f = decode_frame(self.payload_without_origin) assert isinstance(f, AltSvcFrame) assert f.origin == b'' assert f.field == b'h2=":8000"; ma=60' assert f.body_len == 19 assert f.stream_id == 1 def test_altsvc_frame_with_origin_and_stream_serializes_properly(self): # This frame is not valid, but we allow it to be serialized anyway. f = AltSvcFrame(1) f.origin = b'example.com' f.field = b'Alt-Svc: h2=":443"; ma=2592000; persist=1' assert f.serialize() == self.payload_with_origin_and_stream def test_short_altsvc_frame_errors(self): with pytest.raises(InvalidFrameError): decode_frame(self.payload_with_origin[:12]) with pytest.raises(InvalidFrameError): decode_frame(self.payload_with_origin[:10]) def test_altsvc_with_unicode_origin_fails(self): with pytest.raises(InvalidDataError): AltSvcFrame( stream_id=0, origin=u'hello', field=b'h2=":8000"; ma=60' ) def test_altsvc_with_unicode_field_fails(self): with pytest.raises(InvalidDataError): AltSvcFrame( stream_id=0, origin=b'hello', field=u'h2=":8000"; ma=60' ) class TestExtensionFrame: def test_repr(self): f = ExtensionFrame(0xFF, 1, 42, b'hello') assert repr(f).endswith("type=255, flag_byte=42, body=")