pax_global_header00006660000000000000000000000064145541512570014523gustar00rootroot0000000000000052 comment=2efd28ef5dcd8b7ad44a41777ce640debbbf9c39 pluggy-1.4.0/000077500000000000000000000000001455415125700130345ustar00rootroot00000000000000pluggy-1.4.0/.coveragerc000066400000000000000000000010331455415125700151520ustar00rootroot00000000000000[run] include = pluggy/* testing/* */lib/python*/site-packages/pluggy/* */pypy*/site-packages/pluggy/* *\Lib\site-packages\pluggy\* branch = 1 [paths] source = pluggy/ */lib/python*/site-packages/pluggy/ */pypy*/site-packages/pluggy/ *\Lib\site-packages\pluggy\ [report] exclude_lines = # Have to re-enable the standard pragma pragma: no cover if TYPE_CHECKING: if False: if __name__ == .__main__.: raise NotImplementedError # Ignore coverage on lines solely with `...` ^\s*\.\.\.\s*$ pluggy-1.4.0/.github/000077500000000000000000000000001455415125700143745ustar00rootroot00000000000000pluggy-1.4.0/.github/workflows/000077500000000000000000000000001455415125700164315ustar00rootroot00000000000000pluggy-1.4.0/.github/workflows/main.yml000066400000000000000000000070511455415125700201030ustar00rootroot00000000000000name: main on: push: branches: - main tags: - "*" pull_request: branches: - main jobs: build: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: name: [ "windows-py38", "windows-py311", "windows-pypy3", "ubuntu-py38-pytestmain", "ubuntu-py38", "ubuntu-py39", "ubuntu-py310", "ubuntu-py311", "ubuntu-py312", "ubuntu-pypy3", "ubuntu-benchmark", ] include: - name: "windows-py38" python: "3.8" os: windows-latest tox_env: "py38" - name: "windows-py311" python: "3.10" os: windows-latest tox_env: "py311" - name: "windows-pypy3" python: "pypy3.9" os: windows-latest tox_env: "pypy3" - name: "ubuntu-py38" python: "3.8" os: ubuntu-latest tox_env: "py38" use_coverage: true - name: "ubuntu-py38-pytestmain" python: "3.8" os: ubuntu-latest tox_env: "py38-pytestmain" use_coverage: true - name: "ubuntu-py39" python: "3.9" os: ubuntu-latest tox_env: "py39" use_coverage: true - name: "ubuntu-py310" python: "3.10" os: ubuntu-latest tox_env: "py310" - name: "ubuntu-py311" python: "3.11" os: ubuntu-latest tox_env: "py311" use_coverage: true - name: "ubuntu-py312" python: "3.12-dev" os: ubuntu-latest tox_env: "py312" use_coverage: true - name: "ubuntu-pypy3" python: "pypy3.9" os: ubuntu-latest tox_env: "pypy3" use_coverage: true - name: "ubuntu-benchmark" python: "3.8" os: ubuntu-latest tox_env: "benchmark" steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - name: Set up Python ${{ matrix.python }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python }} - name: Install dependencies run: | python -m pip install --upgrade pip setuptools python -m pip install tox coverage - name: Test without coverage if: "! matrix.use_coverage" run: "tox -e ${{ matrix.tox_env }}" - name: Test with coverage if: "matrix.use_coverage" run: "tox -e ${{ matrix.tox_env }}-coverage" - name: Upload coverage if: matrix.use_coverage && github.repository == 'pytest-dev/pluggy' env: CODECOV_NAME: ${{ matrix.name }} run: bash scripts/upload-coverage.sh -F GHA,${{ runner.os }} deploy: if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags') && github.repository == 'pytest-dev/pluggy' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - uses: actions/setup-python@v4 with: python-version: "3.11" - name: Install dependencies run: | python -m pip install --upgrade pip pip install --upgrade build - name: Build package run: python -m build --sdist --wheel --outdir dist/ - name: Publish package uses: pypa/gh-action-pypi-publish@v1.8.6 with: user: __token__ password: ${{ secrets.pypi_token }} pluggy-1.4.0/.gitignore000066400000000000000000000015641455415125700150320ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache .mypy_cache/ nosetests.xml coverage.xml *,cover # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ docs/_changelog_towncrier_draft.rst # PyBuilder target/ *.swp # generated by setuptools_scm src/pluggy/_version.py # generated by pip pip-wheel-metadata/ # pytest-benchmark .benchmarks/ pluggy-1.4.0/.pre-commit-config.yaml000066400000000000000000000031011455415125700173100ustar00rootroot00000000000000repos: - repo: https://github.com/PyCQA/autoflake rev: v2.2.1 hooks: - id: autoflake name: autoflake args: ["--in-place", "--remove-unused-variables", "--remove-all-unused-imports"] language: python files: \.py$ - repo: https://github.com/asottile/reorder-python-imports rev: v3.12.0 hooks: - id: reorder-python-imports args: ['--application-directories=.:src', --py38-plus] - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.1.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: flake8 additional_dependencies: [flake8-typing-imports] - repo: https://github.com/pre-commit/pygrep-hooks rev: v1.10.0 hooks: - id: rst-backticks - repo: https://github.com/asottile/pyupgrade rev: v3.15.0 hooks: - id: pyupgrade args: [--py38-plus] - repo: https://github.com/psf/black rev: 23.12.1 hooks: - id: black args: [--safe, --quiet] - repo: https://github.com/asottile/blacken-docs rev: 1.16.0 hooks: - id: blacken-docs additional_dependencies: [black==22.10.0] - repo: local hooks: - id: rst name: rst entry: rst-lint --encoding utf-8 files: ^(HOWTORELEASE.rst|README.rst)$ language: python additional_dependencies: [pygments, restructuredtext_lint] - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.8.0 hooks: - id: mypy files: ^(src/|testing/) args: [] additional_dependencies: [pytest] pluggy-1.4.0/.readthedocs.yml000066400000000000000000000003351455415125700161230ustar00rootroot00000000000000version: 2 python: install: # Without this, sphinx can't find pluggy's version. - method: pip path: . - requirements: docs/requirements.txt build: os: ubuntu-22.04 tools: python: "3.11" pluggy-1.4.0/CHANGELOG.rst000066400000000000000000000461231455415125700150630ustar00rootroot00000000000000========= Changelog ========= Versions follow `Semantic Versioning `_ (``..``). .. You should *NOT* be adding new change log entries to this file, this file is managed by towncrier. You *may* edit previous change logs to fix problems like typo corrections or such. To add a new change log entry, please see https://pip.pypa.io/en/latest/development/contributing/#news-entries we named the news folder changelog .. only:: changelog_towncrier_draft .. The 'changelog_towncrier_draft' tag is included by our 'tox -e docs', but not on readthedocs. .. include:: _changelog_towncrier_draft.rst .. towncrier release notes start pluggy 1.4.0 (2024-01-24) ========================= Features -------- - `#463 `_: A warning :class:`~pluggy.PluggyTeardownRaisedWarning` is now issued when an old-style hookwrapper raises an exception during teardown. See the warning documentation for more details. - `#471 `_: Add :func:`PluginManager.unblock ` method to unblock a plugin by plugin name. Bug Fixes --------- - `#441 `_: Fix :func:`~pluggy.HookCaller.call_extra()` extra methods getting ordered before everything else in some circumstances. Regressed in pluggy 1.1.0. - `#438 `_: Fix plugins registering other plugins in a hook when the other plugins implement the same hook itself. Regressed in pluggy 1.1.0. pluggy 1.3.0 (2023-08-26) ========================= Deprecations and Removals ------------------------- - `#426 `_: Python 3.7 is no longer supported. Features -------- - `#428 `_: Pluggy now exposes its typings to static type checkers. As part of this, the following changes are made: - Renamed ``_Result`` to ``Result``, and exported as :class:`pluggy.Result`. - Renamed ``_HookRelay`` to ``HookRelay``, and exported as :class:`pluggy.HookRelay`. - Renamed ``_HookCaller`` to ``HookCaller``, and exported as :class:`pluggy.HookCaller`. - Exported ``HookImpl`` as :class:`pluggy.HookImpl`. - Renamed ``_HookImplOpts`` to ``HookimplOpts``, and exported as :class:`pluggy.HookimplOpts`. - Renamed ``_HookSpecOpts`` to ``HookspecOpts``, and exported as :class:`pluggy.HookspecOpts`. - Some fields and classes are marked ``Final`` and ``@final``. - The :ref:`api-reference` is updated to clearly delineate pluggy's public API. Compatibility aliases are put in place for the renamed types. We do not plan to remove the aliases, but we strongly recommend to only import from ``pluggy.*`` to ensure future compatibility. Please note that pluggy is currently unable to provide strong typing for hook calls, e.g. ``pm.hook.my_hook(...)``, nor to statically check that a hook implementation matches the hook specification's type. pluggy 1.2.0 (2023-06-21) ========================= Features -------- - `#405 `_: The new-style hook wrappers, added in the yanked 1.1.0 release, now require an explicit ``wrapper=True`` designation in the ``@hookimpl()`` decorator. pluggy 1.1.0 (YANKED) ===================== .. note:: This release was yanked because unfortunately the implicit new-style hook wrappers broke some downstream projects. See `#403 `__ for more information. This was rectified in the 1.2.0 release. Deprecations and Removals ------------------------- - `#364 `_: Python 3.6 is no longer supported. Features -------- - `#260 `_: Added "new-style" hook wrappers, a simpler but equally powerful alternative to the existing ``hookwrapper=True`` wrappers. New-style wrappers are generator functions, similarly to ``hookwrapper``, but do away with the :class:`result ` object. Instead, the return value is sent directly to the ``yield`` statement, or, if inner calls raised an exception, it is raised from the ``yield``. The wrapper is expected to return a value or raise an exception, which will become the result of the hook call. New-style wrappers are fully interoperable with old-style wrappers. We encourage users to use the new style, however we do not intend to deprecate the old style any time soon. See :ref:`hookwrappers` for the full documentation. - `#364 `_: Python 3.11 and 3.12 are now officially supported. - `#394 `_: Added the :meth:`~pluggy.Result.force_exception` method to ``_Result``. ``force_exception`` allows (old-style) hookwrappers to force an exception or override/adjust an existing exception of a hook invocation, in a properly behaving manner. Using ``force_exception`` is preferred over raising an exception from the hookwrapper, because raising an exception causes other hookwrappers to be skipped. pluggy 1.0.0 (2021-08-25) ========================= Deprecations and Removals ------------------------- - `#116 `_: Remove deprecated ``implprefix`` support. Decorate hook implementations using an instance of HookimplMarker instead. The deprecation was announced in release ``0.7.0``. - `#120 `_: Remove the deprecated ``proc`` argument to ``call_historic``. Use ``result_callback`` instead, which has the same behavior. The deprecation was announced in release ``0.7.0``. - `#265 `_: Remove the ``_Result.result`` property. Use ``_Result.get_result()`` instead. Note that unlike ``result``, ``get_result()`` raises the exception if the hook raised. The deprecation was announced in release ``0.6.0``. - `#267 `_: Remove official support for Python 3.4. - `#272 `_: Dropped support for Python 2. Continue to use pluggy 0.13.x for Python 2 support. - `#308 `_: Remove official support for Python 3.5. - `#313 `_: The internal ``pluggy.callers``, ``pluggy.manager`` and ``pluggy.hooks`` are now explicitly marked private by a ``_`` prefix (e.g. ``pluggy._callers``). Only API exported by the top-level ``pluggy`` module is considered public. - `#59 `_: Remove legacy ``__multicall__`` recursive hook calling system. The deprecation was announced in release ``0.5.0``. Features -------- - `#282 `_: When registering a hookimpl which is declared as ``hookwrapper=True`` but whose function is not a generator function, a :class:`~pluggy.PluginValidationError` exception is now raised. Previously this problem would cause an error only later, when calling the hook. In the unlikely case that you have a hookwrapper that *returns* a generator instead of yielding directly, for example: .. code-block:: python def my_hook_implementation(arg): print("before") yield print("after") @hookimpl(hookwrapper=True) def my_hook(arg): return my_hook_implementation(arg) change it to use ``yield from`` instead: .. code-block:: python @hookimpl(hookwrapper=True) def my_hook(arg): yield from my_hook_implementation(arg) - `#309 `_: Add official support for Python 3.9. - `#251 `_: Add ``specname`` option to ``@hookimpl``. If ``specname`` is provided, it will be used instead of the function name when matching this hook implementation to a hook specification during registration (allowing a plugin to register a hook implementation that was not named the same thing as the corresponding ``@hookspec``). pluggy 0.13.1 (2019-11-21) ========================== Trivial/Internal Changes ------------------------ - `#236 `_: Improved documentation, especially with regard to references. pluggy 0.13.0 (2019-09-10) ========================== Trivial/Internal Changes ------------------------ - `#222 `_: Replace ``importlib_metadata`` backport with ``importlib.metadata`` from the standard library on Python 3.8+. pluggy 0.12.0 (2019-05-27) ========================== Features -------- - `#215 `_: Switch from ``pkg_resources`` to ``importlib-metadata`` for entrypoint detection for improved performance and import time. This time with ``.egg`` support. pluggy 0.11.0 (2019-05-07) ========================== Bug Fixes --------- - `#205 `_: Revert changes made in 0.10.0 release breaking ``.egg`` installs. pluggy 0.10.0 (2019-05-07) ========================== Features -------- - `#199 `_: Switch from ``pkg_resources`` to ``importlib-metadata`` for entrypoint detection for improved performance and import time. pluggy 0.9.0 (2019-02-21) ========================= Features -------- - `#189 `_: ``PluginManager.load_setuptools_entrypoints`` now accepts a ``name`` parameter that when given will load only entry points with that name. ``PluginManager.load_setuptools_entrypoints`` also now returns the number of plugins loaded by the call, as opposed to the number of all plugins loaded by all calls to this method. Bug Fixes --------- - `#187 `_: Fix internal ``varnames`` function for PyPy3. pluggy 0.8.1 (2018-11-09) ========================= Trivial/Internal Changes ------------------------ - `#166 `_: Add ``stacklevel=2`` to implprefix warning so that the reported location of warning is the caller of PluginManager. pluggy 0.8.0 (2018-10-15) ========================= Features -------- - `#177 `_: Add ``get_hookimpls()`` method to hook callers. Trivial/Internal Changes ------------------------ - `#165 `_: Add changelog in long package description and documentation. - `#172 `_: Add a test exemplifying the opt-in nature of spec defined args. - `#57 `_: Encapsulate hook specifications in a type for easier introspection. pluggy 0.7.1 (2018-07-28) ========================= Deprecations and Removals ------------------------- - `#116 `_: Deprecate the ``implprefix`` kwarg to ``PluginManager`` and instead expect users to start using explicit ``HookimplMarker`` everywhere. Features -------- - `#122 `_: Add ``.plugin`` member to ``PluginValidationError`` to access failing plugin during post-mortem. - `#138 `_: Add per implementation warnings support for hookspecs allowing for both deprecation and future warnings of legacy and (future) experimental hooks respectively. Bug Fixes --------- - `#110 `_: Fix a bug where ``_HookCaller.call_historic()`` would call the ``proc`` arg even when the default is ``None`` resulting in a ``TypeError``. - `#160 `_: Fix problem when handling ``VersionConflict`` errors when loading setuptools plugins. Improved Documentation ---------------------- - `#123 `_: Document how exceptions are handled and how the hook call loop terminates immediately on the first error which is then delivered to any surrounding wrappers. - `#136 `_: Docs rework including a much better introduction and comprehensive example set for new users. A big thanks goes out to @obestwalter for the great work! Trivial/Internal Changes ------------------------ - `#117 `_: Break up the main monolithic package modules into separate modules by concern - `#131 `_: Automate ``setuptools`` wheels building and PyPi upload using TravisCI. - `#153 `_: Reorganize tests more appropriately by modules relating to each internal component/feature. This is in an effort to avoid (future) duplication and better separation of concerns in the test set. - `#156 `_: Add ``HookImpl.__repr__()`` for better debugging. - `#66 `_: Start using ``towncrier`` and a custom ``tox`` environment to prepare releases! pluggy 0.7.0 (Unreleased) ========================= * `#160 `_: We discovered a deployment issue so this version was never released to PyPI, only the tag exists. pluggy 0.6.0 (2017-11-24) ========================= - Add CI testing for the features, release, and master branches of ``pytest`` (PR `#79`_). - Document public API for ``_Result`` objects passed to wrappers (PR `#85`_). - Document and test hook LIFO ordering (PR `#85`_). - Turn warnings into errors in test suite (PR `#89`_). - Deprecate ``_Result.result`` (PR `#88`_). - Convert ``_Multicall`` to a simple function distinguishing it from the legacy version (PR `#90`_). - Resolve E741 errors (PR `#96`_). - Test and bug fix for unmarked hook collection (PRs `#97`_ and `#102`_). - Drop support for EOL Python 2.6 and 3.3 (PR `#103`_). - Fix ``inspect`` based arg introspection on py3.6 (PR `#94`_). .. _#79: https://github.com/pytest-dev/pluggy/pull/79 .. _#85: https://github.com/pytest-dev/pluggy/pull/85 .. _#88: https://github.com/pytest-dev/pluggy/pull/88 .. _#89: https://github.com/pytest-dev/pluggy/pull/89 .. _#90: https://github.com/pytest-dev/pluggy/pull/90 .. _#94: https://github.com/pytest-dev/pluggy/pull/94 .. _#96: https://github.com/pytest-dev/pluggy/pull/96 .. _#97: https://github.com/pytest-dev/pluggy/pull/97 .. _#102: https://github.com/pytest-dev/pluggy/pull/102 .. _#103: https://github.com/pytest-dev/pluggy/pull/103 pluggy 0.5.2 (2017-09-06) ========================= - fix bug where ``firstresult`` wrappers were being sent an incorrectly configured ``_Result`` (a list was set instead of a single value). Add tests to check for this as well as ``_Result.force_result()`` behaviour. Thanks to `@tgoodlet`_ for the PR `#72`_. - fix incorrect ``getattr`` of ``DeprecationWarning`` from the ``warnings`` module. Thanks to `@nicoddemus`_ for the PR `#77`_. - hide ``pytest`` tracebacks in certain core routines. Thanks to `@nicoddemus`_ for the PR `#80`_. .. _#72: https://github.com/pytest-dev/pluggy/pull/72 .. _#77: https://github.com/pytest-dev/pluggy/pull/77 .. _#80: https://github.com/pytest-dev/pluggy/pull/80 pluggy 0.5.1 (2017-08-29) ========================= - fix a bug and add tests for case where ``firstresult`` hooks return ``None`` results. Thanks to `@RonnyPfannschmidt`_ and `@tgoodlet`_ for the issue (`#68`_) and PR (`#69`_) respectively. .. _#69: https://github.com/pytest-dev/pluggy/pull/69 .. _#68: https://github.com/pytest-dev/pluggy/issues/68 pluggy 0.5.0 (2017-08-28) ========================= - fix bug where callbacks for historic hooks would not be called for already registered plugins. Thanks `@vodik`_ for the PR and `@hpk42`_ for further fixes. - fix `#17`_ by considering only actual functions for hooks this removes the ability to register arbitrary callable objects which at first glance is a reasonable simplification, thanks `@RonnyPfannschmidt`_ for report and pr. - fix `#19`_: allow registering hookspecs from instances. The PR from `@tgoodlet`_ also modernized the varnames implementation. - resolve `#32`_: split up the test set into multiple modules. Thanks to `@RonnyPfannschmidt`_ for the PR and `@tgoodlet`_ for the initial request. - resolve `#14`_: add full sphinx docs. Thanks to `@tgoodlet`_ for PR `#39`_. - add hook call mismatch warnings. Thanks to `@tgoodlet`_ for the PR `#42`_. - resolve `#44`_: move to new-style classes. Thanks to `@MichalTHEDUDE`_ for PR `#46`_. - add baseline benchmarking/speed tests using ``pytest-benchmark`` in PR `#54`_. Thanks to `@tgoodlet`_. - update the README to showcase the API. Thanks to `@tgoodlet`_ for the issue and PR `#55`_. - deprecate ``__multicall__`` and add a faster call loop implementation. Thanks to `@tgoodlet`_ for PR `#58`_. - raise a comprehensible error when a ``hookimpl`` is called with positional args. Thanks to `@RonnyPfannschmidt`_ for the issue and `@tgoodlet`_ for PR `#60`_. - fix the ``firstresult`` test making it more complete and remove a duplicate of that test. Thanks to `@tgoodlet`_ for PR `#62`_. .. _#62: https://github.com/pytest-dev/pluggy/pull/62 .. _#60: https://github.com/pytest-dev/pluggy/pull/60 .. _#58: https://github.com/pytest-dev/pluggy/pull/58 .. _#55: https://github.com/pytest-dev/pluggy/pull/55 .. _#54: https://github.com/pytest-dev/pluggy/pull/54 .. _#46: https://github.com/pytest-dev/pluggy/pull/46 .. _#44: https://github.com/pytest-dev/pluggy/issues/44 .. _#42: https://github.com/pytest-dev/pluggy/pull/42 .. _#39: https://github.com/pytest-dev/pluggy/pull/39 .. _#32: https://github.com/pytest-dev/pluggy/pull/32 .. _#19: https://github.com/pytest-dev/pluggy/issues/19 .. _#17: https://github.com/pytest-dev/pluggy/issues/17 .. _#14: https://github.com/pytest-dev/pluggy/issues/14 pluggy 0.4.0 (2016-09-25) ========================= - add ``has_plugin(name)`` method to pluginmanager. thanks `@nicoddemus`_. - fix `#11`_: make plugin parsing more resilient against exceptions from ``__getattr__`` functions. Thanks `@nicoddemus`_. - fix issue `#4`_: specific ``HookCallError`` exception for when a hook call provides not enough arguments. - better error message when loading setuptools entrypoints fails due to a ``VersionConflict``. Thanks `@blueyed`_. .. _#11: https://github.com/pytest-dev/pluggy/issues/11 .. _#4: https://github.com/pytest-dev/pluggy/issues/4 pluggy 0.3.1 (2015-09-17) ========================= - avoid using deprecated-in-python3.5 getargspec method. Thanks `@mdboom`_. pluggy 0.3.0 (2015-05-07) ========================= initial release .. contributors .. _@hpk42: https://github.com/hpk42 .. _@tgoodlet: https://github.com/goodboy .. _@MichalTHEDUDE: https://github.com/MichalTHEDUDE .. _@vodik: https://github.com/vodik .. _@RonnyPfannschmidt: https://github.com/RonnyPfannschmidt .. _@blueyed: https://github.com/blueyed .. _@nicoddemus: https://github.com/nicoddemus .. _@mdboom: https://github.com/mdboom pluggy-1.4.0/LICENSE000066400000000000000000000021261455415125700140420ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015 holger krekel (rather uses bitbucket/hpk42) 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. pluggy-1.4.0/MANIFEST.in000066400000000000000000000002041455415125700145660ustar00rootroot00000000000000include CHANGELOG include README.rst include setup.py include tox.ini include LICENSE graft testing recursive-exclude * *.pyc *.pyo pluggy-1.4.0/README.rst000066400000000000000000000054131455415125700145260ustar00rootroot00000000000000==================================================== pluggy - A minimalist production ready plugin system ==================================================== |pypi| |conda-forge| |versions| |github-actions| |gitter| |black| |codecov| This is the core framework used by the `pytest`_, `tox`_, and `devpi`_ projects. Please `read the docs`_ to learn more! A definitive example ==================== .. code-block:: python import pluggy hookspec = pluggy.HookspecMarker("myproject") hookimpl = pluggy.HookimplMarker("myproject") class MySpec: """A hook specification namespace.""" @hookspec def myhook(self, arg1, arg2): """My special little hook that you can customize.""" class Plugin_1: """A hook implementation namespace.""" @hookimpl def myhook(self, arg1, arg2): print("inside Plugin_1.myhook()") return arg1 + arg2 class Plugin_2: """A 2nd hook implementation namespace.""" @hookimpl def myhook(self, arg1, arg2): print("inside Plugin_2.myhook()") return arg1 - arg2 # create a manager and add the spec pm = pluggy.PluginManager("myproject") pm.add_hookspecs(MySpec) # register plugins pm.register(Plugin_1()) pm.register(Plugin_2()) # call our ``myhook`` hook results = pm.hook.myhook(arg1=1, arg2=2) print(results) Running this directly gets us:: $ python docs/examples/toy-example.py inside Plugin_2.myhook() inside Plugin_1.myhook() [-1, 3] .. badges .. |pypi| image:: https://img.shields.io/pypi/v/pluggy.svg :target: https://pypi.org/pypi/pluggy .. |versions| image:: https://img.shields.io/pypi/pyversions/pluggy.svg :target: https://pypi.org/pypi/pluggy .. |github-actions| image:: https://github.com/pytest-dev/pluggy/workflows/main/badge.svg :target: https://github.com/pytest-dev/pluggy/actions .. |conda-forge| image:: https://img.shields.io/conda/vn/conda-forge/pluggy.svg :target: https://anaconda.org/conda-forge/pytest .. |gitter| image:: https://badges.gitter.im/pytest-dev/pluggy.svg :alt: Join the chat at https://gitter.im/pytest-dev/pluggy :target: https://gitter.im/pytest-dev/pluggy?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge .. |black| image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black .. |codecov| image:: https://codecov.io/gh/pytest-dev/pluggy/branch/master/graph/badge.svg :target: https://codecov.io/gh/pytest-dev/pluggy :alt: Code coverage Status .. links .. _pytest: http://pytest.org .. _tox: https://tox.readthedocs.org .. _devpi: http://doc.devpi.net .. _read the docs: https://pluggy.readthedocs.io/en/latest/ pluggy-1.4.0/RELEASING.rst000066400000000000000000000015271455415125700151040ustar00rootroot00000000000000Release Procedure ----------------- #. Dependening on the magnitude of the changes in the release, consider testing some of the large downstream users of pluggy against the upcoming release. You can do so using the scripts in the ``downstream/`` directory. #. From a clean work tree, execute:: tox -e release -- VERSION This will create the branch ready to be pushed. #. Open a PR targeting ``main``. #. All tests must pass and the PR must be approved by at least another maintainer. #. Publish to PyPI by pushing a tag:: git tag X.Y.Z release-X.Y.Z git push git@github.com:pytest-dev/pluggy.git X.Y.Z The tag will trigger a new build, which will deploy to PyPI. #. Make sure it is `available on PyPI `_. #. Merge the PR into ``main``, either manually or using GitHub's web interface. pluggy-1.4.0/changelog/000077500000000000000000000000001455415125700147635ustar00rootroot00000000000000pluggy-1.4.0/changelog/README.rst000066400000000000000000000031761455415125700164610ustar00rootroot00000000000000This directory contains "newsfragments" which are short files that contain a small **ReST**-formatted text that will be added to the next ``CHANGELOG``. The ``CHANGELOG`` will be read by users, so this description should be aimed to pytest users instead of describing internal changes which are only relevant to the developers. Make sure to use full sentences with correct case and punctuation, for example:: Fix issue with non-ascii messages from the ``warnings`` module. Each file should be named like ``..rst``, where ```` is an issue number, and ```` is one of: * ``feature``: new user facing features, like new command-line options and new behavior. * ``bugfix``: fixes a reported bug. * ``doc``: documentation improvement, like rewording an entire session or adding missing docs. * ``removal``: feature deprecation or removal. * ``vendor``: changes in packages vendored in pytest. * ``trivial``: fixing a small typo or internal change that might be noteworthy. So for example: ``123.feature.rst``, ``456.bugfix.rst``. If your PR fixes an issue, use that number here. If there is no issue, then after you submit the PR and get the PR number you can add a changelog using that instead. If you are not sure what issue type to use, don't hesitate to ask in your PR. ``towncrier`` preserves multiple paragraphs and formatting (code blocks, lists, and so on), but for entries other than ``features`` it is usually better to stick to a single paragraph to keep it concise. You can install ``towncrier`` and then run ``towncrier --draft`` if you want to get a preview of how your change will look in the final release notes. pluggy-1.4.0/changelog/_template.rst000066400000000000000000000016531455415125700174740ustar00rootroot00000000000000{% for section in sections %} {% set underline = "-" %} {% if section %} {{section}} {{ underline * section|length }}{% set underline = "~" %} {% endif %} {% if sections[section] %} {% for category, val in definitions.items() if category in sections[section] %} {{ definitions[category]['name'] }} {{ underline * definitions[category]['name']|length }} {% if definitions[category]['showcontent'] %} {% for text, values in sections[section][category]|dictsort(by='value') %} {% set issue_joiner = joiner(', ') %} - {% for value in values|sort %}{{ issue_joiner() }}`{{ value }} `_{% endfor %}: {{ text }} {% endfor %} {% else %} - {{ sections[section][category]['']|sort|join(', ') }} {% endif %} {% if sections[section][category]|length == 0 %} No significant changes. {% else %} {% endif %} {% endfor %} {% else %} No significant changes. {% endif %} {% endfor %} pluggy-1.4.0/codecov.yml000066400000000000000000000001261455415125700152000ustar00rootroot00000000000000coverage: status: project: true patch: true changes: true comment: off pluggy-1.4.0/docs/000077500000000000000000000000001455415125700137645ustar00rootroot00000000000000pluggy-1.4.0/docs/_static/000077500000000000000000000000001455415125700154125ustar00rootroot00000000000000pluggy-1.4.0/docs/_static/img/000077500000000000000000000000001455415125700161665ustar00rootroot00000000000000pluggy-1.4.0/docs/_static/img/plug.png000066400000000000000000000222061455415125700176450ustar00rootroot00000000000000PNG  IHDR sBIT|d IDATxmlkwǠuΩ!A&Ds{PB4A a#'ZE-ĕH"U>$$̓%vqym`&q~A{Yfggvv#Y<\kIi@pBpTf'JH,3\Id^W^[F\U"t4aPs\9px w%9.چݲqB˹y^|ve^{7W$VNMM}c|˺ZZkͨ{ݿ׸B#be}'wݎZlp\ֵ ɲN綆J݂^L8zc:y.y] F\6r?9~/tĺ s(tNͺ߭F n/-!,xjj] H$F\LMMY>䓥u5pe~~CsEbU@3GԺŰC`.say>Gk1r+hԺNjp}EV|v9M)J2N^W;^~7p0H$h9?uڼ}:U}:B/Ф_pr)5}7KSblj]۴ۗeKYl ܆Ïbf~8ݿ JIv@x1BpT!p #.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.l||\ɤtwwK__ LMM+̙3^dѢEH$$ (H:N.ԩS) 8R]]-K.+Wʜ9sL\pႴˎ;$J.(XLdݺu2c \CvZ7]JI̟?_:::t)+@w}222b]vM8Fp CZgF^PvxĄ]6%"222"k׮Ud\МӲ/P!ǩSEm[XL^}UZQqytvvVLhR)4]P#.zwާZyf@YcXH&Z"_6$Ie.Bww.B__.4]`,.Q%SSS244$'N'NʧTdxxX>s/B&''%J ͢({\e̙3r{G}$}}}ryeqWt颼ay77ߒ?tIP.RO_~Y~H\ ݻe߾}ri*Wz{{vȡC8E"o?/K.3l&. ʯ~+yLCpŋ;ٶm\pt9JW|sҥ\ Ȇ Rb0;|^u;cR:ٲe 3Rb'\{L8`T*jyˡQYz.( ]w*Z4*YfI]]̛7OddLW:IsimmG.ıc .CpsJ"innH$b$ۑݡ\WgΜ{W?n 0W466ʊ+dǍՑ\HDQ=aLh\ǥ6ikm3`uؘZBc||\,^Xvmd҄X,WT*՗䤬YsZBiddDx {dppXv!fʑN?{K_ȝw);a"rtttHWW2 Ν3 С]X9\Yɤlٲt흲qFtoVG(8X]]]кuW.ҥ~z9KvPyQ_ڍ!U>,w]]]o><趣P>@on (+;6tb\/~9;w.ozIxUtpuv1 sɣߴHl۶tPzzzd޽%f:.c zJ.\` ({7o17 \G?FFFd%n$aB~i%*;wqO bV\pk Pe||\y;֤=@_|ā9r2@'Oʇ~Xq[^x'꫞&. ɡCL%ɢ&.޽'NSq0T*%3]‘#5q[N>m >O{4O{WbKOJb]4]:q2 2::j >sۜoat:;֛o.BerrFVn4B\gΜ?t HDQn8| tZT5 ?n2HfΜYv;tR+Koe6<_ lm|FhkhhHΟ?o kuKY:~ Z/mM mWɓ'M`M%V15 ӿ~jsWnfteTUdW tm#6]NKKKɷ->矛.BQ^?Jv4k9[@iXB"2\Ν3]F<˗.CDB|… KhmkxQn t1% 4`9SNIgg߿_&&&LP&pႴˎ;\T M!]>#kJ(PvS>}'###AB?00@hJkZYX6S>sN )얳ԩSsN?wPP(wNV|qy@mĕL&7GFe46k *4%To#6 L`:[pi@-e{d@@&Tqʆ):S 0-MDqTI!Dv(E"Xb~3~6o\U.*,8%ُn1S1@19B1&JV#-3e+JI:ڿbDnWTe0*_81,;,p! &i"WRn0Yo׼ a/C**z.F\b*0"2tT\Di!Z62\v. a BBR@59iuw2J#E=2F^N+#߿"U1]G \Ш15 0>:mMP r+H0"bTdE$翹E;w=eP(9]4rhu^ r3 Z>@"Yy-Y3"18]/+=褻Vnf(١ž6rOpA#]Z}@tڴApT!\t' 9,mܰCpb'@Y b"ps@P!@ pr> CpTP!lplY';8TP¡B@ jF\UqeפdTƈ B̜(7]e"w8io-]jjj4\ ~mBN-4@6n--ZצE"3:;|"jkeri|qqYå~mP|Y_E) |R/;ל9s]*W [N:w(si}e5o\!~ X&rtWˮ]/gM(8|ٳg̟??]B(Йpd޽mk7aF$]`ON:%۶m..ṞcLrL6Ƃ+c||\ɤtwwK__ LMM, hP(3\RQG;+dRΝ;g4 FJjjjd֬YRWW'͓&Y&=*%lu64]Z~sΕD"!---\ڨYԏ\8);wv4]:W466ʊ+dǍ>>*PDJh||\isXVX͜1s& PJ/b: ș32o.BɓzFN;I$uW.BW_5]Bxt :duLd'ϦK9qℜ>?Fkmp566.BȑZy,; kt J}}}Fફ.t:|6(7x |c t>쳢-wMp@^i2ORMqr-KЙ~P3DDf͚%3]B\""t *UUUFoKPz| t--Nʢ>R܏+˴ieŦШ/zBTʶtR%@h\{ַqXh̞=t Y3D*$bG?2]‚7]H9 .KъysWU(͠Oż}ejD622B*&DDt ZKK*+ny,XtRcc47KD?@+VH$1]Fw]MqY|yIe=ȍ$ xGLJ<|pUOV,X ?L*J[kiۘɃ{Lf̘a ({7nm/=ˉ zYz2-\P-[fY'r5ט._.6m*Y'TtpM^%O=SA'|-LR7xZtPVV^%wqGIiwn-KDD~ʷme@YXdlX!Ҝ´i巿?Rŷ-T֧Pʷ˦_$$hd.ӦM7]-+K"ztV͛} -݄Wkʒ%KL.? S>D׿|;1] j…/nW. UUUuVM%W[[+/}ijόH555cfx\~r]w͡A"t:mrv{Ksر\wuTRhll[-[$~ˌs\Hkk=zt)@ .Ν+DBZZZYͥ>W իt)FJjjjd֬YRWW'͓nAnF=*%~vwd&''.r\ .tttȖ-[aEpl)1(ȃ>([nenC0*=}Ŭ0˃ye͚5jmxhڴay饗d޼y#Jo#֭3f.B*ӫ?rm.Bvx3l^ӥrFpߖyr!2]rFp044$w}ӧM|rFpJwߕȡٿ5] "U&.](wXx yͷ?6]*rFp3g }M Ap\JLMMА8q\N8)SaellL T*B9# _}v~FQ%3sL%.BCC7]`,455.J~Ё,,Zt Ts`!HHuu2W]]-Dt- e.#pKT2[ʟX,fb1Y "<̙#Lkk̙3t@A\ ؘ˗KR|5|ٳgOE׃>!KMmmtttZP hhh]v2jkke׮]}5!2ϟo sBe d޽6b޽{iA%3":uJm&]]]211aGeɒ%zjx0>>.dROett-QѨ̜9S륩I-Z$D @qT!\U.*@31IDAT PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpT!\U.*@ PBpTf'JH,3\Id^W^[F\U"t:mbPs\9px w%9.چݲqB˹y^|ve^{7W$VNMM}c|˺ZZkͨ{ݿ׸B#be}'wݎZlp\ֵ ɲN綆J݂^L8zc:y.y] F\6r?9~/tĺ s(tNͺ߭F n/-!,xjj] H$F\LMMY>䓥u5pe~~CsEbU@3GԺŰC`.say>Gk1r+hԺNjp}EV|v9M)J2N^W;^~7p0H$h9?uڼ}:U}:B/Ф_pr)5}7KSblj]۴ۗeKYl ܆Ïbf~8ݿ JIv@x1BpT!p #.*@&f9IENDB`pluggy-1.4.0/docs/api_reference.rst000066400000000000000000000021251455415125700173050ustar00rootroot00000000000000:orphan: .. _`api-reference`: API Reference ============= .. autoclass:: pluggy.PluginManager :members: .. autoclass:: pluggy.PluginValidationError :show-inheritance: :members: .. autodecorator:: pluggy.HookspecMarker .. autodecorator:: pluggy.HookimplMarker .. autoclass:: pluggy.HookRelay() :members: .. data:: :type: HookCaller The caller for the hook with the given name. .. autoclass:: pluggy.HookCaller() :members: :special-members: __call__ .. autoclass:: pluggy.HookCallError() :show-inheritance: :members: .. autoclass:: pluggy.Result() :show-inheritance: :members: .. autoclass:: pluggy.HookImpl() :members: .. autoclass:: pluggy.HookspecOpts() :show-inheritance: :members: .. autoclass:: pluggy.HookimplOpts() :show-inheritance: :members: Warnings -------- Custom warnings generated in some situations such as improper usage or deprecated features. .. autoclass:: pluggy.PluggyWarning() :show-inheritance: .. autoclass:: pluggy.PluggyTeardownRaisedWarning() :show-inheritance: pluggy-1.4.0/docs/changelog.rst000066400000000000000000000000361455415125700164440ustar00rootroot00000000000000.. include:: ../CHANGELOG.rst pluggy-1.4.0/docs/conf.py000066400000000000000000000074151455415125700152720ustar00rootroot00000000000000from importlib import metadata from typing import TYPE_CHECKING if TYPE_CHECKING: import sphinx.application extensions = [ "sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.intersphinx", "sphinx.ext.coverage", "sphinx.ext.viewcode", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] source_suffix = ".rst" # The master toctree document. master_doc = "index" # General information about the project. project = "pluggy" copyright = "2016, Holger Krekel" author = "Holger Krekel" release = metadata.version(project) # The short X.Y version. version = ".".join(release.split(".")[:2]) language = "en" pygments_style = "sphinx" # html_logo = "_static/img/plug.png" html_theme = "alabaster" html_theme_options = { "logo": "img/plug.png", "description": "The pytest plugin system", "github_user": "pytest-dev", "github_repo": "pluggy", "github_button": "true", "github_banner": "true", "github_type": "star", "badge_branch": "main", "page_width": "1080px", "sidebar_width": "300px", "fixed_sidebar": "false", } html_sidebars = { "**": ["about.html", "localtoc.html", "relations.html", "searchbox.html"] } html_static_path = ["_static"] # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, "pluggy", "pluggy Documentation", [author], 1)] autodoc_member_order = "bysource" nitpicky = True nitpick_ignore = { # Don't want to expose this yet (see #428). ("py:class", "pluggy._tracing.TagTracerSub"), # Compat hack, don't want to expose it. ("py:class", "pluggy._manager.DistFacade"), # `types.ModuleType` turns into `module` but then fails to resolve... ("py:class", "module"), # Just a TypeVar. ("py:obj", "pluggy._result.ResultType"), ("py:class", "pluggy._result.ResultType"), } # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "pluggy", "pluggy Documentation", author, "pluggy", "One line description of project.", "Miscellaneous", ) ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { "python": ("https://docs.python.org/3", None), "pytest": ("https://docs.pytest.org/en/latest", None), "setuptools": ("https://setuptools.pypa.io/en/latest", None), "tox": ("https://tox.wiki/en/latest", None), "devpi": ("https://devpi.net/docs/devpi/devpi/stable/+doc/", None), "kedro": ("https://docs.kedro.org/en/latest/", None), } def configure_logging(app: "sphinx.application.Sphinx") -> None: """Configure Sphinx's WarningHandler to handle (expected) missing include.""" import sphinx.util.logging import logging class WarnLogFilter(logging.Filter): def filter(self, record: logging.LogRecord) -> bool: """Ignore warnings about missing include with "only" directive. Ref: https://github.com/sphinx-doc/sphinx/issues/2150.""" if ( record.msg.startswith('Problems with "include" directive path:') and "_changelog_towncrier_draft.rst" in record.msg ): return False return True logger = logging.getLogger(sphinx.util.logging.NAMESPACE) warn_handler = [x for x in logger.handlers if x.level == logging.WARNING] assert len(warn_handler) == 1, warn_handler warn_handler[0].filters.insert(0, WarnLogFilter()) def setup(app: "sphinx.application.Sphinx") -> None: configure_logging(app) pluggy-1.4.0/docs/examples/000077500000000000000000000000001455415125700156025ustar00rootroot00000000000000pluggy-1.4.0/docs/examples/eggsample-spam/000077500000000000000000000000001455415125700205045ustar00rootroot00000000000000pluggy-1.4.0/docs/examples/eggsample-spam/eggsample_spam.py000066400000000000000000000011501455415125700240370ustar00rootroot00000000000000import eggsample @eggsample.hookimpl def eggsample_add_ingredients(ingredients): """Here the caller expects us to return a list.""" if "egg" in ingredients: spam = ["lovely spam", "wonderous spam"] else: spam = ["splendiferous spam", "magnificent spam"] return spam @eggsample.hookimpl def eggsample_prep_condiments(condiments): """Here the caller passes a mutable object, so we mess with it directly.""" try: del condiments["steak sauce"] except KeyError: pass condiments["spam sauce"] = 42 return "Now this is what I call a condiments tray!" pluggy-1.4.0/docs/examples/eggsample-spam/setup.py000066400000000000000000000003021455415125700222110ustar00rootroot00000000000000from setuptools import setup setup( name="eggsample-spam", install_requires="eggsample", entry_points={"eggsample": ["spam = eggsample_spam"]}, py_modules=["eggsample_spam"], ) pluggy-1.4.0/docs/examples/eggsample/000077500000000000000000000000001455415125700175465ustar00rootroot00000000000000pluggy-1.4.0/docs/examples/eggsample/eggsample/000077500000000000000000000000001455415125700215125ustar00rootroot00000000000000pluggy-1.4.0/docs/examples/eggsample/eggsample/__init__.py000066400000000000000000000002131455415125700236170ustar00rootroot00000000000000import pluggy hookimpl = pluggy.HookimplMarker("eggsample") """Marker to be imported and used in plugins (and for own implementations)""" pluggy-1.4.0/docs/examples/eggsample/eggsample/hookspecs.py000066400000000000000000000010001455415125700240510ustar00rootroot00000000000000import pluggy hookspec = pluggy.HookspecMarker("eggsample") @hookspec def eggsample_add_ingredients(ingredients: tuple): """Have a look at the ingredients and offer your own. :param ingredients: the ingredients, don't touch them! :return: a list of ingredients """ @hookspec def eggsample_prep_condiments(condiments: dict): """Reorganize the condiments tray to your heart's content. :param condiments: some sauces and stuff :return: a witty comment about your activity """ pluggy-1.4.0/docs/examples/eggsample/eggsample/host.py000066400000000000000000000030521455415125700230410ustar00rootroot00000000000000import itertools import random from eggsample import hookspecs from eggsample import lib import pluggy condiments_tray = {"pickled walnuts": 13, "steak sauce": 4, "mushy peas": 2} def main(): pm = get_plugin_manager() cook = EggsellentCook(pm.hook) cook.add_ingredients() cook.prepare_the_food() cook.serve_the_food() def get_plugin_manager(): pm = pluggy.PluginManager("eggsample") pm.add_hookspecs(hookspecs) pm.load_setuptools_entrypoints("eggsample") pm.register(lib) return pm class EggsellentCook: FAVORITE_INGREDIENTS = ("egg", "egg", "egg") def __init__(self, hook): self.hook = hook self.ingredients = None def add_ingredients(self): results = self.hook.eggsample_add_ingredients( ingredients=self.FAVORITE_INGREDIENTS ) my_ingredients = list(self.FAVORITE_INGREDIENTS) # Each hook returns a list - so we chain this list of lists other_ingredients = list(itertools.chain(*results)) self.ingredients = my_ingredients + other_ingredients def prepare_the_food(self): random.shuffle(self.ingredients) def serve_the_food(self): condiment_comments = self.hook.eggsample_prep_condiments( condiments=condiments_tray ) print(f"Your food. Enjoy some {', '.join(self.ingredients)}") print(f"Some condiments? We have {', '.join(condiments_tray.keys())}") if any(condiment_comments): print("\n".join(condiment_comments)) if __name__ == "__main__": main() pluggy-1.4.0/docs/examples/eggsample/eggsample/lib.py000066400000000000000000000005171455415125700226350ustar00rootroot00000000000000import eggsample @eggsample.hookimpl def eggsample_add_ingredients(): spices = ["salt", "pepper"] you_can_never_have_enough_eggs = ["egg", "egg"] ingredients = spices + you_can_never_have_enough_eggs return ingredients @eggsample.hookimpl def eggsample_prep_condiments(condiments): condiments["mint sauce"] = 1 pluggy-1.4.0/docs/examples/eggsample/setup.py000066400000000000000000000003621455415125700212610ustar00rootroot00000000000000from setuptools import find_packages from setuptools import setup setup( name="eggsample", install_requires="pluggy>=0.3,<1.0", entry_points={"console_scripts": ["eggsample=eggsample.host:main"]}, packages=find_packages(), ) pluggy-1.4.0/docs/examples/toy-example.py000066400000000000000000000015671455415125700204310ustar00rootroot00000000000000import pluggy hookspec = pluggy.HookspecMarker("myproject") hookimpl = pluggy.HookimplMarker("myproject") class MySpec: """A hook specification namespace.""" @hookspec def myhook(self, arg1, arg2): """My special little hook that you can customize.""" class Plugin_1: """A hook implementation namespace.""" @hookimpl def myhook(self, arg1, arg2): print("inside Plugin_1.myhook()") return arg1 + arg2 class Plugin_2: """A 2nd hook implementation namespace.""" @hookimpl def myhook(self, arg1, arg2): print("inside Plugin_2.myhook()") return arg1 - arg2 # create a manager and add the spec pm = pluggy.PluginManager("myproject") pm.add_hookspecs(MySpec) # register plugins pm.register(Plugin_1()) pm.register(Plugin_2()) # call our `myhook` hook results = pm.hook.myhook(arg1=1, arg2=2) print(results) pluggy-1.4.0/docs/index.rst000066400000000000000000001000511455415125700156220ustar00rootroot00000000000000``pluggy`` ========== **The pytest plugin system** What is it? *********** ``pluggy`` is the crystallized core of :ref:`plugin management and hook calling ` for :std:doc:`pytest `. It enables `500+ plugins`_ to extend and customize ``pytest``'s default behaviour. Even ``pytest`` itself is composed as a set of ``pluggy`` plugins which are invoked in sequence according to a well defined set of protocols. It gives users the ability to extend or modify the behaviour of a ``host program`` by installing a ``plugin`` for that program. The plugin code will run as part of normal program execution, changing or enhancing certain aspects of it. In essence, ``pluggy`` enables function `hooking`_ so you can build "pluggable" systems. Why is it useful? ***************** There are some established mechanisms for modifying the behavior of other programs/libraries in Python like `method overriding `_ (e.g. Jinja2) or `monkey patching `_ (e.g. gevent or for :std:doc:`writing tests `). These strategies become problematic though when several parties want to participate in the modification of the same program. Therefore ``pluggy`` does not rely on these mechanisms to enable a more structured approach and avoid unnecessary exposure of state and behaviour. This leads to a more `loosely coupled `_ relationship between ``host`` and ``plugins``. The ``pluggy`` approach puts the burden on the designer of the ``host program`` to think carefully about which objects are really needed in a hook implementation. This gives ``plugin`` creators a clear framework for how to extend the ``host`` via a well defined set of functions and objects to work with. How does it work? ***************** Let us start with a short overview of what is involved: * ``host`` or ``host program``: the program offering extensibility by specifying ``hook functions`` and invoking their implementation(s) as part of program execution * ``plugin``: the program implementing (a subset of) the specified hooks and participating in program execution when the implementations are invoked by the ``host`` * ``pluggy``: connects ``host`` and ``plugins`` by using ... - the hook :ref:`specifications ` defining call signatures provided by the ``host`` (a.k.a ``hookspecs`` - see :ref:`marking_hooks`) - the hook :ref:`implementations ` provided by registered ``plugins`` (a.k.a ``hookimpl`` - see `callbacks`_) - the hook :ref:`caller ` - a call loop triggered at appropriate program positions in the ``host`` invoking the implementations and collecting the results ... where for each registered hook *specification*, a hook *call* will invoke up to ``N`` registered hook *implementations*. * ``user``: the person who installed the ``host program`` and wants to extend its functionality with ``plugins``. In the simplest case they install the ``plugin`` in the same environment as the ``host`` and the magic will happen when the ``host program`` is run the next time. Depending on the ``plugin``, there might be other things they need to do. For example, they might have to call the host with an additional commandline parameter to the host that the ``plugin`` added. A toy example ------------- Let us demonstrate the core functionality in one module and show how you can start experimenting with pluggy functionality. .. literalinclude:: examples/toy-example.py Running this directly gets us:: $ python docs/examples/toy-example.py inside Plugin_2.myhook() inside Plugin_1.myhook() [-1, 3] A complete example ------------------ Now let us demonstrate how this plays together in a vaguely real world scenario. Let's assume our ``host program`` is called **eggsample** where some eggs will be prepared and served with a tray containing condiments. As everybody knows: the more cooks are involved the better the food, so let us make the process pluggable and write a plugin that improves the meal with some spam and replaces the steak sauce (nobody likes that anyway) with spam sauce (it's a thing - trust me). .. note:: **naming markers**: ``HookSpecMarker`` and ``HookImplMarker`` must be initialized with the name of the ``host`` project (the ``name`` parameter in ``setup()``) - so **eggsample** in our case. **naming plugin projects**: they should be named in the form of ``-`` (e.g. ``pytest-xdist``), therefore we call our plugin *eggsample-spam*. The host ^^^^^^^^ ``eggsample/eggsample/__init__.py`` .. literalinclude:: examples/eggsample/eggsample/__init__.py ``eggsample/eggsample/hookspecs.py`` .. literalinclude:: examples/eggsample/eggsample/hookspecs.py ``eggsample/eggsample/lib.py`` .. literalinclude:: examples/eggsample/eggsample/lib.py ``eggsample/eggsample/host.py`` .. literalinclude:: examples/eggsample/eggsample/host.py ``eggsample/setup.py`` .. literalinclude:: examples/eggsample/setup.py Let's get cooking - we install the host and see what a program run looks like:: $ pip install --editable pluggy/docs/examples/eggsample $ eggsample Your food. Enjoy some egg, egg, salt, egg, egg, pepper, egg Some condiments? We have pickled walnuts, steak sauce, mushy peas, mint sauce The plugin ^^^^^^^^^^ ``eggsample-spam/eggsample_spam.py`` .. literalinclude:: examples/eggsample-spam/eggsample_spam.py ``eggsample-spam/setup.py`` .. literalinclude:: examples/eggsample-spam/setup.py Let's get cooking with more cooks - we install the plugin and and see what we get:: $ pip install --editable pluggy/docs/examples/eggsample-spam $ eggsample Your food. Enjoy some egg, lovely spam, salt, egg, egg, egg, wonderous spam, egg, pepper Some condiments? We have pickled walnuts, mushy peas, mint sauce, spam sauce Now this is what I call a condiments tray! More real world examples ------------------------ To see how ``pluggy`` is used in the real world, have a look at these projects documentation and source code: * :ref:`pytest ` * :std:doc:`tox ` * :std:doc:`devpi ` * :std:doc:`kedro ` For more details and advanced usage please read on. .. _define: Define and collect hooks ************************ A *plugin* is a :ref:`namespace ` type (currently one of a ``class`` or module) which defines a set of *hook* functions. As mentioned in :ref:`manage`, all *plugins* which specify *hooks* are managed by an instance of a :py:class:`pluggy.PluginManager` which defines the primary ``pluggy`` API. In order for a :py:class:`~pluggy.PluginManager` to detect functions in a namespace intended to be *hooks*, they must be decorated using special ``pluggy`` *marks*. .. _marking_hooks: Marking hooks ------------- The :py:class:`~pluggy.HookspecMarker` and :py:class:`~pluggy.HookimplMarker` decorators are used to *mark* functions for detection by a :py:class:`~pluggy.PluginManager`: .. code-block:: python from pluggy import HookspecMarker, HookimplMarker hookspec = HookspecMarker("project_name") hookimpl = HookimplMarker("project_name") Each decorator type takes a single ``project_name`` string as its lone argument the value of which is used to mark hooks for detection by a similarly configured :py:class:`~pluggy.PluginManager` instance. That is, a *mark* type called with ``project_name`` returns an object which can be used to decorate functions which will then be detected by a :py:class:`~pluggy.PluginManager` which was instantiated with the same ``project_name`` value. Furthermore, each *hookimpl* or *hookspec* decorator can configure the underlying call-time behavior of each *hook* object by providing special *options* passed as keyword arguments. .. note:: The following sections correspond to similar documentation in ``pytest`` for :ref:`pytest:writinghooks` and can be used as a supplementary resource. .. _impls: Implementations --------------- A hook *implementation* (*hookimpl*) is just a (callback) function which has been appropriately marked. *hookimpls* are loaded from a plugin using the :py:meth:`~pluggy.PluginManager.register()` method: *hookimpls* must be hashable. .. code-block:: python import sys from pluggy import PluginManager, HookimplMarker hookimpl = HookimplMarker("myproject") @hookimpl def setup_project(config, args): """This hook is used to process the initial config and possibly input arguments. """ if args: config.process_args(args) return config pm = PluginManager("myproject") # load all hookimpls from the local module's namespace plugin_name = pm.register(sys.modules[__name__]) .. _optionalhook: Optional validation ^^^^^^^^^^^^^^^^^^^ Normally each *hookimpl* should be validated against a corresponding hook :ref:`specification `. If you want to make an exception then the *hookimpl* should be marked with the ``"optionalhook"`` option: .. code-block:: python @hookimpl(optionalhook=True) def setup_project(config, args): """This hook is used to process the initial config and possibly input arguments. """ if args: config.process_args(args) return config .. _specname: Hookspec name matching ^^^^^^^^^^^^^^^^^^^^^^ During plugin :ref:`registration `, pluggy attempts to match each hook implementation declared by the *plugin* to a hook :ref:`specification ` in the *host* program with the **same name** as the function being decorated by ``@hookimpl`` (e.g. ``setup_project`` in the example above). Note: there is *no* strict requirement that each *hookimpl* has a corresponding *hookspec* (see :ref:`enforcing spec validation `). *new in version 1.0.0:* To override the default behavior, a *hookimpl* may also be matched to a *hookspec* in the *host* program with a non-matching function name by using the ``specname`` option. Continuing the example above, the *hookimpl* function does not need to be named ``setup_project``, but if the argument ``specname="setup_project"`` is provided to the ``hookimpl`` decorator, it will be matched and checked against the ``setup_project`` hookspec: .. code-block:: python @hookimpl(specname="setup_project") def any_plugin_function(config, args): """This hook is used to process the initial config and possibly input arguments. """ if args: config.process_args(args) return config .. _callorder: Call time order ^^^^^^^^^^^^^^^ By default hooks are :ref:`called ` in LIFO registered order, however, a *hookimpl* can influence its call-time invocation position using special attributes. If marked with a ``"tryfirst"`` or ``"trylast"`` option it will be executed *first* or *last* respectively in the hook call loop: .. code-block:: python import sys from pluggy import PluginManager, HookimplMarker hookimpl = HookimplMarker("myproject") @hookimpl(trylast=True) def setup_project(config, args): """Default implementation.""" if args: config.process_args(args) return config class SomeOtherPlugin: """Some other plugin defining the same hook.""" @hookimpl(tryfirst=True) def setup_project(self, config, args): """Report what args were passed before calling downstream hooks. """ if args: print("Got args: {}".format(args)) return config pm = PluginManager("myproject") # load from the local module's namespace pm.register(sys.modules[__name__]) # load a plugin defined on a class pm.register(SomeOtherPlugin()) For another example see the :ref:`pytest:plugin-hookorder` section of the ``pytest`` docs. .. note:: ``tryfirst`` and ``trylast`` hooks are still invoked in LIFO order within each category. .. _hookwrappers: Wrappers ^^^^^^^^ .. note:: This section describes "new-style hook wrappers", which were added in Pluggy 1.1. For earlier versions, see the "old-style hook wrappers" section below. New-style hooks wrappers are declared with ``wrapper=True``, while old-style hook wrappers are declared with ``hookwrapper=True``. The two styles are fully interoperable between plugins using different styles. However within the same plugin we recommend using only one style, for consistency. A *hookimpl* can be marked with the ``"wrapper"`` option, which indicates that the function will be called to *wrap* (or surround) all other normal *hookimpl* calls. A *hook wrapper* can thus execute some code ahead and after the execution of all corresponding non-wrappper *hookimpls*. Much in the same way as a :py:func:`@contextlib.contextmanager `, *hook wrappers* must be implemented as generator function with a single ``yield`` in its body: .. code-block:: python @hookimpl(wrapper=True) def setup_project(config, args): """Wrap calls to ``setup_project()`` implementations which should return json encoded config options. """ # get initial default config defaults = config.tojson() if config.debug: print("Pre-hook config is {}".format(config.tojson())) # all corresponding hookimpls are invoked here result = yield for item in result: print("JSON config override is {}".format(item)) if config.debug: print("Post-hook config is {}".format(config.tojson())) if config.use_defaults: return defaults else: return result The generator is :py:meth:`sent ` the return value of the hook thus far, or, if the previous calls raised an exception, it is :py:meth:`thrown ` the exception. The function should do one of two things: - Return a value, which can be the same value as received from the ``yield``, or something else entirely. - Raise an exception. The return value or exception propagate to further hook wrappers, and finally to the hook caller. Also see the :ref:`pytest:hookwrapper` section in the ``pytest`` docs. .. _old_style_hookwrappers: Old-style wrappers ^^^^^^^^^^^^^^^^^^ .. note:: Prefer to use new-style hook wrappers, unless you need to support Pluggy versions before 1.1. A *hookimpl* can be marked with the ``"hookwrapper"`` option, which indicates that the function will be called to *wrap* (or surround) all other normal *hookimpl* calls. A *hookwrapper* can thus execute some code ahead and after the execution of all corresponding non-wrappper *hookimpls*. *hookwrappers* must be implemented as generator function with a single ``yield`` in its body: .. code-block:: python @hookimpl(hookwrapper=True) def setup_project(config, args): """Wrap calls to ``setup_project()`` implementations which should return json encoded config options. """ # get initial default config defaults = config.tojson() if config.debug: print("Pre-hook config is {}".format(config.tojson())) # all corresponding hookimpls are invoked here outcome = yield try: result = outcome.get_result() except BaseException as e: outcome.force_exception(e) return for item in result: print("JSON config override is {}".format(item)) if config.debug: print("Post-hook config is {}".format(config.tojson())) if config.use_defaults: outcome.force_result(defaults) The generator is :py:meth:`sent ` a :py:class:`pluggy.Result` object which can be assigned in the ``yield`` expression and used to inspect the final result(s) or exceptions returned back to the caller using the :py:meth:`~pluggy.Result.get_result` method, override the result using the :py:meth:`~pluggy.Result.force_result`, or override the exception using the :py:meth:`~pluggy.Result.force_exception` method. .. note:: Old-style hook wrappers can **not** return results; they can only modify them using the :py:meth:`~pluggy.Result.force_result` API. Old-style Hook wrappers should **not** raise exceptions; this will cause further hookwrappers to be skipped. They should use :py:meth:`~pluggy.Result.force_exception` to adjust the exception. .. _specs: Specifications -------------- A hook *specification* (*hookspec*) is a definition used to validate each *hookimpl* ensuring that an extension writer has correctly defined their callback function *implementation* . *hookspecs* are defined using similarly marked functions however only the function *signature* (its name and names of all its arguments) is analyzed and stored. As such, often you will see a *hookspec* defined with only a docstring in its body. *hookspecs* are loaded using the :py:meth:`~pluggy.PluginManager.add_hookspecs()` method and normally should be added before registering corresponding *hookimpls*: .. code-block:: python import sys from pluggy import PluginManager, HookspecMarker hookspec = HookspecMarker("myproject") @hookspec def setup_project(config, args): """This hook is used to process the initial config and input arguments. """ pm = PluginManager("myproject") # load from the local module's namespace pm.add_hookspecs(sys.modules[__name__]) Registering a *hookimpl* which does not meet the constraints of its corresponding *hookspec* will result in an error. A *hookspec* can also be added **after** some *hookimpls* have been registered however this is not normally recommended as it results in delayed hook validation. .. note:: The term *hookspec* can sometimes refer to the plugin-namespace which defines ``hookspec`` decorated functions as in the case of ``pytest``'s `hookspec module`_ .. _enforcing: Enforcing spec validation ^^^^^^^^^^^^^^^^^^^^^^^^^ By default there is no strict requirement that each *hookimpl* has a corresponding *hookspec*. However, if you'd like you enforce this behavior you can run a check with the :py:meth:`~pluggy.PluginManager.check_pending()` method. If you'd like to enforce requisite *hookspecs* but with certain exceptions for some hooks then make sure to mark those hooks as :ref:`optional `. Opt-in arguments ^^^^^^^^^^^^^^^^ To allow for *hookspecs* to evolve over the lifetime of a project, *hookimpls* can accept **less** arguments than defined in the spec. This allows for extending hook arguments (and thus semantics) without breaking existing *hookimpls*. In other words this is ok: .. code-block:: python @hookspec def myhook(config, args): pass @hookimpl def myhook(args): print(args) whereas this is not: .. code-block:: python @hookspec def myhook(config, args): pass @hookimpl def myhook(config, args, extra_arg): print(args) .. note:: The one exception to this rule (that a *hookspec* must have as least as many arguments as its *hookimpls*) is the conventional :ref:`self ` arg; this is always ignored when *hookimpls* are defined as :ref:`methods `. .. _firstresult: First result only ^^^^^^^^^^^^^^^^^ A *hookspec* can be marked such that when the *hook* is called the call loop will only invoke up to the first *hookimpl* which returns a result other than ``None``. .. code-block:: python @hookspec(firstresult=True) def myhook(config, args): pass This can be useful for optimizing a call loop for which you are only interested in a single core *hookimpl*. An example is the :func:`~_pytest.hookspec.pytest_cmdline_main` central routine of ``pytest``. Note that all hook wrappers are still invoked with the first result. Also see the :ref:`pytest:firstresult` section in the ``pytest`` docs. .. _historic: Historic hooks ^^^^^^^^^^^^^^ You can mark a *hookspec* as being *historic* meaning that the hook can be called with :py:meth:`~pluggy.HookCaller.call_historic()` **before** having been registered: .. code-block:: python @hookspec(historic=True) def myhook(config, args): pass The implication is that late registered *hookimpls* will be called back immediately at register time and **can not** return a result to the caller. This turns out to be particularly useful when dealing with lazy or dynamically loaded plugins. For more info see :ref:`call_historic`. .. _warn_on_impl: Warnings on hook implementation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ As projects evolve new hooks may be introduced and/or deprecated. If a hookspec specifies a ``warn_on_impl``, pluggy will trigger it for any plugin implementing the hook. .. code-block:: python @hookspec( warn_on_impl=DeprecationWarning("oldhook is deprecated and will be removed soon") ) def oldhook(): pass .. _manage: The Plugin registry ******************* ``pluggy`` manages plugins using instances of the :py:class:`pluggy.PluginManager`. A :py:class:`~pluggy.PluginManager` is instantiated with a single ``str`` argument, the ``project_name``: .. code-block:: python import pluggy pm = pluggy.PluginManager("my_project_name") The ``project_name`` value is used when a :py:class:`~pluggy.PluginManager` scans for *hook* functions :ref:`defined on a plugin `. This allows for multiple plugin managers from multiple projects to define hooks alongside each other. .. _registration: Registration ------------ Each :py:class:`~pluggy.PluginManager` maintains a *plugin* registry where each *plugin* contains a set of *hookimpl* definitions. Loading *hookimpl* and *hookspec* definitions to populate the registry is described in detail in the section on :ref:`define`. In summary, you pass a plugin namespace object to the :py:meth:`~pluggy.PluginManager.register()` and :py:meth:`~pluggy.PluginManager.add_hookspecs()` methods to collect hook *implementations* and *specifications* from *plugin* namespaces respectively. You can unregister any *plugin*'s hooks using :py:meth:`~pluggy.PluginManager.unregister()` and check if a plugin is registered by passing its name to the :py:meth:`~pluggy.PluginManager.is_registered()` method. Loading ``setuptools`` entry points ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You can automatically load plugins registered through :ref:`setuptools entry points ` with the :py:meth:`~pluggy.PluginManager.load_setuptools_entrypoints()` method. An example use of this is the :ref:`pytest entry point `. Blocking -------- You can block any plugin from being registered using :py:meth:`~pluggy.PluginManager.set_blocked()` and check if a given *plugin* is blocked by name using :py:meth:`~pluggy.PluginManager.is_blocked()`. Inspection ---------- You can use a variety of methods to inspect both the registry and particular plugins in it: - :py:meth:`~pluggy.PluginManager.list_name_plugin()` - return a list of name-plugin pairs - :py:meth:`~pluggy.PluginManager.get_plugins()` - retrieve all plugins - :py:meth:`~pluggy.PluginManager.get_canonical_name()`- get a *plugin*'s canonical name (the name it was registered with) - :py:meth:`~pluggy.PluginManager.get_plugin()` - retrieve a plugin by its canonical name Parsing mark options ^^^^^^^^^^^^^^^^^^^^ You can retrieve the *options* applied to a particular *hookspec* or *hookimpl* as per :ref:`marking_hooks` using the :py:meth:`~pluggy.PluginManager.parse_hookspec_opts()` and :py:meth:`~pluggy.PluginManager.parse_hookimpl_opts()` respectively. .. _calling: Calling hooks ************* The core functionality of ``pluggy`` enables an extension provider to override function calls made at certain points throughout a program. A particular *hook* is invoked by calling an instance of a :py:class:`pluggy.HookCaller` which in turn *loops* through the ``1:N`` registered *hookimpls* and calls them in sequence. Every :py:class:`~pluggy.PluginManager` has a ``hook`` attribute which is an instance of :py:class:`pluggy.HookRelay`. The :py:class:`~pluggy.HookRelay` itself contains references (by hook name) to each registered *hookimpl*'s :py:class:`~pluggy.HookCaller` instance. More practically you call a *hook* like so: .. code-block:: python import sys import pluggy import mypluginspec import myplugin from configuration import config pm = pluggy.PluginManager("myproject") pm.add_hookspecs(mypluginspec) pm.register(myplugin) # we invoke the HookCaller and thus all underlying hookimpls result_list = pm.hook.myhook(config=config, args=sys.argv) Note that you **must** call hooks using keyword :std:term:`python:argument` syntax! Hook implementations are called in LIFO registered order: *the last registered plugin's hooks are called first*. As an example, the below assertion should not error: .. code-block:: python from pluggy import PluginManager, HookimplMarker hookimpl = HookimplMarker("myproject") class Plugin1: @hookimpl def myhook(self, args): """Default implementation.""" return 1 class Plugin2: @hookimpl def myhook(self, args): """Default implementation.""" return 2 class Plugin3: @hookimpl def myhook(self, args): """Default implementation.""" return 3 pm = PluginManager("myproject") pm.register(Plugin1()) pm.register(Plugin2()) pm.register(Plugin3()) assert pm.hook.myhook(args=()) == [3, 2, 1] Collecting results ------------------ By default calling a hook results in all underlying :ref:`hookimpls ` functions to be invoked in sequence via a loop. Any function which returns a value other than a ``None`` result will have that result appended to a :py:class:`list` which is returned by the call. The only exception to this behaviour is if the hook has been marked to return its :ref:`first result only ` in which case only the first single value (which is not ``None``) will be returned. .. _call_historic: Exception handling ------------------ If any *hookimpl* errors with an exception no further callbacks are invoked and the exception is delivered to any :ref:`wrappers ` before being re-raised at the hook invocation point: .. code-block:: python from pluggy import PluginManager, HookimplMarker hookimpl = HookimplMarker("myproject") class Plugin1: @hookimpl def myhook(self, args): return 1 class Plugin2: @hookimpl def myhook(self, args): raise RuntimeError class Plugin3: @hookimpl def myhook(self, args): return 3 @hookimpl(wrapper=True) def myhook(self, args): try: return (yield) except RuntimeError as exc: # log runtime error details print(exc) raise pm = PluginManager("myproject") # register plugins pm.register(Plugin1()) pm.register(Plugin2()) pm.register(Plugin3()) # register wrapper pm.register(sys.modules[__name__]) # this raises RuntimeError due to Plugin2 pm.hook.myhook(args=()) Historic calls -------------- A *historic call* allows for all newly registered functions to receive all hook calls that happened before their registration. The implication is that this is only useful if you expect that some *hookimpls* may be registered **after** the hook is initially invoked. Historic hooks must be :ref:`specially marked ` and called using the :py:meth:`~pluggy.HookCaller.call_historic()` method: .. code-block:: python def callback(result): print("historic call result is {result}".format(result=result)) # call with history; no results returned pm.hook.myhook.call_historic( kwargs={"config": config, "args": sys.argv}, result_callback=callback ) # ... more of our program ... # late loading of some plugin import mylateplugin # historic callback is invoked here pm.register(mylateplugin) Note that if you :py:meth:`~pluggy.HookCaller.call_historic()` the :py:class:`~pluggy.HookCaller` (and thus your calling code) can not receive results back from the underlying *hookimpl* functions. Instead you can provide a *callback* for processing results (like the ``callback`` function above) which will be called as each new plugin is registered. .. note:: *historic* calls are incompatible with :ref:`firstresult` marked hooks since only the first registered plugin's hook(s) would ever be called. .. _call_extra: Calling with extras ------------------- You can call a hook with temporarily participating *implementation* functions (that aren't in the registry) using the :py:meth:`pluggy.HookCaller.call_extra()` method. Calling with a subset of registered plugins ------------------------------------------- You can make a call using a subset of plugins by asking the :py:class:`~pluggy.PluginManager` first for a :py:class:`~pluggy.HookCaller` with those plugins removed using the :py:meth:`pluggy.PluginManager.subset_hook_caller()` method. You then can use that :py:class:`~pluggy.HookCaller` to make normal, :py:meth:`~pluggy.HookCaller.call_historic`, or :py:meth:`~pluggy.HookCaller.call_extra` calls as necessary. .. _tracing: Built-in tracing **************** ``pluggy`` comes with some batteries included hook tracing for your debugging needs. Call tracing ------------ To enable tracing use the :py:meth:`pluggy.PluginManager.enable_tracing()` method which returns an undo function to disable the behaviour. .. code-block:: python pm = PluginManager("myproject") # magic line to set a writer function pm.trace.root.setwriter(print) undo = pm.enable_tracing() Call monitoring --------------- Instead of using the built-in tracing mechanism you can also add your own ``before`` and ``after`` monitoring functions using :py:class:`pluggy.PluginManager.add_hookcall_monitoring()`. The expected signature and default implementations for these functions is: .. code-block:: python def before(hook_name, hook_impls, kwargs): pass def after(outcome, hook_name, hook_impls, kwargs): pass Public API ********** Please see the :doc:`api_reference`. Development *********** Great care must taken when hacking on ``pluggy`` since multiple mature projects rely on it. Our Github integrated CI process runs the full `tox test suite`_ on each commit so be sure your changes can run on all required `Python interpreters`_ and ``pytest`` versions. For development, we suggest to create a virtual environment and install ``pluggy`` in editable mode and ``dev`` dependencies:: $ python3 -m venv .env $ source .env/bin/activate $ pip install -e .[dev] To make sure you follow the code style used in the project, install pre-commit_ which will run style checks before each commit:: $ pre-commit install Release Policy ************** Pluggy uses `Semantic Versioning`_. Breaking changes are only foreseen for Major releases (incremented X in "X.Y.Z"). If you want to use ``pluggy`` in your project you should thus use a dependency restriction like ``"pluggy>=0.1.0,<1.0"`` to avoid surprises. Table of contents ***************** .. toctree:: :maxdepth: 2 api_reference changelog .. hyperlinks .. _hookspec module: https://docs.pytest.org/en/latest/_modules/_pytest/hookspec.html .. _request-response pattern: https://en.wikipedia.org/wiki/Request%E2%80%93response .. _publish-subscribe: https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern .. _hooking: https://en.wikipedia.org/wiki/Hooking .. _callbacks: https://en.wikipedia.org/wiki/Callback_(computer_programming) .. _tox test suite: https://github.com/pytest-dev/pluggy/blob/main/tox.ini .. _Semantic Versioning: https://semver.org/ .. _Python interpreters: https://github.com/pytest-dev/pluggy/blob/main/tox.ini#L2 .. _500+ plugins: https://docs.pytest.org/en/latest/reference/plugin_list.html .. _pre-commit: https://pre-commit.com/ .. Indices and tables .. ================== .. * :ref:`genindex` .. * :ref:`modindex` .. * :ref:`search` pluggy-1.4.0/docs/requirements.txt000066400000000000000000000001571455415125700172530ustar00rootroot00000000000000# Higher bound for safety, can bump it if builds fine with new major versions. sphinx>=6,<8 pygments towncrier pluggy-1.4.0/downstream/000077500000000000000000000000001455415125700152175ustar00rootroot00000000000000pluggy-1.4.0/downstream/.gitignore000066400000000000000000000000631455415125700172060ustar00rootroot00000000000000/conda/ /datasette/ /devpi/ /hatch/ /pytest/ /tox/ pluggy-1.4.0/downstream/README.md000066400000000000000000000001531455415125700164750ustar00rootroot00000000000000This directory contains scripts for testing some downstream projects against your current pluggy worktree. pluggy-1.4.0/downstream/conda.sh000077500000000000000000000003771455415125700166510ustar00rootroot00000000000000#!/usr/bin/env bash set -eux -o pipefail if [[ ! -d conda ]]; then git clone https://github.com/conda/conda fi pushd conda && trap popd EXIT git pull set +eu source dev/start set -eu pip install -e ../../ pytest -m "not integration and not installed" pluggy-1.4.0/downstream/datasette.sh000077500000000000000000000003641455415125700175370ustar00rootroot00000000000000#!/usr/bin/env bash set -eux -o pipefail if [[ ! -d datasette ]]; then git clone https://github.com/simonw/datasette fi pushd datasette && trap popd EXIT git pull python -m venv venv venv/bin/pip install -e .[test] -e ../.. venv/bin/pytest pluggy-1.4.0/downstream/devpi.sh000077500000000000000000000004751455415125700166730ustar00rootroot00000000000000#!/usr/bin/env bash set -eux -o pipefail if [[ ! -d devpi ]]; then git clone https://github.com/devpi/devpi fi pushd devpi && trap popd EXIT git pull python -m venv venv venv/bin/pip install -r dev-requirements.txt -e ../.. venv/bin/pytest common venv/bin/pytest server venv/bin/pytest client venv/bin/pytest web pluggy-1.4.0/downstream/hatch.sh000077500000000000000000000003651455415125700166510ustar00rootroot00000000000000#!/usr/bin/env bash set -eux -o pipefail if [[ ! -d hatch ]]; then git clone https://github.com/pypa/hatch fi pushd hatch && trap popd EXIT git pull python -m venv venv venv/bin/pip install -e . -e ./backend -e ../.. venv/bin/hatch run dev pluggy-1.4.0/downstream/pytest.sh000077500000000000000000000003621455415125700171070ustar00rootroot00000000000000#!/usr/bin/env bash set -eux -o pipefail if [[ ! -d pytest ]]; then git clone https://github.com/pytest-dev/pytest fi pushd pytest && trap popd EXIT git pull python -m venv venv venv/bin/pip install -e .[testing] -e ../.. venv/bin/pytest pluggy-1.4.0/downstream/tox.sh000077500000000000000000000003351455415125700163710ustar00rootroot00000000000000#!/usr/bin/env bash set -eux -o pipefail if [[ ! -d tox ]]; then git clone https://github.com/tox-dev/tox fi pushd tox && trap popd EXIT python -m venv venv venv/bin/pip install -e .[testing] -e ../.. venv/bin/pytest pluggy-1.4.0/pyproject.toml000066400000000000000000000031111455415125700157440ustar00rootroot00000000000000[build-system] requires = [ # sync with setup.py until we discard non-pep-517/518 "setuptools>=45.0", "setuptools-scm[toml]>=6.2.3", ] build-backend = "setuptools.build_meta" [tool.setuptools_scm] write_to = "src/pluggy/_version.py" [tool.towncrier] package = "pluggy" package_dir = "src/pluggy" filename = "CHANGELOG.rst" directory = "changelog/" title_format = "pluggy {version} ({project_date})" template = "changelog/_template.rst" [[tool.towncrier.type]] directory = "removal" name = "Deprecations and Removals" showcontent = true [[tool.towncrier.type]] directory = "feature" name = "Features" showcontent = true [[tool.towncrier.type]] directory = "bugfix" name = "Bug Fixes" showcontent = true [[tool.towncrier.type]] directory = "vendor" name = "Vendored Libraries" showcontent = true [[tool.towncrier.type]] directory = "doc" name = "Improved Documentation" showcontent = true [[tool.towncrier.type]] directory = "trivial" name = "Trivial/Internal Changes" showcontent = true [tool.mypy] mypy_path = "src" check_untyped_defs = true # Hopefully we can set this someday! # disallow_any_expr = true disallow_any_generics = true disallow_any_unimported = true disallow_subclassing_any = true disallow_untyped_calls = true disallow_untyped_decorators = true ignore_missing_imports = true implicit_reexport = false no_implicit_optional = true show_error_codes = true strict_equality = true strict_optional = true warn_redundant_casts = true warn_return_any = true warn_unreachable = true warn_unused_configs = true warn_unused_ignores = true pluggy-1.4.0/scripts/000077500000000000000000000000001455415125700145235ustar00rootroot00000000000000pluggy-1.4.0/scripts/release.py000066400000000000000000000037141455415125700165220ustar00rootroot00000000000000""" Release script. """ import argparse import sys from subprocess import check_call from colorama import Fore from colorama import init from git import Remote from git import Repo def create_branch(version): """Create a fresh branch from upstream/main""" repo = Repo.init(".") if repo.is_dirty(untracked_files=True): raise RuntimeError("Repository is dirty, please commit/stash your changes.") branch_name = f"release-{version}" print(f"{Fore.CYAN}Create {branch_name} branch from upstream main") upstream = get_upstream(repo) upstream.fetch() release_branch = repo.create_head(branch_name, upstream.refs.main, force=True) release_branch.checkout() return repo def get_upstream(repo: Repo) -> Remote: """Find upstream repository for pluggy on the remotes""" for remote in repo.remotes: for url in remote.urls: if url.endswith(("pytest-dev/pluggy.git", "pytest-dev/pluggy")): return remote raise RuntimeError("could not find pytest-dev/pluggy remote") def pre_release(version): """Generates new docs, release announcements and creates a local tag.""" create_branch(version) changelog(version, write_out=True) check_call(["git", "commit", "-a", "-m", f"Preparing release {version}"]) print() print(f"{Fore.GREEN}Please push your branch to your fork and open a PR.") def changelog(version, write_out=False): if write_out: addopts = [] else: addopts = ["--draft"] print(f"{Fore.CYAN}Generating CHANGELOG") check_call(["towncrier", "build", "--yes", "--version", version] + addopts) def main(): init(autoreset=True) parser = argparse.ArgumentParser() parser.add_argument("version", help="Release version") options = parser.parse_args() try: pre_release(options.version) except RuntimeError as e: print(f"{Fore.RED}ERROR: {e}") return 1 if __name__ == "__main__": sys.exit(main()) pluggy-1.4.0/scripts/towncrier-draft-to-file.py000066400000000000000000000006541455415125700215510ustar00rootroot00000000000000import sys from subprocess import call def main(): """ Platform agnostic wrapper script for towncrier. Fixes the issue (pytest#7251) where windows users are unable to natively run tox -e docs to build pytest docs. """ with open("docs/_changelog_towncrier_draft.rst", "w") as draft_file: return call(("towncrier", "--draft"), stdout=draft_file) if __name__ == "__main__": sys.exit(main()) pluggy-1.4.0/scripts/upload-coverage.sh000077500000000000000000000006471455415125700201460ustar00rootroot00000000000000#!/usr/bin/env bash set -e set -x if [ -z "$TOXENV" ]; then python -m pip install coverage else # Add last TOXENV to $PATH. PATH="$PWD/.tox/${TOXENV##*,}/bin:$PATH" fi python -m coverage xml # Set --connect-timeout to work around https://github.com/curl/curl/issues/4461 curl -S -L --connect-timeout 5 --retry 6 -s https://codecov.io/bash -o codecov-upload.sh bash codecov-upload.sh -Z -X fix -f coverage.xml "$@" pluggy-1.4.0/setup.cfg000066400000000000000000000025151455415125700146600ustar00rootroot00000000000000[metadata] name = pluggy description = plugin and hook calling mechanisms for python long_description = file: README.rst long_description_content_type = text/x-rst license = MIT platforms = unix, linux, osx, win32 author = Holger Krekel author_email = holger@merlinux.eu url = https://github.com/pytest-dev/pluggy classifiers = Development Status :: 6 - Mature Intended Audience :: Developers License :: OSI Approved :: MIT License Operating System :: POSIX Operating System :: Microsoft :: Windows Operating System :: MacOS :: MacOS X Topic :: Software Development :: Testing Topic :: Software Development :: Libraries Topic :: Utilities Programming Language :: Python :: Implementation :: CPython Programming Language :: Python :: Implementation :: PyPy Programming Language :: Python :: 3 Programming Language :: Python :: 3 :: Only Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 [options] packages = pluggy python_requires = >=3.8 package_dir = =src setup_requires = setuptools-scm [options.extras_require] dev = pre-commit tox testing = pytest pytest-benchmark [options.package_data] pluggy = py.typed [devpi:upload] formats=sdist.tgz,bdist_wheel pluggy-1.4.0/setup.py000066400000000000000000000001741455415125700145500ustar00rootroot00000000000000from setuptools import setup if __name__ == "__main__": setup(use_scm_version={"write_to": "src/pluggy/_version.py"}) pluggy-1.4.0/src/000077500000000000000000000000001455415125700136235ustar00rootroot00000000000000pluggy-1.4.0/src/pluggy/000077500000000000000000000000001455415125700151325ustar00rootroot00000000000000pluggy-1.4.0/src/pluggy/__init__.py000066400000000000000000000015211455415125700172420ustar00rootroot00000000000000try: from ._version import version as __version__ except ImportError: # broken installation, we don't even try # unknown only works because we do poor mans version compare __version__ = "unknown" __all__ = [ "__version__", "PluginManager", "PluginValidationError", "HookCaller", "HookCallError", "HookspecOpts", "HookimplOpts", "HookImpl", "HookRelay", "HookspecMarker", "HookimplMarker", "Result", "PluggyWarning", "PluggyTeardownRaisedWarning", ] from ._manager import PluginManager, PluginValidationError from ._result import HookCallError, Result from ._hooks import ( HookspecMarker, HookimplMarker, HookCaller, HookRelay, HookspecOpts, HookimplOpts, HookImpl, ) from ._warnings import ( PluggyWarning, PluggyTeardownRaisedWarning, ) pluggy-1.4.0/src/pluggy/_callers.py000066400000000000000000000162231455415125700172740ustar00rootroot00000000000000""" Call loop machinery """ from __future__ import annotations import warnings from typing import cast from typing import Generator from typing import Mapping from typing import NoReturn from typing import Sequence from typing import Tuple from typing import Union from ._hooks import HookImpl from ._result import HookCallError from ._result import Result from ._warnings import PluggyTeardownRaisedWarning # Need to distinguish between old- and new-style hook wrappers. # Wrapping with a tuple is the fastest type-safe way I found to do it. Teardown = Union[ Tuple[Generator[None, Result[object], None], HookImpl], Generator[None, object, object], ] def _raise_wrapfail( wrap_controller: ( Generator[None, Result[object], None] | Generator[None, object, object] ), msg: str, ) -> NoReturn: co = wrap_controller.gi_code raise RuntimeError( "wrap_controller at %r %s:%d %s" % (co.co_name, co.co_filename, co.co_firstlineno, msg) ) def _warn_teardown_exception( hook_name: str, hook_impl: HookImpl, e: BaseException ) -> None: msg = "A plugin raised an exception during an old-style hookwrapper teardown.\n" msg += f"Plugin: {hook_impl.plugin_name}, Hook: {hook_name}\n" msg += f"{type(e).__name__}: {e}\n" msg += "For more information see https://pluggy.readthedocs.io/en/stable/api_reference.html#pluggy.PluggyTeardownRaisedWarning" # noqa: E501 warnings.warn(PluggyTeardownRaisedWarning(msg), stacklevel=5) def _multicall( hook_name: str, hook_impls: Sequence[HookImpl], caller_kwargs: Mapping[str, object], firstresult: bool, ) -> object | list[object]: """Execute a call into multiple python functions/methods and return the result(s). ``caller_kwargs`` comes from HookCaller.__call__(). """ __tracebackhide__ = True results: list[object] = [] exception = None only_new_style_wrappers = True try: # run impl and wrapper setup functions in a loop teardowns: list[Teardown] = [] try: for hook_impl in reversed(hook_impls): try: args = [caller_kwargs[argname] for argname in hook_impl.argnames] except KeyError: for argname in hook_impl.argnames: if argname not in caller_kwargs: raise HookCallError( f"hook call must provide argument {argname!r}" ) if hook_impl.hookwrapper: only_new_style_wrappers = False try: # If this cast is not valid, a type error is raised below, # which is the desired response. res = hook_impl.function(*args) wrapper_gen = cast(Generator[None, Result[object], None], res) next(wrapper_gen) # first yield teardowns.append((wrapper_gen, hook_impl)) except StopIteration: _raise_wrapfail(wrapper_gen, "did not yield") elif hook_impl.wrapper: try: # If this cast is not valid, a type error is raised below, # which is the desired response. res = hook_impl.function(*args) function_gen = cast(Generator[None, object, object], res) next(function_gen) # first yield teardowns.append(function_gen) except StopIteration: _raise_wrapfail(function_gen, "did not yield") else: res = hook_impl.function(*args) if res is not None: results.append(res) if firstresult: # halt further impl calls break except BaseException as exc: exception = exc finally: # Fast path - only new-style wrappers, no Result. if only_new_style_wrappers: if firstresult: # first result hooks return a single value result = results[0] if results else None else: result = results # run all wrapper post-yield blocks for teardown in reversed(teardowns): try: if exception is not None: teardown.throw(exception) # type: ignore[union-attr] else: teardown.send(result) # type: ignore[union-attr] # Following is unreachable for a well behaved hook wrapper. # Try to force finalizers otherwise postponed till GC action. # Note: close() may raise if generator handles GeneratorExit. teardown.close() # type: ignore[union-attr] except StopIteration as si: result = si.value exception = None continue except BaseException as e: exception = e continue _raise_wrapfail(teardown, "has second yield") # type: ignore[arg-type] if exception is not None: raise exception.with_traceback(exception.__traceback__) else: return result # Slow path - need to support old-style wrappers. else: if firstresult: # first result hooks return a single value outcome: Result[object | list[object]] = Result( results[0] if results else None, exception ) else: outcome = Result(results, exception) # run all wrapper post-yield blocks for teardown in reversed(teardowns): if isinstance(teardown, tuple): try: teardown[0].send(outcome) except StopIteration: pass except BaseException as e: _warn_teardown_exception(hook_name, teardown[1], e) raise else: _raise_wrapfail(teardown[0], "has second yield") else: try: if outcome._exception is not None: teardown.throw(outcome._exception) else: teardown.send(outcome._result) # Following is unreachable for a well behaved hook wrapper. # Try to force finalizers otherwise postponed till GC action. # Note: close() may raise if generator handles GeneratorExit. teardown.close() except StopIteration as si: outcome.force_result(si.value) continue except BaseException as e: outcome.force_exception(e) continue _raise_wrapfail(teardown, "has second yield") return outcome.get_result() pluggy-1.4.0/src/pluggy/_hooks.py000066400000000000000000000574541455415125700170050ustar00rootroot00000000000000""" Internal hook annotation, representation and calling machinery. """ from __future__ import annotations import inspect import sys import warnings from types import ModuleType from typing import AbstractSet from typing import Any from typing import Callable from typing import Final from typing import final from typing import Generator from typing import List from typing import Mapping from typing import Optional from typing import overload from typing import Sequence from typing import Tuple from typing import TYPE_CHECKING from typing import TypedDict from typing import TypeVar from typing import Union from ._result import Result _T = TypeVar("_T") _F = TypeVar("_F", bound=Callable[..., object]) _Namespace = Union[ModuleType, type] _Plugin = object _HookExec = Callable[ [str, Sequence["HookImpl"], Mapping[str, object], bool], Union[object, List[object]], ] _HookImplFunction = Callable[..., Union[_T, Generator[None, Result[_T], None]]] class HookspecOpts(TypedDict): """Options for a hook specification.""" #: Whether the hook is :ref:`first result only `. firstresult: bool #: Whether the hook is :ref:`historic `. historic: bool #: Whether the hook :ref:`warns when implemented `. warn_on_impl: Warning | None class HookimplOpts(TypedDict): """Options for a hook implementation.""" #: Whether the hook implementation is a :ref:`wrapper `. wrapper: bool #: Whether the hook implementation is an :ref:`old-style wrapper #: `. hookwrapper: bool #: Whether validation against a hook specification is :ref:`optional #: `. optionalhook: bool #: Whether to try to order this hook implementation :ref:`first #: `. tryfirst: bool #: Whether to try to order this hook implementation :ref:`last #: `. trylast: bool #: The name of the hook specification to match, see :ref:`specname`. specname: str | None @final class HookspecMarker: """Decorator for marking functions as hook specifications. Instantiate it with a project_name to get a decorator. Calling :meth:`PluginManager.add_hookspecs` later will discover all marked functions if the :class:`PluginManager` uses the same project name. """ __slots__ = ("project_name",) def __init__(self, project_name: str) -> None: self.project_name: Final = project_name @overload def __call__( self, function: _F, firstresult: bool = False, historic: bool = False, warn_on_impl: Warning | None = None, ) -> _F: ... @overload # noqa: F811 def __call__( # noqa: F811 self, function: None = ..., firstresult: bool = ..., historic: bool = ..., warn_on_impl: Warning | None = ..., ) -> Callable[[_F], _F]: ... def __call__( # noqa: F811 self, function: _F | None = None, firstresult: bool = False, historic: bool = False, warn_on_impl: Warning | None = None, ) -> _F | Callable[[_F], _F]: """If passed a function, directly sets attributes on the function which will make it discoverable to :meth:`PluginManager.add_hookspecs`. If passed no function, returns a decorator which can be applied to a function later using the attributes supplied. :param firstresult: If ``True``, the 1:N hook call (N being the number of registered hook implementation functions) will stop at I<=N when the I'th function returns a non-``None`` result. See :ref:`firstresult`. :param historic: If ``True``, every call to the hook will be memorized and replayed on plugins registered after the call was made. See :ref:`historic`. :param warn_on_impl: If given, every implementation of this hook will trigger the given warning. See :ref:`warn_on_impl`. """ def setattr_hookspec_opts(func: _F) -> _F: if historic and firstresult: raise ValueError("cannot have a historic firstresult hook") opts: HookspecOpts = { "firstresult": firstresult, "historic": historic, "warn_on_impl": warn_on_impl, } setattr(func, self.project_name + "_spec", opts) return func if function is not None: return setattr_hookspec_opts(function) else: return setattr_hookspec_opts @final class HookimplMarker: """Decorator for marking functions as hook implementations. Instantiate it with a ``project_name`` to get a decorator. Calling :meth:`PluginManager.register` later will discover all marked functions if the :class:`PluginManager` uses the same project name. """ __slots__ = ("project_name",) def __init__(self, project_name: str) -> None: self.project_name: Final = project_name @overload def __call__( self, function: _F, hookwrapper: bool = ..., optionalhook: bool = ..., tryfirst: bool = ..., trylast: bool = ..., specname: str | None = ..., wrapper: bool = ..., ) -> _F: ... @overload # noqa: F811 def __call__( # noqa: F811 self, function: None = ..., hookwrapper: bool = ..., optionalhook: bool = ..., tryfirst: bool = ..., trylast: bool = ..., specname: str | None = ..., wrapper: bool = ..., ) -> Callable[[_F], _F]: ... def __call__( # noqa: F811 self, function: _F | None = None, hookwrapper: bool = False, optionalhook: bool = False, tryfirst: bool = False, trylast: bool = False, specname: str | None = None, wrapper: bool = False, ) -> _F | Callable[[_F], _F]: """If passed a function, directly sets attributes on the function which will make it discoverable to :meth:`PluginManager.register`. If passed no function, returns a decorator which can be applied to a function later using the attributes supplied. :param optionalhook: If ``True``, a missing matching hook specification will not result in an error (by default it is an error if no matching spec is found). See :ref:`optionalhook`. :param tryfirst: If ``True``, this hook implementation will run as early as possible in the chain of N hook implementations for a specification. See :ref:`callorder`. :param trylast: If ``True``, this hook implementation will run as late as possible in the chain of N hook implementations for a specification. See :ref:`callorder`. :param wrapper: If ``True`` ("new-style hook wrapper"), the hook implementation needs to execute exactly one ``yield``. The code before the ``yield`` is run early before any non-hook-wrapper function is run. The code after the ``yield`` is run after all non-hook-wrapper functions have run. The ``yield`` receives the result value of the inner calls, or raises the exception of inner calls (including earlier hook wrapper calls). The return value of the function becomes the return value of the hook, and a raised exception becomes the exception of the hook. See :ref:`hookwrapper`. :param hookwrapper: If ``True`` ("old-style hook wrapper"), the hook implementation needs to execute exactly one ``yield``. The code before the ``yield`` is run early before any non-hook-wrapper function is run. The code after the ``yield`` is run after all non-hook-wrapper function have run The ``yield`` receives a :class:`Result` object representing the exception or result outcome of the inner calls (including earlier hook wrapper calls). This option is mutually exclusive with ``wrapper``. See :ref:`old_style_hookwrapper`. :param specname: If provided, the given name will be used instead of the function name when matching this hook implementation to a hook specification during registration. See :ref:`specname`. .. versionadded:: 1.2.0 The ``wrapper`` parameter. """ def setattr_hookimpl_opts(func: _F) -> _F: opts: HookimplOpts = { "wrapper": wrapper, "hookwrapper": hookwrapper, "optionalhook": optionalhook, "tryfirst": tryfirst, "trylast": trylast, "specname": specname, } setattr(func, self.project_name + "_impl", opts) return func if function is None: return setattr_hookimpl_opts else: return setattr_hookimpl_opts(function) def normalize_hookimpl_opts(opts: HookimplOpts) -> None: opts.setdefault("tryfirst", False) opts.setdefault("trylast", False) opts.setdefault("wrapper", False) opts.setdefault("hookwrapper", False) opts.setdefault("optionalhook", False) opts.setdefault("specname", None) _PYPY = hasattr(sys, "pypy_version_info") def varnames(func: object) -> tuple[tuple[str, ...], tuple[str, ...]]: """Return tuple of positional and keywrord argument names for a function, method, class or callable. In case of a class, its ``__init__`` method is considered. For methods the ``self`` parameter is not included. """ if inspect.isclass(func): try: func = func.__init__ except AttributeError: return (), () elif not inspect.isroutine(func): # callable object? try: func = getattr(func, "__call__", func) except Exception: return (), () try: # func MUST be a function or method here or we won't parse any args. sig = inspect.signature( func.__func__ if inspect.ismethod(func) else func # type:ignore[arg-type] ) except TypeError: return (), () _valid_param_kinds = ( inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD, ) _valid_params = { name: param for name, param in sig.parameters.items() if param.kind in _valid_param_kinds } args = tuple(_valid_params) defaults = ( tuple( param.default for param in _valid_params.values() if param.default is not param.empty ) or None ) if defaults: index = -len(defaults) args, kwargs = args[:index], tuple(args[index:]) else: kwargs = () # strip any implicit instance arg # pypy3 uses "obj" instead of "self" for default dunder methods if not _PYPY: implicit_names: tuple[str, ...] = ("self",) else: implicit_names = ("self", "obj") if args: qualname: str = getattr(func, "__qualname__", "") if inspect.ismethod(func) or ("." in qualname and args[0] in implicit_names): args = args[1:] return args, kwargs @final class HookRelay: """Hook holder object for performing 1:N hook calls where N is the number of registered plugins.""" __slots__ = ("__dict__",) def __init__(self) -> None: """:meta private:""" if TYPE_CHECKING: def __getattr__(self, name: str) -> HookCaller: ... # Historical name (pluggy<=1.2), kept for backward compatibility. _HookRelay = HookRelay _CallHistory = List[Tuple[Mapping[str, object], Optional[Callable[[Any], None]]]] class HookCaller: """A caller of all registered implementations of a hook specification.""" __slots__ = ( "name", "spec", "_hookexec", "_hookimpls", "_call_history", ) def __init__( self, name: str, hook_execute: _HookExec, specmodule_or_class: _Namespace | None = None, spec_opts: HookspecOpts | None = None, ) -> None: """:meta private:""" #: Name of the hook getting called. self.name: Final = name self._hookexec: Final = hook_execute # The hookimpls list. The caller iterates it *in reverse*. Format: # 1. trylast nonwrappers # 2. nonwrappers # 3. tryfirst nonwrappers # 4. trylast wrappers # 5. wrappers # 6. tryfirst wrappers self._hookimpls: Final[list[HookImpl]] = [] self._call_history: _CallHistory | None = None # TODO: Document, or make private. self.spec: HookSpec | None = None if specmodule_or_class is not None: assert spec_opts is not None self.set_specification(specmodule_or_class, spec_opts) # TODO: Document, or make private. def has_spec(self) -> bool: return self.spec is not None # TODO: Document, or make private. def set_specification( self, specmodule_or_class: _Namespace, spec_opts: HookspecOpts, ) -> None: if self.spec is not None: raise ValueError( f"Hook {self.spec.name!r} is already registered " f"within namespace {self.spec.namespace}" ) self.spec = HookSpec(specmodule_or_class, self.name, spec_opts) if spec_opts.get("historic"): self._call_history = [] def is_historic(self) -> bool: """Whether this caller is :ref:`historic `.""" return self._call_history is not None def _remove_plugin(self, plugin: _Plugin) -> None: for i, method in enumerate(self._hookimpls): if method.plugin == plugin: del self._hookimpls[i] return raise ValueError(f"plugin {plugin!r} not found") def get_hookimpls(self) -> list[HookImpl]: """Get all registered hook implementations for this hook.""" return self._hookimpls.copy() def _add_hookimpl(self, hookimpl: HookImpl) -> None: """Add an implementation to the callback chain.""" for i, method in enumerate(self._hookimpls): if method.hookwrapper or method.wrapper: splitpoint = i break else: splitpoint = len(self._hookimpls) if hookimpl.hookwrapper or hookimpl.wrapper: start, end = splitpoint, len(self._hookimpls) else: start, end = 0, splitpoint if hookimpl.trylast: self._hookimpls.insert(start, hookimpl) elif hookimpl.tryfirst: self._hookimpls.insert(end, hookimpl) else: # find last non-tryfirst method i = end - 1 while i >= start and self._hookimpls[i].tryfirst: i -= 1 self._hookimpls.insert(i + 1, hookimpl) def __repr__(self) -> str: return f"" def _verify_all_args_are_provided(self, kwargs: Mapping[str, object]) -> None: # This is written to avoid expensive operations when not needed. if self.spec: for argname in self.spec.argnames: if argname not in kwargs: notincall = ", ".join( repr(argname) for argname in self.spec.argnames # Avoid self.spec.argnames - kwargs.keys() - doesn't preserve order. if argname not in kwargs.keys() ) warnings.warn( "Argument(s) {} which are declared in the hookspec " "cannot be found in this hook call".format(notincall), stacklevel=2, ) break def __call__(self, **kwargs: object) -> Any: """Call the hook. Only accepts keyword arguments, which should match the hook specification. Returns the result(s) of calling all registered plugins, see :ref:`calling`. """ assert ( not self.is_historic() ), "Cannot directly call a historic hook - use call_historic instead." self._verify_all_args_are_provided(kwargs) firstresult = self.spec.opts.get("firstresult", False) if self.spec else False # Copy because plugins may register other plugins during iteration (#438). return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) def call_historic( self, result_callback: Callable[[Any], None] | None = None, kwargs: Mapping[str, object] | None = None, ) -> None: """Call the hook with given ``kwargs`` for all registered plugins and for all plugins which will be registered afterwards, see :ref:`historic`. :param result_callback: If provided, will be called for each non-``None`` result obtained from a hook implementation. """ assert self._call_history is not None kwargs = kwargs or {} self._verify_all_args_are_provided(kwargs) self._call_history.append((kwargs, result_callback)) # Historizing hooks don't return results. # Remember firstresult isn't compatible with historic. # Copy because plugins may register other plugins during iteration (#438). res = self._hookexec(self.name, self._hookimpls.copy(), kwargs, False) if result_callback is None: return if isinstance(res, list): for x in res: result_callback(x) def call_extra( self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object] ) -> Any: """Call the hook with some additional temporarily participating methods using the specified ``kwargs`` as call parameters, see :ref:`call_extra`.""" assert ( not self.is_historic() ), "Cannot directly call a historic hook - use call_historic instead." self._verify_all_args_are_provided(kwargs) opts: HookimplOpts = { "wrapper": False, "hookwrapper": False, "optionalhook": False, "trylast": False, "tryfirst": False, "specname": None, } hookimpls = self._hookimpls.copy() for method in methods: hookimpl = HookImpl(None, "", method, opts) # Find last non-tryfirst nonwrapper method. i = len(hookimpls) - 1 while i >= 0 and ( # Skip wrappers. (hookimpls[i].hookwrapper or hookimpls[i].wrapper) # Skip tryfirst nonwrappers. or hookimpls[i].tryfirst ): i -= 1 hookimpls.insert(i + 1, hookimpl) firstresult = self.spec.opts.get("firstresult", False) if self.spec else False return self._hookexec(self.name, hookimpls, kwargs, firstresult) def _maybe_apply_history(self, method: HookImpl) -> None: """Apply call history to a new hookimpl if it is marked as historic.""" if self.is_historic(): assert self._call_history is not None for kwargs, result_callback in self._call_history: res = self._hookexec(self.name, [method], kwargs, False) if res and result_callback is not None: # XXX: remember firstresult isn't compat with historic assert isinstance(res, list) result_callback(res[0]) # Historical name (pluggy<=1.2), kept for backward compatibility. _HookCaller = HookCaller class _SubsetHookCaller(HookCaller): """A proxy to another HookCaller which manages calls to all registered plugins except the ones from remove_plugins.""" # This class is unusual: in inhertits from `HookCaller` so all of # the *code* runs in the class, but it delegates all underlying *data* # to the original HookCaller. # `subset_hook_caller` used to be implemented by creating a full-fledged # HookCaller, copying all hookimpls from the original. This had problems # with memory leaks (#346) and historic calls (#347), which make a proxy # approach better. # An alternative implementation is to use a `_getattr__`/`__getattribute__` # proxy, however that adds more overhead and is more tricky to implement. __slots__ = ( "_orig", "_remove_plugins", ) def __init__(self, orig: HookCaller, remove_plugins: AbstractSet[_Plugin]) -> None: self._orig = orig self._remove_plugins = remove_plugins self.name = orig.name # type: ignore[misc] self._hookexec = orig._hookexec # type: ignore[misc] @property # type: ignore[misc] def _hookimpls(self) -> list[HookImpl]: return [ impl for impl in self._orig._hookimpls if impl.plugin not in self._remove_plugins ] @property def spec(self) -> HookSpec | None: # type: ignore[override] return self._orig.spec @property def _call_history(self) -> _CallHistory | None: # type: ignore[override] return self._orig._call_history def __repr__(self) -> str: return f"<_SubsetHookCaller {self.name!r}>" @final class HookImpl: """A hook implementation in a :class:`HookCaller`.""" __slots__ = ( "function", "argnames", "kwargnames", "plugin", "opts", "plugin_name", "wrapper", "hookwrapper", "optionalhook", "tryfirst", "trylast", ) def __init__( self, plugin: _Plugin, plugin_name: str, function: _HookImplFunction[object], hook_impl_opts: HookimplOpts, ) -> None: """:meta private:""" #: The hook implementation function. self.function: Final = function argnames, kwargnames = varnames(self.function) #: The positional parameter names of ``function```. self.argnames: Final = argnames #: The keyword parameter names of ``function```. self.kwargnames: Final = kwargnames #: The plugin which defined this hook implementation. self.plugin: Final = plugin #: The :class:`HookimplOpts` used to configure this hook implementation. self.opts: Final = hook_impl_opts #: The name of the plugin which defined this hook implementation. self.plugin_name: Final = plugin_name #: Whether the hook implementation is a :ref:`wrapper `. self.wrapper: Final = hook_impl_opts["wrapper"] #: Whether the hook implementation is an :ref:`old-style wrapper #: `. self.hookwrapper: Final = hook_impl_opts["hookwrapper"] #: Whether validation against a hook specification is :ref:`optional #: `. self.optionalhook: Final = hook_impl_opts["optionalhook"] #: Whether to try to order this hook implementation :ref:`first #: `. self.tryfirst: Final = hook_impl_opts["tryfirst"] #: Whether to try to order this hook implementation :ref:`last #: `. self.trylast: Final = hook_impl_opts["trylast"] def __repr__(self) -> str: return f"" @final class HookSpec: __slots__ = ( "namespace", "function", "name", "argnames", "kwargnames", "opts", "warn_on_impl", ) def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None: self.namespace = namespace self.function: Callable[..., object] = getattr(namespace, name) self.name = name self.argnames, self.kwargnames = varnames(self.function) self.opts = opts self.warn_on_impl = opts.get("warn_on_impl") pluggy-1.4.0/src/pluggy/_manager.py000066400000000000000000000467401455415125700172700ustar00rootroot00000000000000from __future__ import annotations import inspect import types import warnings from typing import Any from typing import Callable from typing import cast from typing import Final from typing import Iterable from typing import Mapping from typing import Sequence from typing import TYPE_CHECKING from . import _tracing from ._callers import _multicall from ._hooks import _HookImplFunction from ._hooks import _Namespace from ._hooks import _Plugin from ._hooks import _SubsetHookCaller from ._hooks import HookCaller from ._hooks import HookImpl from ._hooks import HookimplOpts from ._hooks import HookRelay from ._hooks import HookspecOpts from ._hooks import normalize_hookimpl_opts from ._result import Result if TYPE_CHECKING: # importtlib.metadata import is slow, defer it. import importlib.metadata _BeforeTrace = Callable[[str, Sequence[HookImpl], Mapping[str, Any]], None] _AfterTrace = Callable[[Result[Any], str, Sequence[HookImpl], Mapping[str, Any]], None] def _warn_for_function(warning: Warning, function: Callable[..., object]) -> None: func = cast(types.FunctionType, function) warnings.warn_explicit( warning, type(warning), lineno=func.__code__.co_firstlineno, filename=func.__code__.co_filename, ) class PluginValidationError(Exception): """Plugin failed validation. :param plugin: The plugin which failed validation. :param message: Error message. """ def __init__(self, plugin: _Plugin, message: str) -> None: super().__init__(message) #: The plugin which failed validation. self.plugin = plugin class DistFacade: """Emulate a pkg_resources Distribution""" def __init__(self, dist: importlib.metadata.Distribution) -> None: self._dist = dist @property def project_name(self) -> str: name: str = self.metadata["name"] return name def __getattr__(self, attr: str, default=None): return getattr(self._dist, attr, default) def __dir__(self) -> list[str]: return sorted(dir(self._dist) + ["_dist", "project_name"]) class PluginManager: """Core class which manages registration of plugin objects and 1:N hook calling. You can register new hooks by calling :meth:`add_hookspecs(module_or_class) `. You can register plugin objects (which contain hook implementations) by calling :meth:`register(plugin) `. For debugging purposes you can call :meth:`PluginManager.enable_tracing` which will subsequently send debug information to the trace helper. :param project_name: The short project name. Prefer snake case. Make sure it's unique! """ def __init__(self, project_name: str) -> None: #: The project name. self.project_name: Final = project_name self._name2plugin: Final[dict[str, _Plugin]] = {} self._plugin_distinfo: Final[list[tuple[_Plugin, DistFacade]]] = [] #: The "hook relay", used to call a hook on all registered plugins. #: See :ref:`calling`. self.hook: Final = HookRelay() #: The tracing entry point. See :ref:`tracing`. self.trace: Final[_tracing.TagTracerSub] = _tracing.TagTracer().get( "pluginmanage" ) self._inner_hookexec = _multicall def _hookexec( self, hook_name: str, methods: Sequence[HookImpl], kwargs: Mapping[str, object], firstresult: bool, ) -> object | list[object]: # called from all hookcaller instances. # enable_tracing will set its own wrapping function at self._inner_hookexec return self._inner_hookexec(hook_name, methods, kwargs, firstresult) def register(self, plugin: _Plugin, name: str | None = None) -> str | None: """Register a plugin and return its name. :param name: The name under which to register the plugin. If not specified, a name is generated using :func:`get_canonical_name`. :returns: The plugin name. If the name is blocked from registering, returns ``None``. If the plugin is already registered, raises a :exc:`ValueError`. """ plugin_name = name or self.get_canonical_name(plugin) if plugin_name in self._name2plugin: if self._name2plugin.get(plugin_name, -1) is None: return None # blocked plugin, return None to indicate no registration raise ValueError( "Plugin name already registered: %s=%s\n%s" % (plugin_name, plugin, self._name2plugin) ) if plugin in self._name2plugin.values(): raise ValueError( "Plugin already registered under a different name: %s=%s\n%s" % (plugin_name, plugin, self._name2plugin) ) # XXX if an error happens we should make sure no state has been # changed at point of return self._name2plugin[plugin_name] = plugin # register matching hook implementations of the plugin for name in dir(plugin): hookimpl_opts = self.parse_hookimpl_opts(plugin, name) if hookimpl_opts is not None: normalize_hookimpl_opts(hookimpl_opts) method: _HookImplFunction[object] = getattr(plugin, name) hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts) name = hookimpl_opts.get("specname") or name hook: HookCaller | None = getattr(self.hook, name, None) if hook is None: hook = HookCaller(name, self._hookexec) setattr(self.hook, name, hook) elif hook.has_spec(): self._verify_hook(hook, hookimpl) hook._maybe_apply_history(hookimpl) hook._add_hookimpl(hookimpl) return plugin_name def parse_hookimpl_opts(self, plugin: _Plugin, name: str) -> HookimplOpts | None: """Try to obtain a hook implementation from an item with the given name in the given plugin which is being searched for hook impls. :returns: The parsed hookimpl options, or None to skip the given item. This method can be overridden by ``PluginManager`` subclasses to customize how hook implementation are picked up. By default, returns the options for items decorated with :class:`HookimplMarker`. """ method: object = getattr(plugin, name) if not inspect.isroutine(method): return None try: res: HookimplOpts | None = getattr( method, self.project_name + "_impl", None ) except Exception: res = {} # type: ignore[assignment] if res is not None and not isinstance(res, dict): # false positive res = None # type:ignore[unreachable] return res def unregister( self, plugin: _Plugin | None = None, name: str | None = None ) -> Any | None: """Unregister a plugin and all of its hook implementations. The plugin can be specified either by the plugin object or the plugin name. If both are specified, they must agree. Returns the unregistered plugin, or ``None`` if not found. """ if name is None: assert plugin is not None, "one of name or plugin needs to be specified" name = self.get_name(plugin) assert name is not None, "plugin is not registered" if plugin is None: plugin = self.get_plugin(name) if plugin is None: return None hookcallers = self.get_hookcallers(plugin) if hookcallers: for hookcaller in hookcallers: hookcaller._remove_plugin(plugin) # if self._name2plugin[name] == None registration was blocked: ignore if self._name2plugin.get(name): assert name is not None del self._name2plugin[name] return plugin def set_blocked(self, name: str) -> None: """Block registrations of the given name, unregister if already registered.""" self.unregister(name=name) self._name2plugin[name] = None def is_blocked(self, name: str) -> bool: """Return whether the given plugin name is blocked.""" return name in self._name2plugin and self._name2plugin[name] is None def unblock(self, name: str) -> bool: """Unblocks a name. Returns whether the name was actually blocked. """ if self._name2plugin.get(name, -1) is None: del self._name2plugin[name] return True return False def add_hookspecs(self, module_or_class: _Namespace) -> None: """Add new hook specifications defined in the given ``module_or_class``. Functions are recognized as hook specifications if they have been decorated with a matching :class:`HookspecMarker`. """ names = [] for name in dir(module_or_class): spec_opts = self.parse_hookspec_opts(module_or_class, name) if spec_opts is not None: hc: HookCaller | None = getattr(self.hook, name, None) if hc is None: hc = HookCaller(name, self._hookexec, module_or_class, spec_opts) setattr(self.hook, name, hc) else: # Plugins registered this hook without knowing the spec. hc.set_specification(module_or_class, spec_opts) for hookfunction in hc.get_hookimpls(): self._verify_hook(hc, hookfunction) names.append(name) if not names: raise ValueError( f"did not find any {self.project_name!r} hooks in {module_or_class!r}" ) def parse_hookspec_opts( self, module_or_class: _Namespace, name: str ) -> HookspecOpts | None: """Try to obtain a hook specification from an item with the given name in the given module or class which is being searched for hook specs. :returns: The parsed hookspec options for defining a hook, or None to skip the given item. This method can be overridden by ``PluginManager`` subclasses to customize how hook specifications are picked up. By default, returns the options for items decorated with :class:`HookspecMarker`. """ method = getattr(module_or_class, name) opts: HookspecOpts | None = getattr(method, self.project_name + "_spec", None) return opts def get_plugins(self) -> set[Any]: """Return a set of all registered plugin objects.""" return set(self._name2plugin.values()) def is_registered(self, plugin: _Plugin) -> bool: """Return whether the plugin is already registered.""" return any(plugin == val for val in self._name2plugin.values()) def get_canonical_name(self, plugin: _Plugin) -> str: """Return a canonical name for a plugin object. Note that a plugin may be registered under a different name specified by the caller of :meth:`register(plugin, name) `. To obtain the name of a registered plugin use :meth:`get_name(plugin) ` instead. """ name: str | None = getattr(plugin, "__name__", None) return name or str(id(plugin)) def get_plugin(self, name: str) -> Any | None: """Return the plugin registered under the given name, if any.""" return self._name2plugin.get(name) def has_plugin(self, name: str) -> bool: """Return whether a plugin with the given name is registered.""" return self.get_plugin(name) is not None def get_name(self, plugin: _Plugin) -> str | None: """Return the name the plugin is registered under, or ``None`` if is isn't.""" for name, val in self._name2plugin.items(): if plugin == val: return name return None def _verify_hook(self, hook: HookCaller, hookimpl: HookImpl) -> None: if hook.is_historic() and (hookimpl.hookwrapper or hookimpl.wrapper): raise PluginValidationError( hookimpl.plugin, "Plugin %r\nhook %r\nhistoric incompatible with yield/wrapper/hookwrapper" % (hookimpl.plugin_name, hook.name), ) assert hook.spec is not None if hook.spec.warn_on_impl: _warn_for_function(hook.spec.warn_on_impl, hookimpl.function) # positional arg checking notinspec = set(hookimpl.argnames) - set(hook.spec.argnames) if notinspec: raise PluginValidationError( hookimpl.plugin, "Plugin %r for hook %r\nhookimpl definition: %s\n" "Argument(s) %s are declared in the hookimpl but " "can not be found in the hookspec" % ( hookimpl.plugin_name, hook.name, _formatdef(hookimpl.function), notinspec, ), ) if ( hookimpl.wrapper or hookimpl.hookwrapper ) and not inspect.isgeneratorfunction(hookimpl.function): raise PluginValidationError( hookimpl.plugin, "Plugin %r for hook %r\nhookimpl definition: %s\n" "Declared as wrapper=True or hookwrapper=True " "but function is not a generator function" % (hookimpl.plugin_name, hook.name, _formatdef(hookimpl.function)), ) if hookimpl.wrapper and hookimpl.hookwrapper: raise PluginValidationError( hookimpl.plugin, "Plugin %r for hook %r\nhookimpl definition: %s\n" "The wrapper=True and hookwrapper=True options are mutually exclusive" % (hookimpl.plugin_name, hook.name, _formatdef(hookimpl.function)), ) def check_pending(self) -> None: """Verify that all hooks which have not been verified against a hook specification are optional, otherwise raise :exc:`PluginValidationError`.""" for name in self.hook.__dict__: if name[0] != "_": hook: HookCaller = getattr(self.hook, name) if not hook.has_spec(): for hookimpl in hook.get_hookimpls(): if not hookimpl.optionalhook: raise PluginValidationError( hookimpl.plugin, "unknown hook %r in plugin %r" % (name, hookimpl.plugin), ) def load_setuptools_entrypoints(self, group: str, name: str | None = None) -> int: """Load modules from querying the specified setuptools ``group``. :param group: Entry point group to load plugins. :param name: If given, loads only plugins with the given ``name``. :return: The number of plugins loaded by this call. """ import importlib.metadata count = 0 for dist in list(importlib.metadata.distributions()): for ep in dist.entry_points: if ( ep.group != group or (name is not None and ep.name != name) # already registered or self.get_plugin(ep.name) or self.is_blocked(ep.name) ): continue plugin = ep.load() self.register(plugin, name=ep.name) self._plugin_distinfo.append((plugin, DistFacade(dist))) count += 1 return count def list_plugin_distinfo(self) -> list[tuple[_Plugin, DistFacade]]: """Return a list of (plugin, distinfo) pairs for all setuptools-registered plugins.""" return list(self._plugin_distinfo) def list_name_plugin(self) -> list[tuple[str, _Plugin]]: """Return a list of (name, plugin) pairs for all registered plugins.""" return list(self._name2plugin.items()) def get_hookcallers(self, plugin: _Plugin) -> list[HookCaller] | None: """Get all hook callers for the specified plugin. :returns: The hook callers, or ``None`` if ``plugin`` is not registered in this plugin manager. """ if self.get_name(plugin) is None: return None hookcallers = [] for hookcaller in self.hook.__dict__.values(): for hookimpl in hookcaller.get_hookimpls(): if hookimpl.plugin is plugin: hookcallers.append(hookcaller) return hookcallers def add_hookcall_monitoring( self, before: _BeforeTrace, after: _AfterTrace ) -> Callable[[], None]: """Add before/after tracing functions for all hooks. Returns an undo function which, when called, removes the added tracers. ``before(hook_name, hook_impls, kwargs)`` will be called ahead of all hook calls and receive a hookcaller instance, a list of HookImpl instances and the keyword arguments for the hook call. ``after(outcome, hook_name, hook_impls, kwargs)`` receives the same arguments as ``before`` but also a :class:`~pluggy.Result` object which represents the result of the overall hook call. """ oldcall = self._inner_hookexec def traced_hookexec( hook_name: str, hook_impls: Sequence[HookImpl], caller_kwargs: Mapping[str, object], firstresult: bool, ) -> object | list[object]: before(hook_name, hook_impls, caller_kwargs) outcome = Result.from_call( lambda: oldcall(hook_name, hook_impls, caller_kwargs, firstresult) ) after(outcome, hook_name, hook_impls, caller_kwargs) return outcome.get_result() self._inner_hookexec = traced_hookexec def undo() -> None: self._inner_hookexec = oldcall return undo def enable_tracing(self) -> Callable[[], None]: """Enable tracing of hook calls. Returns an undo function which, when called, removes the added tracing. """ hooktrace = self.trace.root.get("hook") def before( hook_name: str, methods: Sequence[HookImpl], kwargs: Mapping[str, object] ) -> None: hooktrace.root.indent += 1 hooktrace(hook_name, kwargs) def after( outcome: Result[object], hook_name: str, methods: Sequence[HookImpl], kwargs: Mapping[str, object], ) -> None: if outcome.exception is None: hooktrace("finish", hook_name, "-->", outcome.get_result()) hooktrace.root.indent -= 1 return self.add_hookcall_monitoring(before, after) def subset_hook_caller( self, name: str, remove_plugins: Iterable[_Plugin] ) -> HookCaller: """Return a proxy :class:`~pluggy.HookCaller` instance for the named method which manages calls to all registered plugins except the ones from remove_plugins.""" orig: HookCaller = getattr(self.hook, name) plugins_to_remove = {plug for plug in remove_plugins if hasattr(plug, name)} if plugins_to_remove: return _SubsetHookCaller(orig, plugins_to_remove) return orig def _formatdef(func: Callable[..., object]) -> str: return f"{func.__name__}{inspect.signature(func)}" pluggy-1.4.0/src/pluggy/_result.py000066400000000000000000000054401455415125700171640ustar00rootroot00000000000000""" Hook wrapper "result" utilities. """ from __future__ import annotations from types import TracebackType from typing import Callable from typing import cast from typing import final from typing import Generic from typing import Optional from typing import Tuple from typing import Type from typing import TypeVar _ExcInfo = Tuple[Type[BaseException], BaseException, Optional[TracebackType]] ResultType = TypeVar("ResultType") class HookCallError(Exception): """Hook was called incorrectly.""" @final class Result(Generic[ResultType]): """An object used to inspect and set the result in a :ref:`hook wrapper `.""" __slots__ = ("_result", "_exception") def __init__( self, result: ResultType | None, exception: BaseException | None, ) -> None: """:meta private:""" self._result = result self._exception = exception @property def excinfo(self) -> _ExcInfo | None: """:meta private:""" exc = self._exception if exc is None: return None else: return (type(exc), exc, exc.__traceback__) @property def exception(self) -> BaseException | None: """:meta private:""" return self._exception @classmethod def from_call(cls, func: Callable[[], ResultType]) -> Result[ResultType]: """:meta private:""" __tracebackhide__ = True result = exception = None try: result = func() except BaseException as exc: exception = exc return cls(result, exception) def force_result(self, result: ResultType) -> None: """Force the result(s) to ``result``. If the hook was marked as a ``firstresult`` a single value should be set, otherwise set a (modified) list of results. Any exceptions found during invocation will be deleted. This overrides any previous result or exception. """ self._result = result self._exception = None def force_exception(self, exception: BaseException) -> None: """Force the result to fail with ``exception``. This overrides any previous result or exception. .. versionadded:: 1.1.0 """ self._result = None self._exception = exception def get_result(self) -> ResultType: """Get the result(s) for this hook call. If the hook was marked as a ``firstresult`` only a single value will be returned, otherwise a list of results. """ __tracebackhide__ = True exc = self._exception if exc is None: return cast(ResultType, self._result) else: raise exc.with_traceback(exc.__traceback__) # Historical name (pluggy<=1.2), kept for backward compatibility. _Result = Result pluggy-1.4.0/src/pluggy/_tracing.py000066400000000000000000000040501455415125700172710ustar00rootroot00000000000000""" Tracing utils """ from __future__ import annotations from typing import Any from typing import Callable from typing import Sequence from typing import Tuple _Writer = Callable[[str], object] _Processor = Callable[[Tuple[str, ...], Tuple[Any, ...]], object] class TagTracer: def __init__(self) -> None: self._tags2proc: dict[tuple[str, ...], _Processor] = {} self._writer: _Writer | None = None self.indent = 0 def get(self, name: str) -> TagTracerSub: return TagTracerSub(self, (name,)) def _format_message(self, tags: Sequence[str], args: Sequence[object]) -> str: if isinstance(args[-1], dict): extra = args[-1] args = args[:-1] else: extra = {} content = " ".join(map(str, args)) indent = " " * self.indent lines = ["{}{} [{}]\n".format(indent, content, ":".join(tags))] for name, value in extra.items(): lines.append(f"{indent} {name}: {value}\n") return "".join(lines) def _processmessage(self, tags: tuple[str, ...], args: tuple[object, ...]) -> None: if self._writer is not None and args: self._writer(self._format_message(tags, args)) try: processor = self._tags2proc[tags] except KeyError: pass else: processor(tags, args) def setwriter(self, writer: _Writer | None) -> None: self._writer = writer def setprocessor(self, tags: str | tuple[str, ...], processor: _Processor) -> None: if isinstance(tags, str): tags = tuple(tags.split(":")) else: assert isinstance(tags, tuple) self._tags2proc[tags] = processor class TagTracerSub: def __init__(self, root: TagTracer, tags: tuple[str, ...]) -> None: self.root = root self.tags = tags def __call__(self, *args: object) -> None: self.root._processmessage(self.tags, args) def get(self, name: str) -> TagTracerSub: return self.__class__(self.root, self.tags + (name,)) pluggy-1.4.0/src/pluggy/_warnings.py000066400000000000000000000014741455415125700175010ustar00rootroot00000000000000from typing import final class PluggyWarning(UserWarning): """Base class for all warnings emitted by pluggy.""" __module__ = "pluggy" @final class PluggyTeardownRaisedWarning(PluggyWarning): """A plugin raised an exception during an :ref:`old-style hookwrapper ` teardown. Such exceptions are not handled by pluggy, and may cause subsequent teardowns to be executed at unexpected times, or be skipped entirely. This is an issue in the plugin implementation. If the exception is unintended, fix the underlying cause. If the exception is intended, switch to :ref:`new-style hook wrappers `, or use :func:`result.force_exception() ` to set the exception instead of raising. """ __module__ = "pluggy" pluggy-1.4.0/src/pluggy/py.typed000066400000000000000000000000001455415125700166170ustar00rootroot00000000000000pluggy-1.4.0/testing/000077500000000000000000000000001455415125700145115ustar00rootroot00000000000000pluggy-1.4.0/testing/benchmark.py000066400000000000000000000047541455415125700170270ustar00rootroot00000000000000""" Benchmarking and performance tests. """ import pytest from pluggy import HookimplMarker from pluggy import HookspecMarker from pluggy import PluginManager from pluggy._callers import _multicall from pluggy._hooks import HookImpl hookspec = HookspecMarker("example") hookimpl = HookimplMarker("example") @hookimpl def hook(arg1, arg2, arg3): return arg1, arg2, arg3 @hookimpl(wrapper=True) def wrapper(arg1, arg2, arg3): return (yield) @pytest.fixture(params=[10, 100], ids="hooks={}".format) def hooks(request): return [hook for i in range(request.param)] @pytest.fixture(params=[10, 100], ids="wrappers={}".format) def wrappers(request): return [wrapper for i in range(request.param)] def test_hook_and_wrappers_speed(benchmark, hooks, wrappers): def setup(): hook_name = "foo" hook_impls = [] for method in hooks + wrappers: f = HookImpl(None, "", method, method.example_impl) hook_impls.append(f) caller_kwargs = {"arg1": 1, "arg2": 2, "arg3": 3} firstresult = False return (hook_name, hook_impls, caller_kwargs, firstresult), {} benchmark.pedantic(_multicall, setup=setup, rounds=10) @pytest.mark.parametrize( ("plugins, wrappers, nesting"), [ (1, 1, 0), (1, 1, 1), (1, 1, 5), (1, 5, 1), (1, 5, 5), (5, 1, 1), (5, 1, 5), (5, 5, 1), (5, 5, 5), (20, 20, 0), (100, 100, 0), ], ) def test_call_hook(benchmark, plugins, wrappers, nesting): pm = PluginManager("example") class HookSpec: @hookspec def fun(self, hooks, nesting: int): pass class Plugin: def __init__(self, num: int) -> None: self.num = num def __repr__(self) -> str: return f"" @hookimpl def fun(self, hooks, nesting: int) -> None: if nesting: hooks.fun(hooks=hooks, nesting=nesting - 1) class PluginWrap: def __init__(self, num: int) -> None: self.num = num def __repr__(self) -> str: return f"" @hookimpl(wrapper=True) def fun(self): return (yield) pm.add_hookspecs(HookSpec) for i in range(plugins): pm.register(Plugin(i), name=f"plug_{i}") for i in range(wrappers): pm.register(PluginWrap(i), name=f"wrap_plug_{i}") benchmark(pm.hook.fun, hooks=pm.hook, nesting=nesting) pluggy-1.4.0/testing/conftest.py000066400000000000000000000010451455415125700167100ustar00rootroot00000000000000import pytest from pluggy import HookspecMarker from pluggy import PluginManager @pytest.fixture( params=[lambda spec: spec, lambda spec: spec()], ids=["spec-is-class", "spec-is-instance"], ) def he_pm(request, pm: PluginManager) -> PluginManager: hookspec = HookspecMarker("example") class Hooks: @hookspec def he_method1(self, arg: int) -> int: return arg + 1 pm.add_hookspecs(request.param(Hooks)) return pm @pytest.fixture def pm() -> PluginManager: return PluginManager("example") pluggy-1.4.0/testing/test_details.py000066400000000000000000000104441455415125700175520ustar00rootroot00000000000000import pytest from pluggy import HookimplMarker from pluggy import HookspecMarker from pluggy import PluginManager hookspec = HookspecMarker("example") hookimpl = HookimplMarker("example") def test_parse_hookimpl_override() -> None: class MyPluginManager(PluginManager): def parse_hookimpl_opts(self, module_or_class, name): opts = PluginManager.parse_hookimpl_opts(self, module_or_class, name) if opts is None: if name.startswith("x1"): opts = {} # type: ignore[assignment] return opts class Plugin: def x1meth(self): pass @hookimpl(hookwrapper=True, tryfirst=True) def x1meth2(self): yield # pragma: no cover @hookimpl(wrapper=True, trylast=True) def x1meth3(self): return (yield) # pragma: no cover class Spec: @hookspec def x1meth(self): pass @hookspec def x1meth2(self): pass @hookspec def x1meth3(self): pass pm = MyPluginManager(hookspec.project_name) pm.register(Plugin()) pm.add_hookspecs(Spec) hookimpls = pm.hook.x1meth.get_hookimpls() assert len(hookimpls) == 1 assert not hookimpls[0].hookwrapper assert not hookimpls[0].wrapper assert not hookimpls[0].tryfirst assert not hookimpls[0].trylast assert not hookimpls[0].optionalhook hookimpls = pm.hook.x1meth2.get_hookimpls() assert len(hookimpls) == 1 assert hookimpls[0].hookwrapper assert not hookimpls[0].wrapper assert hookimpls[0].tryfirst hookimpls = pm.hook.x1meth3.get_hookimpls() assert len(hookimpls) == 1 assert not hookimpls[0].hookwrapper assert hookimpls[0].wrapper assert not hookimpls[0].tryfirst assert hookimpls[0].trylast def test_warn_when_deprecated_specified(recwarn) -> None: warning = DeprecationWarning("foo is deprecated") class Spec: @hookspec(warn_on_impl=warning) def foo(self): pass class Plugin: @hookimpl def foo(self): pass pm = PluginManager(hookspec.project_name) pm.add_hookspecs(Spec) with pytest.warns(DeprecationWarning) as records: pm.register(Plugin()) (record,) = records assert record.message is warning assert record.filename == Plugin.foo.__code__.co_filename assert record.lineno == Plugin.foo.__code__.co_firstlineno def test_plugin_getattr_raises_errors() -> None: """Pluggy must be able to handle plugins which raise weird exceptions when getattr() gets called (#11). """ class DontTouchMe: def __getattr__(self, x): raise Exception("can't touch me") class Module: pass module = Module() module.x = DontTouchMe() # type: ignore[attr-defined] pm = PluginManager(hookspec.project_name) # register() would raise an error pm.register(module, "donttouch") assert pm.get_plugin("donttouch") is module def test_not_all_arguments_are_provided_issues_a_warning(pm: PluginManager) -> None: """Calling a hook without providing all arguments specified in the hook spec issues a warning.""" class Spec: @hookspec def hello(self, arg1, arg2): pass @hookspec(historic=True) def herstory(self, arg1, arg2): pass pm.add_hookspecs(Spec) with pytest.warns(UserWarning, match=r"'arg1', 'arg2'.*cannot be found.*$"): pm.hook.hello() with pytest.warns(UserWarning, match=r"'arg2'.*cannot be found.*$"): pm.hook.hello(arg1=1) with pytest.warns(UserWarning, match=r"'arg1'.*cannot be found.*$"): pm.hook.hello(arg2=2) with pytest.warns(UserWarning, match=r"'arg1', 'arg2'.*cannot be found.*$"): pm.hook.hello.call_extra([], kwargs=dict()) with pytest.warns(UserWarning, match=r"'arg1', 'arg2'.*cannot be found.*$"): pm.hook.herstory.call_historic(kwargs=dict()) def test_repr() -> None: class Plugin: @hookimpl def myhook(self): raise NotImplementedError() pm = PluginManager(hookspec.project_name) plugin = Plugin() pname = pm.register(plugin) assert repr(pm.hook.myhook.get_hookimpls()[0]) == ( f"" ) pluggy-1.4.0/testing/test_helpers.py000066400000000000000000000046001455415125700175640ustar00rootroot00000000000000from functools import wraps from typing import Any from typing import Callable from typing import cast from typing import TypeVar from pluggy._hooks import varnames from pluggy._manager import _formatdef def test_varnames() -> None: def f(x) -> None: i = 3 # noqa class A: def f(self, y) -> None: pass class B: def __call__(self, z) -> None: pass assert varnames(f) == (("x",), ()) assert varnames(A().f) == (("y",), ()) assert varnames(B()) == (("z",), ()) def test_varnames_default() -> None: def f(x, y=3) -> None: pass assert varnames(f) == (("x",), ("y",)) def test_varnames_class() -> None: class C: def __init__(self, x) -> None: pass class D: pass class E: def __init__(self, x) -> None: pass class F: pass assert varnames(C) == (("x",), ()) assert varnames(D) == ((), ()) assert varnames(E) == (("x",), ()) assert varnames(F) == ((), ()) def test_varnames_keyword_only() -> None: def f1(x, *, y) -> None: pass def f2(x, *, y=3) -> None: pass def f3(x=1, *, y=3) -> None: pass assert varnames(f1) == (("x",), ()) assert varnames(f2) == (("x",), ()) assert varnames(f3) == ((), ("x",)) def test_formatdef() -> None: def function1(): pass assert _formatdef(function1) == "function1()" def function2(arg1): pass assert _formatdef(function2) == "function2(arg1)" def function3(arg1, arg2="qwe"): pass assert _formatdef(function3) == "function3(arg1, arg2='qwe')" def function4(arg1, *args, **kwargs): pass assert _formatdef(function4) == "function4(arg1, *args, **kwargs)" def test_varnames_decorator() -> None: F = TypeVar("F", bound=Callable[..., Any]) def my_decorator(func: F) -> F: @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return cast(F, wrapper) @my_decorator def example(a, b=123) -> None: pass class Example: @my_decorator def example_method(self, x, y=1) -> None: pass ex_inst = Example() assert varnames(example) == (("a",), ("b",)) assert varnames(Example.example_method) == (("x",), ("y",)) assert varnames(ex_inst.example_method) == (("x",), ("y",)) pluggy-1.4.0/testing/test_hookcaller.py000066400000000000000000000274551455415125700202620ustar00rootroot00000000000000from typing import Callable from typing import Generator from typing import List from typing import Sequence from typing import TypeVar import pytest from pluggy import HookimplMarker from pluggy import HookspecMarker from pluggy import PluginManager from pluggy import PluginValidationError from pluggy._hooks import HookCaller from pluggy._hooks import HookImpl hookspec = HookspecMarker("example") hookimpl = HookimplMarker("example") @pytest.fixture def hc(pm: PluginManager) -> HookCaller: class Hooks: @hookspec def he_method1(self, arg: object) -> None: pass pm.add_hookspecs(Hooks) return pm.hook.he_method1 FuncT = TypeVar("FuncT", bound=Callable[..., object]) class AddMeth: def __init__(self, hc: HookCaller) -> None: self.hc = hc def __call__( self, tryfirst: bool = False, trylast: bool = False, hookwrapper: bool = False, wrapper: bool = False, ) -> Callable[[FuncT], FuncT]: def wrap(func: FuncT) -> FuncT: hookimpl( tryfirst=tryfirst, trylast=trylast, hookwrapper=hookwrapper, wrapper=wrapper, )(func) self.hc._add_hookimpl( HookImpl(None, "", func, func.example_impl), # type: ignore[attr-defined] ) return func return wrap @pytest.fixture def addmeth(hc: HookCaller) -> AddMeth: return AddMeth(hc) def funcs(hookmethods: Sequence[HookImpl]) -> List[Callable[..., object]]: return [hookmethod.function for hookmethod in hookmethods] def test_adding_nonwrappers(hc: HookCaller, addmeth: AddMeth) -> None: @addmeth() def he_method1() -> None: pass @addmeth() def he_method2() -> None: pass @addmeth() def he_method3() -> None: pass assert funcs(hc.get_hookimpls()) == [he_method1, he_method2, he_method3] def test_adding_nonwrappers_trylast(hc: HookCaller, addmeth: AddMeth) -> None: @addmeth() def he_method1_middle() -> None: pass @addmeth(trylast=True) def he_method1() -> None: pass @addmeth() def he_method1_b() -> None: pass assert funcs(hc.get_hookimpls()) == [he_method1, he_method1_middle, he_method1_b] def test_adding_nonwrappers_trylast3(hc: HookCaller, addmeth: AddMeth) -> None: @addmeth() def he_method1_a() -> None: pass @addmeth(trylast=True) def he_method1_b() -> None: pass @addmeth() def he_method1_c() -> None: pass @addmeth(trylast=True) def he_method1_d() -> None: pass assert funcs(hc.get_hookimpls()) == [ he_method1_d, he_method1_b, he_method1_a, he_method1_c, ] def test_adding_nonwrappers_trylast2(hc: HookCaller, addmeth: AddMeth) -> None: @addmeth() def he_method1_middle() -> None: pass @addmeth() def he_method1_b() -> None: pass @addmeth(trylast=True) def he_method1() -> None: pass assert funcs(hc.get_hookimpls()) == [he_method1, he_method1_middle, he_method1_b] def test_adding_nonwrappers_tryfirst(hc: HookCaller, addmeth: AddMeth) -> None: @addmeth(tryfirst=True) def he_method1() -> None: pass @addmeth() def he_method1_middle() -> None: pass @addmeth() def he_method1_b() -> None: pass assert funcs(hc.get_hookimpls()) == [he_method1_middle, he_method1_b, he_method1] def test_adding_wrappers_ordering(hc: HookCaller, addmeth: AddMeth) -> None: @addmeth(hookwrapper=True) def he_method1(): yield @addmeth(wrapper=True) def he_method1_fun(): yield @addmeth() def he_method1_middle(): return @addmeth(hookwrapper=True) def he_method3_fun(): yield @addmeth(hookwrapper=True) def he_method3(): yield assert funcs(hc.get_hookimpls()) == [ he_method1_middle, he_method1, he_method1_fun, he_method3_fun, he_method3, ] def test_adding_wrappers_ordering_tryfirst(hc: HookCaller, addmeth: AddMeth) -> None: @addmeth(hookwrapper=True, tryfirst=True) def he_method1(): yield @addmeth(hookwrapper=True) def he_method2(): yield @addmeth(wrapper=True, tryfirst=True) def he_method3(): yield assert funcs(hc.get_hookimpls()) == [he_method2, he_method1, he_method3] def test_adding_wrappers_complex(hc: HookCaller, addmeth: AddMeth) -> None: assert funcs(hc.get_hookimpls()) == [] @addmeth(hookwrapper=True, trylast=True) def m1(): yield assert funcs(hc.get_hookimpls()) == [m1] @addmeth() def m2() -> None: ... assert funcs(hc.get_hookimpls()) == [m2, m1] @addmeth(trylast=True) def m3() -> None: ... assert funcs(hc.get_hookimpls()) == [m3, m2, m1] @addmeth(hookwrapper=True) def m4() -> None: ... assert funcs(hc.get_hookimpls()) == [m3, m2, m1, m4] @addmeth(wrapper=True, tryfirst=True) def m5(): yield assert funcs(hc.get_hookimpls()) == [m3, m2, m1, m4, m5] @addmeth(tryfirst=True) def m6() -> None: ... assert funcs(hc.get_hookimpls()) == [m3, m2, m6, m1, m4, m5] @addmeth() def m7() -> None: ... assert funcs(hc.get_hookimpls()) == [m3, m2, m7, m6, m1, m4, m5] @addmeth(wrapper=True) def m8(): yield assert funcs(hc.get_hookimpls()) == [m3, m2, m7, m6, m1, m4, m8, m5] @addmeth(trylast=True) def m9() -> None: ... assert funcs(hc.get_hookimpls()) == [m9, m3, m2, m7, m6, m1, m4, m8, m5] @addmeth(tryfirst=True) def m10() -> None: ... assert funcs(hc.get_hookimpls()) == [m9, m3, m2, m7, m6, m10, m1, m4, m8, m5] @addmeth(hookwrapper=True, trylast=True) def m11() -> None: ... assert funcs(hc.get_hookimpls()) == [m9, m3, m2, m7, m6, m10, m11, m1, m4, m8, m5] @addmeth(wrapper=True) def m12(): yield assert funcs(hc.get_hookimpls()) == [ m9, m3, m2, m7, m6, m10, m11, m1, m4, m8, m12, m5, ] @addmeth() def m13() -> None: ... assert funcs(hc.get_hookimpls()) == [ m9, m3, m2, m7, m13, m6, m10, m11, m1, m4, m8, m12, m5, ] def test_hookspec(pm: PluginManager) -> None: class HookSpec: @hookspec() def he_myhook1(arg1) -> None: pass @hookspec(firstresult=True) def he_myhook2(arg1) -> None: pass @hookspec(firstresult=False) def he_myhook3(arg1) -> None: pass pm.add_hookspecs(HookSpec) assert pm.hook.he_myhook1.spec is not None assert not pm.hook.he_myhook1.spec.opts["firstresult"] assert pm.hook.he_myhook2.spec is not None assert pm.hook.he_myhook2.spec.opts["firstresult"] assert pm.hook.he_myhook3.spec is not None assert not pm.hook.he_myhook3.spec.opts["firstresult"] @pytest.mark.parametrize("name", ["hookwrapper", "optionalhook", "tryfirst", "trylast"]) @pytest.mark.parametrize("val", [True, False]) def test_hookimpl(name: str, val: bool) -> None: @hookimpl(**{name: val}) # type: ignore[misc,call-overload] def he_myhook1(arg1) -> None: pass if val: assert he_myhook1.example_impl.get(name) else: assert not hasattr(he_myhook1, name) def test_hookrelay_registry(pm: PluginManager) -> None: """Verify hook caller instances are registered by name onto the relay and can be likewise unregistered.""" class Api: @hookspec def hello(self, arg: object) -> None: "api hook 1" pm.add_hookspecs(Api) hook = pm.hook assert hasattr(hook, "hello") assert repr(hook.hello).find("hello") != -1 class Plugin: @hookimpl def hello(self, arg): return arg + 1 plugin = Plugin() pm.register(plugin) out = hook.hello(arg=3) assert out == [4] assert not hasattr(hook, "world") pm.unregister(plugin) assert hook.hello(arg=3) == [] def test_hookrelay_registration_by_specname(pm: PluginManager) -> None: """Verify hook caller instances may also be registered by specifying a specname option to the hookimpl""" class Api: @hookspec def hello(self, arg: object) -> None: "api hook 1" pm.add_hookspecs(Api) hook = pm.hook assert hasattr(hook, "hello") assert len(pm.hook.hello.get_hookimpls()) == 0 class Plugin: @hookimpl(specname="hello") def foo(self, arg: int) -> int: return arg + 1 plugin = Plugin() pm.register(plugin) out = hook.hello(arg=3) assert out == [4] def test_hookrelay_registration_by_specname_raises(pm: PluginManager) -> None: """Verify using specname still raises the types of errors during registration as it would have without using specname.""" class Api: @hookspec def hello(self, arg: object) -> None: "api hook 1" pm.add_hookspecs(Api) # make sure a bad signature still raises an error when using specname class Plugin: @hookimpl(specname="hello") def foo(self, arg: int, too, many, args) -> int: return arg + 1 with pytest.raises(PluginValidationError): pm.register(Plugin()) # make sure check_pending still fails if specname doesn't have a # corresponding spec. EVEN if the function name matches one. class Plugin2: @hookimpl(specname="bar") def hello(self, arg: int) -> int: return arg + 1 pm.register(Plugin2()) with pytest.raises(PluginValidationError): pm.check_pending() def test_hook_conflict(pm: PluginManager) -> None: class Api1: @hookspec def conflict(self) -> None: """Api1 hook""" class Api2: @hookspec def conflict(self) -> None: """Api2 hook""" pm.add_hookspecs(Api1) with pytest.raises(ValueError) as exc: pm.add_hookspecs(Api2) assert str(exc.value) == ( "Hook 'conflict' is already registered within namespace " ".Api1'>" ) def test_call_extra_hook_order(hc: HookCaller, addmeth: AddMeth) -> None: """Ensure that call_extra is calling hooks in the right order.""" order = [] @addmeth(tryfirst=True) def method1() -> str: order.append("1") return "1" @addmeth() def method2() -> str: order.append("2") return "2" @addmeth(trylast=True) def method3() -> str: order.append("3") return "3" @addmeth(wrapper=True, tryfirst=True) def method4() -> Generator[None, str, str]: order.append("4pre") result = yield order.append("4post") return result @addmeth(wrapper=True) def method5() -> Generator[None, str, str]: order.append("5pre") result = yield order.append("5post") return result @addmeth(wrapper=True, trylast=True) def method6() -> Generator[None, str, str]: order.append("6pre") result = yield order.append("6post") return result def extra1() -> str: order.append("extra1") return "extra1" def extra2() -> str: order.append("extra2") return "extra2" result = hc.call_extra([extra1, extra2], {"arg": "test"}) assert order == [ "4pre", "5pre", "6pre", "1", "extra2", "extra1", "2", "3", "6post", "5post", "4post", ] assert result == [ "1", "extra2", "extra1", "2", "3", ] pluggy-1.4.0/testing/test_invocations.py000066400000000000000000000174261455415125700204700ustar00rootroot00000000000000from typing import Iterator import pytest from pluggy import HookimplMarker from pluggy import HookspecMarker from pluggy import PluginManager from pluggy import PluginValidationError hookspec = HookspecMarker("example") hookimpl = HookimplMarker("example") def test_argmismatch(pm: PluginManager) -> None: class Api: @hookspec def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) class Plugin: @hookimpl def hello(self, argwrong): pass with pytest.raises(PluginValidationError) as exc: pm.register(Plugin()) assert "argwrong" in str(exc.value) def test_only_kwargs(pm: PluginManager) -> None: class Api: @hookspec def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) with pytest.raises(TypeError) as exc: pm.hook.hello(3) # type: ignore[call-arg] message = "__call__() takes 1 positional argument but 2 were given" assert message in str(exc.value) def test_opt_in_args(pm: PluginManager) -> None: """Verify that two hookimpls with mutex args can serve under the same spec. """ class Api: @hookspec def hello(self, arg1, arg2, common_arg): "api hook 1" class Plugin1: @hookimpl def hello(self, arg1, common_arg): return arg1 + common_arg class Plugin2: @hookimpl def hello(self, arg2, common_arg): return arg2 + common_arg pm.add_hookspecs(Api) pm.register(Plugin1()) pm.register(Plugin2()) results = pm.hook.hello(arg1=1, arg2=2, common_arg=0) assert results == [2, 1] def test_call_order(pm: PluginManager) -> None: class Api: @hookspec def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) class Plugin1: @hookimpl def hello(self, arg): return 1 class Plugin2: @hookimpl def hello(self, arg): return 2 class Plugin3: @hookimpl def hello(self, arg): return 3 class Plugin4: @hookimpl(hookwrapper=True) def hello(self, arg): assert arg == 0 outcome = yield assert outcome.get_result() == [3, 2, 1] assert outcome.exception is None assert outcome.excinfo is None class Plugin5: @hookimpl(wrapper=True) def hello(self, arg): assert arg == 0 result = yield assert result == [3, 2, 1] return result pm.register(Plugin1()) pm.register(Plugin2()) pm.register(Plugin3()) pm.register(Plugin4()) # hookwrapper should get same list result pm.register(Plugin5()) # hookwrapper should get same list result res = pm.hook.hello(arg=0) assert res == [3, 2, 1] def test_firstresult_definition(pm: PluginManager) -> None: class Api: @hookspec(firstresult=True) def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) class Plugin1: @hookimpl def hello(self, arg): return arg + 1 class Plugin2: @hookimpl def hello(self, arg): return arg - 1 class Plugin3: @hookimpl def hello(self, arg): return None class Plugin4: @hookimpl(wrapper=True) def hello(self, arg): assert arg == 3 outcome = yield assert outcome == 2 return outcome class Plugin5: @hookimpl(hookwrapper=True) def hello(self, arg): assert arg == 3 outcome = yield assert outcome.get_result() == 2 pm.register(Plugin1()) # discarded - not the last registered plugin pm.register(Plugin2()) # used as result pm.register(Plugin3()) # None result is ignored pm.register(Plugin4()) # wrapper should get same non-list result pm.register(Plugin5()) # hookwrapper should get same non-list result res = pm.hook.hello(arg=3) assert res == 2 def test_firstresult_force_result_hookwrapper(pm: PluginManager) -> None: """Verify forcing a result in a wrapper.""" class Api: @hookspec(firstresult=True) def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) class Plugin1: @hookimpl def hello(self, arg): return arg + 1 class Plugin2: @hookimpl(hookwrapper=True) def hello(self, arg): assert arg == 3 outcome = yield assert outcome.get_result() == 4 outcome.force_result(0) class Plugin3: @hookimpl def hello(self, arg): return None pm.register(Plugin1()) pm.register(Plugin2()) # wrapper pm.register(Plugin3()) # ignored since returns None res = pm.hook.hello(arg=3) assert res == 0 # this result is forced and not a list def test_firstresult_force_result(pm: PluginManager) -> None: """Verify forcing a result in a wrapper.""" class Api: @hookspec(firstresult=True) def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) class Plugin1: @hookimpl def hello(self, arg): return arg + 1 class Plugin2: @hookimpl(wrapper=True) def hello(self, arg): assert arg == 3 outcome = yield assert outcome == 4 return 0 class Plugin3: @hookimpl def hello(self, arg): return None pm.register(Plugin1()) pm.register(Plugin2()) # wrapper pm.register(Plugin3()) # ignored since returns None res = pm.hook.hello(arg=3) assert res == 0 # this result is forced and not a list def test_firstresult_returns_none(pm: PluginManager) -> None: """If None results are returned by underlying implementations ensure the multi-call loop returns a None value. """ class Api: @hookspec(firstresult=True) def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) class Plugin1: @hookimpl def hello(self, arg): return None pm.register(Plugin1()) res = pm.hook.hello(arg=3) assert res is None def test_firstresult_no_plugin(pm: PluginManager) -> None: """If no implementations/plugins have been registered for a firstresult hook the multi-call loop should return a None value. """ class Api: @hookspec(firstresult=True) def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) res = pm.hook.hello(arg=3) assert res is None def test_no_hookspec(pm: PluginManager) -> None: """A hook with hookimpls can still be called even if no hookspec was registered for it (and call_pending wasn't called to check against it). """ class Plugin: @hookimpl def hello(self, arg): return "Plugin.hello" pm.register(Plugin()) assert pm.hook.hello(arg=10, extra=20) == ["Plugin.hello"] def test_non_wrapper_generator(pm: PluginManager) -> None: """A hookimpl can be a generator without being a wrapper, meaning it returns an iterator result.""" class Api: @hookspec def hello(self) -> Iterator[int]: raise NotImplementedError() pm.add_hookspecs(Api) class Plugin1: @hookimpl def hello(self): yield 1 class Plugin2: @hookimpl def hello(self): yield 2 yield 3 class Plugin3: @hookimpl(wrapper=True) def hello(self): return (yield) pm.register(Plugin1()) pm.register(Plugin2()) # wrapper res = pm.hook.hello() assert [y for x in res for y in x] == [2, 3, 1] pm.register(Plugin3()) res = pm.hook.hello() assert [y for x in res for y in x] == [2, 3, 1] pluggy-1.4.0/testing/test_multicall.py000066400000000000000000000232141455415125700201120ustar00rootroot00000000000000from typing import Callable from typing import List from typing import Mapping from typing import Sequence from typing import Type from typing import Union import pytest from pluggy import HookCallError from pluggy import HookimplMarker from pluggy import HookspecMarker from pluggy._callers import _multicall from pluggy._hooks import HookImpl hookspec = HookspecMarker("example") hookimpl = HookimplMarker("example") def MC( methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object], firstresult: bool = False, ) -> Union[object, List[object]]: caller = _multicall hookfuncs = [] for method in methods: f = HookImpl(None, "", method, method.example_impl) # type: ignore[attr-defined] hookfuncs.append(f) return caller("foo", hookfuncs, kwargs, firstresult) def test_keyword_args() -> None: @hookimpl def f(x): return x + 1 class A: @hookimpl def f(self, x, y): return x + y reslist = MC([f, A().f], dict(x=23, y=24)) assert reslist == [24 + 23, 24] def test_keyword_args_with_defaultargs() -> None: @hookimpl def f(x, z=1): return x + z reslist = MC([f], dict(x=23, y=24)) assert reslist == [24] def test_tags_call_error() -> None: @hookimpl def f(x): return x with pytest.raises(HookCallError): MC([f], {}) def test_call_none_is_no_result() -> None: @hookimpl def m1(): return 1 @hookimpl def m2(): return None res = MC([m1, m2], {}, firstresult=True) assert res == 1 res = MC([m1, m2], {}, firstresult=False) assert res == [1] def test_hookwrapper() -> None: out = [] @hookimpl(hookwrapper=True) def m1(): out.append("m1 init") yield None out.append("m1 finish") @hookimpl def m2(): out.append("m2") return 2 res = MC([m2, m1], {}) assert res == [2] assert out == ["m1 init", "m2", "m1 finish"] out[:] = [] res = MC([m2, m1], {}, firstresult=True) assert res == 2 assert out == ["m1 init", "m2", "m1 finish"] def test_hookwrapper_two_yields() -> None: @hookimpl(hookwrapper=True) def m(): yield yield with pytest.raises(RuntimeError, match="has second yield"): MC([m], {}) def test_wrapper() -> None: out = [] @hookimpl(wrapper=True) def m1(): out.append("m1 init") result = yield out.append("m1 finish") return result * 2 @hookimpl def m2(): out.append("m2") return 2 res = MC([m2, m1], {}) assert res == [2, 2] assert out == ["m1 init", "m2", "m1 finish"] out[:] = [] res = MC([m2, m1], {}, firstresult=True) assert res == 4 assert out == ["m1 init", "m2", "m1 finish"] def test_wrapper_two_yields() -> None: @hookimpl(wrapper=True) def m(): yield yield with pytest.raises(RuntimeError, match="has second yield"): MC([m], {}) def test_hookwrapper_order() -> None: out = [] @hookimpl(hookwrapper=True) def m1(): out.append("m1 init") yield 1 out.append("m1 finish") @hookimpl(wrapper=True) def m2(): out.append("m2 init") result = yield 2 out.append("m2 finish") return result @hookimpl(hookwrapper=True) def m3(): out.append("m3 init") yield 3 out.append("m3 finish") @hookimpl(hookwrapper=True) def m4(): out.append("m4 init") yield 4 out.append("m4 finish") res = MC([m4, m3, m2, m1], {}) assert res == [] assert out == [ "m1 init", "m2 init", "m3 init", "m4 init", "m4 finish", "m3 finish", "m2 finish", "m1 finish", ] def test_hookwrapper_not_yield() -> None: @hookimpl(hookwrapper=True) def m1(): pass with pytest.raises(TypeError): MC([m1], {}) def test_hookwrapper_yield_not_executed() -> None: @hookimpl(hookwrapper=True) def m1(): if False: yield # type: ignore[unreachable] with pytest.raises(RuntimeError, match="did not yield"): MC([m1], {}) def test_hookwrapper_too_many_yield() -> None: @hookimpl(hookwrapper=True) def m1(): yield 1 yield 2 with pytest.raises(RuntimeError) as ex: MC([m1], {}) assert "m1" in str(ex.value) assert (__file__ + ":") in str(ex.value) def test_wrapper_yield_not_executed() -> None: @hookimpl(wrapper=True) def m1(): if False: yield # type: ignore[unreachable] with pytest.raises(RuntimeError, match="did not yield"): MC([m1], {}) def test_wrapper_too_many_yield() -> None: out = [] @hookimpl(wrapper=True) def m1(): try: yield 1 yield 2 finally: out.append("cleanup") with pytest.raises(RuntimeError) as ex: try: MC([m1], {}) finally: out.append("finally") assert "m1" in str(ex.value) assert (__file__ + ":") in str(ex.value) assert out == ["cleanup", "finally"] @pytest.mark.parametrize("exc", [ValueError, SystemExit]) def test_hookwrapper_exception(exc: "Type[BaseException]") -> None: out = [] @hookimpl(hookwrapper=True) def m1(): out.append("m1 init") result = yield assert isinstance(result.exception, exc) assert result.excinfo[0] == exc out.append("m1 finish") @hookimpl def m2(): raise exc with pytest.raises(exc): MC([m2, m1], {}) assert out == ["m1 init", "m1 finish"] def test_hookwrapper_force_exception() -> None: out = [] @hookimpl(hookwrapper=True) def m1(): out.append("m1 init") result = yield try: result.get_result() except BaseException as exc: result.force_exception(exc) out.append("m1 finish") @hookimpl(hookwrapper=True) def m2(): out.append("m2 init") result = yield try: result.get_result() except BaseException as exc: new_exc = OSError("m2") new_exc.__cause__ = exc result.force_exception(new_exc) out.append("m2 finish") @hookimpl(hookwrapper=True) def m3(): out.append("m3 init") yield out.append("m3 finish") @hookimpl def m4(): raise ValueError("m4") with pytest.raises(OSError, match="m2") as excinfo: MC([m4, m3, m2, m1], {}) assert out == [ "m1 init", "m2 init", "m3 init", "m3 finish", "m2 finish", "m1 finish", ] assert excinfo.value.__cause__ is not None assert str(excinfo.value.__cause__) == "m4" @pytest.mark.parametrize("exc", [ValueError, SystemExit]) def test_wrapper_exception(exc: "Type[BaseException]") -> None: out = [] @hookimpl(wrapper=True) def m1(): out.append("m1 init") try: result = yield except BaseException as e: assert isinstance(e, exc) raise finally: out.append("m1 finish") return result @hookimpl def m2(): out.append("m2 init") raise exc with pytest.raises(exc): MC([m2, m1], {}) assert out == ["m1 init", "m2 init", "m1 finish"] def test_wrapper_exception_chaining() -> None: @hookimpl def m1(): raise Exception("m1") @hookimpl(wrapper=True) def m2(): try: yield except Exception: raise Exception("m2") @hookimpl(wrapper=True) def m3(): yield return 10 @hookimpl(wrapper=True) def m4(): try: yield except Exception as e: raise Exception("m4") from e with pytest.raises(Exception) as excinfo: MC([m1, m2, m3, m4], {}) assert str(excinfo.value) == "m4" assert excinfo.value.__cause__ is not None assert str(excinfo.value.__cause__) == "m2" assert excinfo.value.__cause__.__context__ is not None assert str(excinfo.value.__cause__.__context__) == "m1" def test_unwind_inner_wrapper_teardown_exc() -> None: out = [] @hookimpl(wrapper=True) def m1(): out.append("m1 init") try: yield out.append("m1 unreachable") except BaseException: out.append("m1 teardown") raise finally: out.append("m1 cleanup") @hookimpl(wrapper=True) def m2(): out.append("m2 init") yield out.append("m2 raise") raise ValueError() with pytest.raises(ValueError): try: MC([m2, m1], {}) finally: out.append("finally") assert out == [ "m1 init", "m2 init", "m2 raise", "m1 teardown", "m1 cleanup", "finally", ] def test_suppress_inner_wrapper_teardown_exc() -> None: out = [] @hookimpl(wrapper=True) def m1(): out.append("m1 init") result = yield out.append("m1 finish") return result @hookimpl(wrapper=True) def m2(): out.append("m2 init") try: yield out.append("m2 unreachable") except ValueError: out.append("m2 suppress") return 22 @hookimpl(wrapper=True) def m3(): out.append("m3 init") yield out.append("m3 raise") raise ValueError() assert MC([m3, m2, m1], {}) == 22 assert out == [ "m1 init", "m2 init", "m3 init", "m3 raise", "m2 suppress", "m1 finish", ] pluggy-1.4.0/testing/test_pluginmanager.py000066400000000000000000000435071455415125700207640ustar00rootroot00000000000000""" ``PluginManager`` unit and public API testing. """ import importlib.metadata from typing import Any from typing import List import pytest from pluggy import HookCallError from pluggy import HookimplMarker from pluggy import HookspecMarker from pluggy import PluginManager from pluggy import PluginValidationError hookspec = HookspecMarker("example") hookimpl = HookimplMarker("example") def test_plugin_double_register(pm: PluginManager) -> None: """Registering the same plugin more then once isn't allowed""" pm.register(42, name="abc") with pytest.raises(ValueError): pm.register(42, name="abc") with pytest.raises(ValueError): pm.register(42, name="def") def test_pm(pm: PluginManager) -> None: """Basic registration with objects""" class A: pass a1, a2 = A(), A() pm.register(a1) assert pm.is_registered(a1) pm.register(a2, "hello") assert pm.is_registered(a2) out = pm.get_plugins() assert a1 in out assert a2 in out assert pm.get_plugin("hello") == a2 assert pm.unregister(a1) == a1 assert not pm.is_registered(a1) out2 = pm.list_name_plugin() assert len(out2) == 1 assert out2 == [("hello", a2)] def test_has_plugin(pm: PluginManager) -> None: class A: pass a1 = A() pm.register(a1, "hello") assert pm.is_registered(a1) assert pm.has_plugin("hello") def test_register_dynamic_attr(he_pm: PluginManager) -> None: class A: def __getattr__(self, name): if name[0] != "_": return 42 raise AttributeError() a = A() he_pm.register(a) assert not he_pm.get_hookcallers(a) def test_pm_name(pm: PluginManager) -> None: class A: pass a1 = A() name = pm.register(a1, name="hello") assert name == "hello" pm.unregister(a1) assert pm.get_plugin("hello") is None assert not pm.is_registered(a1) assert not pm.get_plugins() name2 = pm.register(a1, name="hello") assert name2 == name pm.unregister(name="hello") assert pm.get_plugin("hello") is None assert not pm.is_registered(a1) assert not pm.get_plugins() def test_set_blocked(pm: PluginManager) -> None: class A: pass a1 = A() name = pm.register(a1) assert name is not None assert pm.is_registered(a1) assert not pm.is_blocked(name) pm.set_blocked(name) assert pm.is_blocked(name) assert not pm.is_registered(a1) pm.set_blocked("somename") assert pm.is_blocked("somename") assert not pm.register(A(), "somename") pm.unregister(name="somename") assert pm.is_blocked("somename") # Unblock. assert not pm.unblock("someothername") assert pm.unblock("somename") assert not pm.is_blocked("somename") assert not pm.unblock("somename") assert pm.register(A(), "somename") def test_register_mismatch_method(he_pm: PluginManager) -> None: class hello: @hookimpl def he_method_notexists(self): pass plugin = hello() he_pm.register(plugin) with pytest.raises(PluginValidationError) as excinfo: he_pm.check_pending() assert excinfo.value.plugin is plugin def test_register_mismatch_arg(he_pm: PluginManager) -> None: class hello: @hookimpl def he_method1(self, qlwkje): pass plugin = hello() with pytest.raises(PluginValidationError) as excinfo: he_pm.register(plugin) assert excinfo.value.plugin is plugin def test_register_hookwrapper_not_a_generator_function(he_pm: PluginManager) -> None: class hello: @hookimpl(hookwrapper=True) def he_method1(self): pass # pragma: no cover plugin = hello() with pytest.raises(PluginValidationError, match="generator function") as excinfo: he_pm.register(plugin) assert excinfo.value.plugin is plugin def test_register_both_wrapper_and_hookwrapper(he_pm: PluginManager) -> None: class hello: @hookimpl(wrapper=True, hookwrapper=True) def he_method1(self): yield # pragma: no cover plugin = hello() with pytest.raises( PluginValidationError, match="wrapper.*hookwrapper.*mutually exclusive" ) as excinfo: he_pm.register(plugin) assert excinfo.value.plugin is plugin def test_register(pm: PluginManager) -> None: class MyPlugin: @hookimpl def he_method1(self): ... my = MyPlugin() pm.register(my) assert pm.get_plugins() == {my} my2 = MyPlugin() pm.register(my2) assert pm.get_plugins() == {my, my2} assert pm.is_registered(my) assert pm.is_registered(my2) pm.unregister(my) assert not pm.is_registered(my) assert pm.get_plugins() == {my2} with pytest.raises(AssertionError, match=r"not registered"): pm.unregister(my) def test_register_unknown_hooks(pm: PluginManager) -> None: class Plugin1: @hookimpl def he_method1(self, arg): return arg + 1 pname = pm.register(Plugin1()) assert pname is not None class Hooks: @hookspec def he_method1(self, arg): pass pm.add_hookspecs(Hooks) # assert not pm._unverified_hooks assert pm.hook.he_method1(arg=1) == [2] hookcallers = pm.get_hookcallers(pm.get_plugin(pname)) assert hookcallers is not None assert len(hookcallers) == 1 def test_register_historic(pm: PluginManager) -> None: class Hooks: @hookspec(historic=True) def he_method1(self, arg): pass pm.add_hookspecs(Hooks) pm.hook.he_method1.call_historic(kwargs=dict(arg=1)) out = [] class Plugin: @hookimpl def he_method1(self, arg): out.append(arg) pm.register(Plugin()) assert out == [1] class Plugin2: @hookimpl def he_method1(self, arg): out.append(arg * 10) pm.register(Plugin2()) assert out == [1, 10] pm.hook.he_method1.call_historic(kwargs=dict(arg=12)) assert out == [1, 10, 120, 12] def test_historic_with_subset_hook_caller(pm: PluginManager) -> None: class Hooks: @hookspec(historic=True) def he_method1(self, arg): ... pm.add_hookspecs(Hooks) out = [] class Plugin: @hookimpl def he_method1(self, arg): out.append(arg) plugin = Plugin() pm.register(plugin) class Plugin2: @hookimpl def he_method1(self, arg): out.append(arg * 10) shc = pm.subset_hook_caller("he_method1", remove_plugins=[plugin]) shc.call_historic(kwargs=dict(arg=1)) pm.register(Plugin2()) assert out == [10] pm.register(Plugin()) assert out == [10, 1] @pytest.mark.parametrize("result_callback", [True, False]) def test_with_result_memorized(pm: PluginManager, result_callback: bool) -> None: """Verify that ``HookCaller._maybe_apply_history()` correctly applies the ``result_callback`` function, when provided, to the result from calling each newly registered hook. """ out = [] if not result_callback: callback = None else: def callback(res) -> None: out.append(res) class Hooks: @hookspec(historic=True) def he_method1(self, arg): pass pm.add_hookspecs(Hooks) class Plugin1: @hookimpl def he_method1(self, arg): return arg * 10 pm.register(Plugin1()) he_method1 = pm.hook.he_method1 he_method1.call_historic(result_callback=callback, kwargs=dict(arg=1)) class Plugin2: @hookimpl def he_method1(self, arg): return arg * 10 pm.register(Plugin2()) if result_callback: assert out == [10, 10] else: assert out == [] def test_with_callbacks_immediately_executed(pm: PluginManager) -> None: class Hooks: @hookspec(historic=True) def he_method1(self, arg): pass pm.add_hookspecs(Hooks) class Plugin1: @hookimpl def he_method1(self, arg): return arg * 10 class Plugin2: @hookimpl def he_method1(self, arg): return arg * 20 class Plugin3: @hookimpl def he_method1(self, arg): return arg * 30 out = [] pm.register(Plugin1()) pm.register(Plugin2()) he_method1 = pm.hook.he_method1 he_method1.call_historic(lambda res: out.append(res), dict(arg=1)) assert out == [20, 10] pm.register(Plugin3()) assert out == [20, 10, 30] def test_register_historic_incompat_hookwrapper(pm: PluginManager) -> None: class Hooks: @hookspec(historic=True) def he_method1(self, arg): pass pm.add_hookspecs(Hooks) out = [] class Plugin: @hookimpl(hookwrapper=True) def he_method1(self, arg): out.append(arg) with pytest.raises(PluginValidationError): pm.register(Plugin()) def test_register_historic_incompat_wrapper(pm: PluginManager) -> None: class Hooks: @hookspec(historic=True) def he_method1(self, arg): pass pm.add_hookspecs(Hooks) class Plugin: @hookimpl(wrapper=True) def he_method1(self, arg): yield with pytest.raises(PluginValidationError): pm.register(Plugin()) def test_call_extra(pm: PluginManager) -> None: class Hooks: @hookspec def he_method1(self, arg): pass pm.add_hookspecs(Hooks) def he_method1(arg): return arg * 10 out = pm.hook.he_method1.call_extra([he_method1], dict(arg=1)) assert out == [10] def test_call_with_too_few_args(pm: PluginManager) -> None: class Hooks: @hookspec def he_method1(self, arg): pass pm.add_hookspecs(Hooks) class Plugin1: @hookimpl def he_method1(self, arg): 0 / 0 pm.register(Plugin1()) with pytest.raises(HookCallError): with pytest.warns(UserWarning): pm.hook.he_method1() def test_subset_hook_caller(pm: PluginManager) -> None: class Hooks: @hookspec def he_method1(self, arg): pass pm.add_hookspecs(Hooks) out = [] class Plugin1: @hookimpl def he_method1(self, arg): out.append(arg) class Plugin2: @hookimpl def he_method1(self, arg): out.append(arg * 10) class PluginNo: pass plugin1, plugin2, plugin3 = Plugin1(), Plugin2(), PluginNo() pm.register(plugin1) pm.register(plugin2) pm.register(plugin3) pm.hook.he_method1(arg=1) assert out == [10, 1] out[:] = [] hc = pm.subset_hook_caller("he_method1", [plugin1]) hc(arg=2) assert out == [20] out[:] = [] hc = pm.subset_hook_caller("he_method1", [plugin2]) hc(arg=2) assert out == [2] out[:] = [] pm.unregister(plugin1) hc(arg=2) assert out == [] out[:] = [] pm.hook.he_method1(arg=1) assert out == [10] assert repr(hc) == "<_SubsetHookCaller 'he_method1'>" def test_get_hookimpls(pm: PluginManager) -> None: class Hooks: @hookspec def he_method1(self, arg): pass pm.add_hookspecs(Hooks) assert pm.hook.he_method1.get_hookimpls() == [] class Plugin1: @hookimpl def he_method1(self, arg): pass class Plugin2: @hookimpl def he_method1(self, arg): pass class PluginNo: pass plugin1, plugin2, plugin3 = Plugin1(), Plugin2(), PluginNo() pm.register(plugin1) pm.register(plugin2) pm.register(plugin3) hookimpls = pm.hook.he_method1.get_hookimpls() hook_plugins = [item.plugin for item in hookimpls] assert hook_plugins == [plugin1, plugin2] def test_get_hookcallers(pm: PluginManager) -> None: class Hooks: @hookspec def he_method1(self): ... @hookspec def he_method2(self): ... pm.add_hookspecs(Hooks) class Plugin1: @hookimpl def he_method1(self): ... @hookimpl def he_method2(self): ... class Plugin2: @hookimpl def he_method1(self): ... class Plugin3: @hookimpl def he_method2(self): ... plugin1 = Plugin1() pm.register(plugin1) plugin2 = Plugin2() pm.register(plugin2) plugin3 = Plugin3() pm.register(plugin3) hookcallers1 = pm.get_hookcallers(plugin1) assert hookcallers1 is not None assert len(hookcallers1) == 2 hookcallers2 = pm.get_hookcallers(plugin2) assert hookcallers2 is not None assert len(hookcallers2) == 1 hookcallers3 = pm.get_hookcallers(plugin3) assert hookcallers3 is not None assert len(hookcallers3) == 1 assert hookcallers1 == hookcallers2 + hookcallers3 assert pm.get_hookcallers(object()) is None def test_add_hookspecs_nohooks(pm: PluginManager) -> None: class NoHooks: pass with pytest.raises(ValueError): pm.add_hookspecs(NoHooks) def test_load_setuptools_instantiation(monkeypatch, pm: PluginManager) -> None: class EntryPoint: name = "myname" group = "hello" value = "myname:foo" def load(self): class PseudoPlugin: x = 42 return PseudoPlugin() class Distribution: entry_points = (EntryPoint(),) dist = Distribution() def my_distributions(): return (dist,) monkeypatch.setattr(importlib.metadata, "distributions", my_distributions) num = pm.load_setuptools_entrypoints("hello") assert num == 1 plugin = pm.get_plugin("myname") assert plugin is not None assert plugin.x == 42 ret = pm.list_plugin_distinfo() # poor man's `assert ret == [(plugin, mock.ANY)]` assert len(ret) == 1 assert len(ret[0]) == 2 assert ret[0][0] == plugin assert ret[0][1]._dist == dist # type: ignore[comparison-overlap] num = pm.load_setuptools_entrypoints("hello") assert num == 0 # no plugin loaded by this call def test_add_tracefuncs(he_pm: PluginManager) -> None: out: List[Any] = [] class api1: @hookimpl def he_method1(self): out.append("he_method1-api1") class api2: @hookimpl def he_method1(self): out.append("he_method1-api2") he_pm.register(api1()) he_pm.register(api2()) def before(hook_name, hook_impls, kwargs): out.append((hook_name, list(hook_impls), kwargs)) def after(outcome, hook_name, hook_impls, kwargs): out.append((outcome, hook_name, list(hook_impls), kwargs)) undo = he_pm.add_hookcall_monitoring(before, after) he_pm.hook.he_method1(arg=1) assert len(out) == 4 assert out[0][0] == "he_method1" assert len(out[0][1]) == 2 assert isinstance(out[0][2], dict) assert out[1] == "he_method1-api2" assert out[2] == "he_method1-api1" assert len(out[3]) == 4 assert out[3][1] == out[0][0] undo() he_pm.hook.he_method1(arg=1) assert len(out) == 4 + 2 def test_hook_tracing(he_pm: PluginManager) -> None: saveindent = [] class api1: @hookimpl def he_method1(self): saveindent.append(he_pm.trace.root.indent) class api2: @hookimpl def he_method1(self): saveindent.append(he_pm.trace.root.indent) raise ValueError() he_pm.register(api1()) out: List[Any] = [] he_pm.trace.root.setwriter(out.append) undo = he_pm.enable_tracing() try: indent = he_pm.trace.root.indent he_pm.hook.he_method1(arg=1) assert indent == he_pm.trace.root.indent assert len(out) == 2 assert "he_method1" in out[0] assert "finish" in out[1] out[:] = [] he_pm.register(api2()) with pytest.raises(ValueError): he_pm.hook.he_method1(arg=1) assert he_pm.trace.root.indent == indent assert saveindent[0] > indent finally: undo() @pytest.mark.parametrize("historic", [False, True]) def test_register_while_calling( pm: PluginManager, historic: bool, ) -> None: """Test that registering an impl of a hook while it is being called does not affect the call itself, only later calls. For historic hooks however, the hook is called immediately on registration. Regression test for #438. """ hookspec = HookspecMarker("example") class Hooks: @hookspec(historic=historic) def configure(self) -> int: raise NotImplementedError() class Plugin1: @hookimpl def configure(self) -> int: return 1 class Plugin2: def __init__(self) -> None: self.already_registered = False @hookimpl def configure(self) -> int: if not self.already_registered: pm.register(Plugin4()) pm.register(Plugin5()) pm.register(Plugin6()) self.already_registered = True return 2 class Plugin3: @hookimpl def configure(self) -> int: return 3 class Plugin4: @hookimpl(tryfirst=True) def configure(self) -> int: return 4 class Plugin5: @hookimpl() def configure(self) -> int: return 5 class Plugin6: @hookimpl(trylast=True) def configure(self) -> int: return 6 pm.add_hookspecs(Hooks) pm.register(Plugin1()) pm.register(Plugin2()) pm.register(Plugin3()) if not historic: result = pm.hook.configure() assert result == [3, 2, 1] result = pm.hook.configure() assert result == [4, 5, 3, 2, 1, 6] else: result = [] pm.hook.configure.call_historic(result.append) assert result == [4, 5, 6, 3, 2, 1] result = [] pm.hook.configure.call_historic(result.append) assert result == [4, 5, 3, 2, 1, 6] pluggy-1.4.0/testing/test_tracer.py000066400000000000000000000035541455415125700174110ustar00rootroot00000000000000from typing import List import pytest from pluggy._tracing import TagTracer @pytest.fixture def rootlogger() -> TagTracer: return TagTracer() def test_simple(rootlogger: TagTracer) -> None: log = rootlogger.get("pytest") log("hello") out: List[str] = [] rootlogger.setwriter(out.append) log("world") assert len(out) == 1 assert out[0] == "world [pytest]\n" sublog = log.get("collection") sublog("hello") assert out[1] == "hello [pytest:collection]\n" def test_indent(rootlogger: TagTracer) -> None: log = rootlogger.get("1") out = [] log.root.setwriter(lambda arg: out.append(arg)) log("hello") log.root.indent += 1 log("line1") log("line2") log.root.indent += 1 log("line3") log("line4") log.root.indent -= 1 log("line5") log.root.indent -= 1 log("last") assert len(out) == 7 names = [x[: x.rfind(" [")] for x in out] assert names == [ "hello", " line1", " line2", " line3", " line4", " line5", "last", ] def test_readable_output_dictargs(rootlogger: TagTracer) -> None: out = rootlogger._format_message(["test"], [1]) assert out == "1 [test]\n" out2 = rootlogger._format_message(["test"], ["test", {"a": 1}]) assert out2 == "test [test]\n a: 1\n" def test_setprocessor(rootlogger: TagTracer) -> None: log = rootlogger.get("1") log2 = log.get("2") assert log2.tags == tuple("12") out = [] rootlogger.setprocessor(tuple("12"), lambda *args: out.append(args)) log("not seen") log2("seen") assert len(out) == 1 tags, args = out[0] assert "1" in tags assert "2" in tags assert args == ("seen",) l2 = [] rootlogger.setprocessor("1:2", lambda *args: l2.append(args)) log2("seen") tags, args = l2[0] assert args == ("seen",) pluggy-1.4.0/testing/test_warnings.py000066400000000000000000000022351455415125700177540ustar00rootroot00000000000000from pathlib import Path import pytest from pluggy import HookimplMarker from pluggy import HookspecMarker from pluggy import PluggyTeardownRaisedWarning from pluggy import PluginManager hookspec = HookspecMarker("example") hookimpl = HookimplMarker("example") def test_teardown_raised_warning(pm: PluginManager) -> None: class Api: @hookspec def my_hook(self): raise NotImplementedError() pm.add_hookspecs(Api) class Plugin1: @hookimpl def my_hook(self): pass class Plugin2: @hookimpl(hookwrapper=True) def my_hook(self): yield 1 / 0 class Plugin3: @hookimpl(hookwrapper=True) def my_hook(self): yield pm.register(Plugin1(), "plugin1") pm.register(Plugin2(), "plugin2") pm.register(Plugin3(), "plugin3") with pytest.warns( PluggyTeardownRaisedWarning, match=r"\bplugin2\b.*\bmy_hook\b.*\n.*ZeroDivisionError", ) as wc: with pytest.raises(ZeroDivisionError): pm.hook.my_hook() assert len(wc.list) == 1 assert Path(wc.list[0].filename).name == "test_warnings.py" pluggy-1.4.0/tox.ini000066400000000000000000000025071455415125700143530ustar00rootroot00000000000000[tox] envlist=docs,py{38,39,310,311,py3},py{38}-pytest{main} [testenv] commands= {env:_PLUGGY_TOX_CMD:pytest} {posargs} coverage: coverage report -m coverage: coverage xml setenv= _PYTEST_SETUP_SKIP_PLUGGY_DEP=1 coverage: _PLUGGY_TOX_CMD=coverage run -m pytest extras=testing deps= coverage: coverage pytestmain: git+https://github.com/pytest-dev/pytest.git@main [testenv:benchmark] commands=pytest {posargs:testing/benchmark.py} deps= pytest pytest-benchmark [testenv:docs] deps = -r{toxinidir}/docs/requirements.txt commands = python scripts/towncrier-draft-to-file.py # the '-t changelog_towncrier_draft' tags makes sphinx include the draft # changelog in the docs; this does not happen on ReadTheDocs because it uses # the standard sphinx command so the 'changelog_towncrier_draft' is never set there sphinx-build -W -b html {toxinidir}/docs {toxinidir}/build/html-docs -t changelog_towncrier_draft {posargs:} [pytest] minversion=2.0 testpaths = testing #--pyargs --doctest-modules --ignore=.tox addopts=-r a filterwarnings = error [flake8] max-line-length=99 [testenv:release] description = do a release, required posarg of the version number basepython = python3 skipsdist = True usedevelop = True passenv = * deps = colorama gitpython towncrier commands = python scripts/release.py {posargs}