pluggy-0.3.1/0000775000175000017500000000000012576504560012424 5ustar hpkhpk00000000000000pluggy-0.3.1/pluggy.egg-info/0000775000175000017500000000000012576504560015425 5ustar hpkhpk00000000000000pluggy-0.3.1/pluggy.egg-info/top_level.txt0000664000175000017500000000000712576504560020154 0ustar hpkhpk00000000000000pluggy pluggy-0.3.1/pluggy.egg-info/pbr.json0000664000175000017500000000005712576504560017105 0ustar hpkhpk00000000000000{"is_release": false, "git_version": "7d4c9cd"}pluggy-0.3.1/pluggy.egg-info/PKG-INFO0000664000175000017500000000261212576504560016523 0ustar hpkhpk00000000000000Metadata-Version: 1.1 Name: pluggy Version: 0.3.1 Summary: plugin and hook calling mechanisms for python Home-page: UNKNOWN Author: Holger Krekel Author-email: holger at merlinux.eu License: MIT license Description: Plugin registration and hook calling for Python =============================================== This is the plugin manager as used by pytest but stripped of pytest specific details. During the 0.x series this plugin does not have much documentation except extensive docstrings in the pluggy.py module. Platform: unix Platform: linux Platform: osx Platform: win32 Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: POSIX Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: MacOS :: MacOS X Classifier: Topic :: Software Development :: Testing Classifier: Topic :: Software Development :: Libraries Classifier: Topic :: Utilities Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 pluggy-0.3.1/pluggy.egg-info/SOURCES.txt0000664000175000017500000000040012576504560017303 0ustar hpkhpk00000000000000.gitignore CHANGELOG LICENSE MANIFEST.in README.rst pluggy.py setup.cfg setup.py tox.ini pluggy.egg-info/PKG-INFO pluggy.egg-info/SOURCES.txt pluggy.egg-info/dependency_links.txt pluggy.egg-info/pbr.json pluggy.egg-info/top_level.txt testing/test_pluggy.pypluggy-0.3.1/pluggy.egg-info/dependency_links.txt0000664000175000017500000000000112576504560021473 0ustar hpkhpk00000000000000 pluggy-0.3.1/setup.cfg0000664000175000017500000000021012576504560014236 0ustar hpkhpk00000000000000[bdist_wheel] universal = 1 [devpi:upload] formats = sdist.tgz,bdist_wheel [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 pluggy-0.3.1/MANIFEST.in0000664000175000017500000000015512576504560014163 0ustar hpkhpk00000000000000include CHANGELOG include README.rst include setup.py include tox.ini include LICENSE include test_pluggy.py pluggy-0.3.1/PKG-INFO0000664000175000017500000000261212576504560013522 0ustar hpkhpk00000000000000Metadata-Version: 1.1 Name: pluggy Version: 0.3.1 Summary: plugin and hook calling mechanisms for python Home-page: UNKNOWN Author: Holger Krekel Author-email: holger at merlinux.eu License: MIT license Description: Plugin registration and hook calling for Python =============================================== This is the plugin manager as used by pytest but stripped of pytest specific details. During the 0.x series this plugin does not have much documentation except extensive docstrings in the pluggy.py module. Platform: unix Platform: linux Platform: osx Platform: win32 Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: POSIX Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: MacOS :: MacOS X Classifier: Topic :: Software Development :: Testing Classifier: Topic :: Software Development :: Libraries Classifier: Topic :: Utilities Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 pluggy-0.3.1/tox.ini0000664000175000017500000000102512576504560013735 0ustar hpkhpk00000000000000[tox] envlist=check,{py26,py27,py34,py35,pypy}-{pytest27,pytest} [testenv] commands= py.test {posargs:testing/test_pluggy.py} deps= pytest27: pytest>=2.7.0,<2.8.0 pytest: pytest>=2.8.0.dev5 [testenv:check] usedevelop=True deps = pytest>=2.7.0,<2.8.0 pytest-pep8 pytest-flakes commands = py.test --pep8 py.test --flakes -m flakes pluggy.py testing/test_pluggy.py [pytest] minversion=2.0 #--pyargs --doctest-modules --ignore=.tox addopts= -rxsX pep8ignore = E501 E128 E127 norecursedirs = .tox ja .hg pluggy-0.3.1/LICENSE0000664000175000017500000000213012576504560013425 0ustar hpkhpk00000000000000The 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-0.3.1/README.rst0000664000175000017500000000046112576504560014114 0ustar hpkhpk00000000000000 Plugin registration and hook calling for Python =============================================== This is the plugin manager as used by pytest but stripped of pytest specific details. During the 0.x series this plugin does not have much documentation except extensive docstrings in the pluggy.py module. pluggy-0.3.1/pluggy.py0000664000175000017500000007224612576504560014320 0ustar hpkhpk00000000000000""" PluginManager, basic initialization and tracing. pluggy is the cristallized core of plugin management as used by some 150 plugins for pytest. 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. pluggy is concerned with hook specification, hook implementations and hook calling. For any given hook specification a hook call invokes up to N implementations. A hook implementation can influence its position and type of execution: if attributed "tryfirst" or "trylast" it will be tried to execute first or last. However, if attributed "hookwrapper" an implementation can wrap all calls to non-hookwrapper implementations. A hookwrapper can thus execute some code ahead and after the execution of other hooks. Hook specification is done by way of a regular python function where both the function name and the names of all its arguments are significant. Each hook implementation function is verified against the original specification function, including the names of all its arguments. To allow for hook specifications to evolve over the livetime of a project, hook implementations can accept less arguments. One can thus add new arguments and semantics to a hook specification by adding another argument typically without breaking existing hook implementations. The chosen approach is meant to let a hook designer think carefuly about which objects are needed by an extension writer. By contrast, subclass-based extension mechanisms often expose a lot more state and behaviour than needed, thus restricting future developments. Pluggy currently consists of functionality for: - a way to register new hook specifications. Without a hook specification no hook calling can be performed. - a registry of plugins which contain hook implementation functions. It is possible to register plugins for which a hook specification is not yet known and validate all hooks when the system is in a more referentially consistent state. Setting an "optionalhook" attribution to a hook implementation will avoid PluginValidationError's if a specification is missing. This allows to have optional integration between plugins. - a "hook" relay object from which you can launch 1:N calls to registered hook implementation functions - a mechanism for ordering hook implementation functions - mechanisms for two different type of 1:N calls: "firstresult" for when the call should stop when the first implementation returns a non-None result. And the other (default) way of guaranteeing that all hook implementations will be called and their non-None result collected. - mechanisms for "historic" extension points such that all newly registered functions will receive all hook calls that happened before their registration. - a mechanism for discovering plugin objects which are based on setuptools based entry points. - a simple tracing mechanism, including tracing of plugin calls and their arguments. """ import sys import inspect __version__ = '0.3.1' __all__ = ["PluginManager", "PluginValidationError", "HookspecMarker", "HookimplMarker"] _py3 = sys.version_info > (3, 0) class HookspecMarker: """ Decorator helper class for marking functions as hook specifications. You can instantiate it with a project_name to get a decorator. Calling PluginManager.add_hookspecs later will discover all marked functions if the PluginManager uses the same project_name. """ def __init__(self, project_name): self.project_name = project_name def __call__(self, function=None, firstresult=False, historic=False): """ if passed a function, directly sets attributes on the function which will make it discoverable to add_hookspecs(). If passed no function, returns a decorator which can be applied to a function later using the attributes supplied. If firstresult is 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. If historic is True calls to a hook will be memorized and replayed on later registered plugins. """ def setattr_hookspec_opts(func): if historic and firstresult: raise ValueError("cannot have a historic firstresult hook") setattr(func, self.project_name + "_spec", dict(firstresult=firstresult, historic=historic)) return func if function is not None: return setattr_hookspec_opts(function) else: return setattr_hookspec_opts class HookimplMarker: """ Decorator helper class for marking functions as hook implementations. You can instantiate with a project_name to get a decorator. Calling PluginManager.register later will discover all marked functions if the PluginManager uses the same project_name. """ def __init__(self, project_name): self.project_name = project_name def __call__(self, function=None, hookwrapper=False, optionalhook=False, tryfirst=False, trylast=False): """ if passed a function, directly sets attributes on the function which will make it discoverable to register(). If passed no function, returns a decorator which can be applied to a function later using the attributes supplied. If optionalhook is True a missing matching hook specification will not result in an error (by default it is an error if no matching spec is found). If tryfirst is True this hook implementation will run as early as possible in the chain of N hook implementations for a specfication. If trylast is True this hook implementation will run as late as possible in the chain of N hook implementations. If hookwrapper is True the hook implementations needs to execute exactly one "yield". The code before the yield is run early before any non-hookwrapper function is run. The code after the yield is run after all non-hookwrapper function have run. The yield receives an ``_CallOutcome`` object representing the exception or result outcome of the inner calls (including other hookwrapper calls). """ def setattr_hookimpl_opts(func): setattr(func, self.project_name + "_impl", dict(hookwrapper=hookwrapper, optionalhook=optionalhook, tryfirst=tryfirst, trylast=trylast)) return func if function is None: return setattr_hookimpl_opts else: return setattr_hookimpl_opts(function) def normalize_hookimpl_opts(opts): opts.setdefault("tryfirst", False) opts.setdefault("trylast", False) opts.setdefault("hookwrapper", False) opts.setdefault("optionalhook", False) class _TagTracer: def __init__(self): self._tag2proc = {} self.writer = None self.indent = 0 def get(self, name): return _TagTracerSub(self, (name,)) def format_message(self, tags, args): if isinstance(args[-1], dict): extra = args[-1] args = args[:-1] else: extra = {} content = " ".join(map(str, args)) indent = " " * self.indent lines = [ "%s%s [%s]\n" % (indent, content, ":".join(tags)) ] for name, value in extra.items(): lines.append("%s %s: %s\n" % (indent, name, value)) return lines def processmessage(self, tags, args): if self.writer is not None and args: lines = self.format_message(tags, args) self.writer(''.join(lines)) try: self._tag2proc[tags](tags, args) except KeyError: pass def setwriter(self, writer): self.writer = writer def setprocessor(self, tags, processor): if isinstance(tags, str): tags = tuple(tags.split(":")) else: assert isinstance(tags, tuple) self._tag2proc[tags] = processor class _TagTracerSub: def __init__(self, root, tags): self.root = root self.tags = tags def __call__(self, *args): self.root.processmessage(self.tags, args) def setmyprocessor(self, processor): self.root.setprocessor(self.tags, processor) def get(self, name): return self.__class__(self.root, self.tags + (name,)) def _raise_wrapfail(wrap_controller, msg): 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 _wrapped_call(wrap_controller, func): """ Wrap calling to a function with a generator which needs to yield exactly once. The yield point will trigger calling the wrapped function and return its _CallOutcome to the yield point. The generator then needs to finish (raise StopIteration) in order for the wrapped call to complete. """ try: next(wrap_controller) # first yield except StopIteration: _raise_wrapfail(wrap_controller, "did not yield") call_outcome = _CallOutcome(func) try: wrap_controller.send(call_outcome) _raise_wrapfail(wrap_controller, "has second yield") except StopIteration: pass return call_outcome.get_result() class _CallOutcome: """ Outcome of a function call, either an exception or a proper result. Calling the ``get_result`` method will return the result or reraise the exception raised when the function was called. """ excinfo = None def __init__(self, func): try: self.result = func() except BaseException: self.excinfo = sys.exc_info() def force_result(self, result): self.result = result self.excinfo = None def get_result(self): if self.excinfo is None: return self.result else: ex = self.excinfo if _py3: raise ex[1].with_traceback(ex[2]) _reraise(*ex) # noqa if not _py3: exec(""" def _reraise(cls, val, tb): raise cls, val, tb """) class _TracedHookExecution: def __init__(self, pluginmanager, before, after): self.pluginmanager = pluginmanager self.before = before self.after = after self.oldcall = pluginmanager._inner_hookexec assert not isinstance(self.oldcall, _TracedHookExecution) self.pluginmanager._inner_hookexec = self def __call__(self, hook, hook_impls, kwargs): self.before(hook.name, hook_impls, kwargs) outcome = _CallOutcome(lambda: self.oldcall(hook, hook_impls, kwargs)) self.after(outcome, hook.name, hook_impls, kwargs) return outcome.get_result() def undo(self): self.pluginmanager._inner_hookexec = self.oldcall class PluginManager(object): """ Core Pluginmanager class which manages registration of plugin objects and 1:N hook calling. You can register new hooks by calling ``addhooks(module_or_class)``. You can register plugin objects (which contain hooks) by calling ``register(plugin)``. The Pluginmanager is initialized with a prefix that is searched for in the names of the dict of registered plugin objects. An optional excludefunc allows to blacklist names which are not considered as hooks despite a matching prefix. For debugging purposes you can call ``enable_tracing()`` which will subsequently send debug information to the trace helper. """ def __init__(self, project_name, implprefix=None): """ if implprefix is given implementation functions will be recognized if their name matches the implprefix. """ self.project_name = project_name self._name2plugin = {} self._plugin2hookcallers = {} self._plugin_distinfo = [] self.trace = _TagTracer().get("pluginmanage") self.hook = _HookRelay(self.trace.root.get("hook")) self._implprefix = implprefix self._inner_hookexec = lambda hook, methods, kwargs: \ _MultiCall(methods, kwargs, hook.spec_opts).execute() def _hookexec(self, hook, methods, kwargs): # called from all hookcaller instances. # enable_tracing will set its own wrapping function at self._inner_hookexec return self._inner_hookexec(hook, methods, kwargs) def register(self, plugin, name=None): """ Register a plugin and return its canonical name or None if the name is blocked from registering. Raise a ValueError if the plugin is already registered. """ plugin_name = name or self.get_canonical_name(plugin) if plugin_name in self._name2plugin or plugin in self._plugin2hookcallers: if self._name2plugin.get(plugin_name, -1) is None: return # blocked plugin, return None to indicate no registration raise ValueError("Plugin already registered: %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 self._plugin2hookcallers[plugin] = hookcallers = [] 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 = getattr(plugin, name) hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts) hook = 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) hookcallers.append(hook) return plugin_name def parse_hookimpl_opts(self, plugin, name): method = getattr(plugin, name) res = getattr(method, self.project_name + "_impl", None) if res is not None and not isinstance(res, dict): # false positive res = None elif res is None and self._implprefix and name.startswith(self._implprefix): res = {} return res def unregister(self, plugin=None, name=None): """ unregister a plugin object and all its contained hook implementations from internal data structures. """ if name is None: assert plugin is not None, "one of name or plugin needs to be specified" name = self.get_name(plugin) if plugin is None: plugin = self.get_plugin(name) # if self._name2plugin[name] == None registration was blocked: ignore if self._name2plugin.get(name): del self._name2plugin[name] for hookcaller in self._plugin2hookcallers.pop(plugin, []): hookcaller._remove_plugin(plugin) return plugin def set_blocked(self, name): """ block registrations of the given name, unregister if already registered. """ self.unregister(name=name) self._name2plugin[name] = None def is_blocked(self, name): """ return True if the name blogs registering plugins of that name. """ return name in self._name2plugin and self._name2plugin[name] is None def add_hookspecs(self, module_or_class): """ add new hook specifications defined in the given module_or_class. Functions are recognized if they have been decorated accordingly. """ 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 = 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._wrappers + hc._nonwrappers): self._verify_hook(hc, hookfunction) names.append(name) if not names: raise ValueError("did not find any %r hooks in %r" % (self.project_name, module_or_class)) def parse_hookspec_opts(self, module_or_class, name): method = getattr(module_or_class, name) return getattr(method, self.project_name + "_spec", None) def get_plugins(self): """ return the set of registered plugins. """ return set(self._plugin2hookcallers) def is_registered(self, plugin): """ Return True if the plugin is already registered. """ return plugin in self._plugin2hookcallers def get_canonical_name(self, plugin): """ Return canonical name for a plugin object. Note that a plugin may be registered under a different name which was specified by the caller of register(plugin, name). To obtain the name of an registered plugin use ``get_name(plugin)`` instead.""" return getattr(plugin, "__name__", None) or str(id(plugin)) def get_plugin(self, name): """ Return a plugin or None for the given name. """ return self._name2plugin.get(name) def get_name(self, plugin): """ Return name for registered plugin or None if not registered. """ for name, val in self._name2plugin.items(): if plugin == val: return name def _verify_hook(self, hook, hookimpl): if hook.is_historic() and hookimpl.hookwrapper: raise PluginValidationError( "Plugin %r\nhook %r\nhistoric incompatible to hookwrapper" % (hookimpl.plugin_name, hook.name)) for arg in hookimpl.argnames: if arg not in hook.argnames: raise PluginValidationError( "Plugin %r\nhook %r\nargument %r not available\n" "plugin definition: %s\n" "available hookargs: %s" % (hookimpl.plugin_name, hook.name, arg, _formatdef(hookimpl.function), ", ".join(hook.argnames))) def check_pending(self): """ Verify that all hooks which have not been verified against a hook specification are optional, otherwise raise PluginValidationError""" for name in self.hook.__dict__: if name[0] != "_": hook = getattr(self.hook, name) if not hook.has_spec(): for hookimpl in (hook._wrappers + hook._nonwrappers): if not hookimpl.optionalhook: raise PluginValidationError( "unknown hook %r in plugin %r" % (name, hookimpl.plugin)) def load_setuptools_entrypoints(self, entrypoint_name): """ Load modules from querying the specified setuptools entrypoint name. Return the number of loaded plugins. """ from pkg_resources import iter_entry_points, DistributionNotFound for ep in iter_entry_points(entrypoint_name): # is the plugin registered or blocked? if self.get_plugin(ep.name) or self.is_blocked(ep.name): continue try: plugin = ep.load() except DistributionNotFound: continue self.register(plugin, name=ep.name) self._plugin_distinfo.append((plugin, ep.dist)) return len(self._plugin_distinfo) def list_plugin_distinfo(self): """ return list of distinfo/plugin tuples for all setuptools registered plugins. """ return list(self._plugin_distinfo) def list_name_plugin(self): """ return list of name/plugin pairs. """ return list(self._name2plugin.items()) def get_hookcallers(self, plugin): """ get all hook callers for the specified plugin. """ return self._plugin2hookcallers.get(plugin) def add_hookcall_monitoring(self, before, after): """ add before/after tracing functions for all hooks and return an undo function which, when called, will remove 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 :py:class:`_CallOutcome`` object which represents the result of the overall hook call. """ return _TracedHookExecution(self, before, after).undo def enable_tracing(self): """ enable tracing of hook calls and return an undo function. """ hooktrace = self.hook._trace def before(hook_name, methods, kwargs): hooktrace.root.indent += 1 hooktrace(hook_name, kwargs) def after(outcome, hook_name, methods, kwargs): if outcome.excinfo is None: hooktrace("finish", hook_name, "-->", outcome.result) hooktrace.root.indent -= 1 return self.add_hookcall_monitoring(before, after) def subset_hook_caller(self, name, remove_plugins): """ Return a new _HookCaller instance for the named method which manages calls to all registered plugins except the ones from remove_plugins. """ orig = getattr(self.hook, name) plugins_to_remove = [plug for plug in remove_plugins if hasattr(plug, name)] if plugins_to_remove: hc = _HookCaller(orig.name, orig._hookexec, orig._specmodule_or_class, orig.spec_opts) for hookimpl in (orig._wrappers + orig._nonwrappers): plugin = hookimpl.plugin if plugin not in plugins_to_remove: hc._add_hookimpl(hookimpl) # we also keep track of this hook caller so it # gets properly removed on plugin unregistration self._plugin2hookcallers.setdefault(plugin, []).append(hc) return hc return orig class _MultiCall: """ execute a call into multiple python functions/methods. """ # XXX note that the __multicall__ argument is supported only # for pytest compatibility reasons. It was never officially # supported there and is explicitely deprecated since 2.8 # so we can remove it soon, allowing to avoid the below recursion # in execute() and simplify/speed up the execute loop. def __init__(self, hook_impls, kwargs, specopts={}): self.hook_impls = hook_impls self.kwargs = kwargs self.kwargs["__multicall__"] = self self.specopts = specopts def execute(self): all_kwargs = self.kwargs self.results = results = [] firstresult = self.specopts.get("firstresult") while self.hook_impls: hook_impl = self.hook_impls.pop() args = [all_kwargs[argname] for argname in hook_impl.argnames] if hook_impl.hookwrapper: return _wrapped_call(hook_impl.function(*args), self.execute) res = hook_impl.function(*args) if res is not None: if firstresult: return res results.append(res) if not firstresult: return results def __repr__(self): status = "%d meths" % (len(self.hook_impls),) if hasattr(self, "results"): status = ("%d results, " % len(self.results)) + status return "<_MultiCall %s, kwargs=%r>" % (status, self.kwargs) def varnames(func, startindex=None): """ return argument name tuple 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 unless you are passing an unbound method with Python3 (which has no supports for unbound methods) """ cache = getattr(func, "__dict__", {}) try: return cache["_varnames"] except KeyError: pass if inspect.isclass(func): try: func = func.__init__ except AttributeError: return () startindex = 1 else: if not inspect.isfunction(func) and not inspect.ismethod(func): func = getattr(func, '__call__', func) if startindex is None: startindex = int(inspect.ismethod(func)) try: rawcode = func.__code__ except AttributeError: return () try: x = rawcode.co_varnames[startindex:rawcode.co_argcount] except AttributeError: x = () else: defaults = func.__defaults__ if defaults: x = x[:-len(defaults)] try: cache["_varnames"] = x except TypeError: pass return x class _HookRelay: """ hook holder object for performing 1:N hook calls where N is the number of registered plugins. """ def __init__(self, trace): self._trace = trace class _HookCaller(object): def __init__(self, name, hook_execute, specmodule_or_class=None, spec_opts=None): self.name = name self._wrappers = [] self._nonwrappers = [] self._hookexec = hook_execute if specmodule_or_class is not None: assert spec_opts is not None self.set_specification(specmodule_or_class, spec_opts) def has_spec(self): return hasattr(self, "_specmodule_or_class") def set_specification(self, specmodule_or_class, spec_opts): assert not self.has_spec() self._specmodule_or_class = specmodule_or_class specfunc = getattr(specmodule_or_class, self.name) argnames = varnames(specfunc, startindex=inspect.isclass(specmodule_or_class)) assert "self" not in argnames # sanity check self.argnames = ["__multicall__"] + list(argnames) self.spec_opts = spec_opts if spec_opts.get("historic"): self._call_history = [] def is_historic(self): return hasattr(self, "_call_history") def _remove_plugin(self, plugin): def remove(wrappers): for i, method in enumerate(wrappers): if method.plugin == plugin: del wrappers[i] return True if remove(self._wrappers) is None: if remove(self._nonwrappers) is None: raise ValueError("plugin %r not found" % (plugin,)) def _add_hookimpl(self, hookimpl): if hookimpl.hookwrapper: methods = self._wrappers else: methods = self._nonwrappers if hookimpl.trylast: methods.insert(0, hookimpl) elif hookimpl.tryfirst: methods.append(hookimpl) else: # find last non-tryfirst method i = len(methods) - 1 while i >= 0 and methods[i].tryfirst: i -= 1 methods.insert(i + 1, hookimpl) def __repr__(self): return "<_HookCaller %r>" % (self.name,) def __call__(self, **kwargs): assert not self.is_historic() return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) def call_historic(self, proc=None, kwargs=None): self._call_history.append((kwargs or {}, proc)) # historizing hooks don't return results self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) def call_extra(self, methods, kwargs): """ Call the hook with some additional temporarily participating methods using the specified kwargs as call parameters. """ old = list(self._nonwrappers), list(self._wrappers) for method in methods: opts = dict(hookwrapper=False, trylast=False, tryfirst=False) hookimpl = HookImpl(None, "", method, opts) self._add_hookimpl(hookimpl) try: return self(**kwargs) finally: self._nonwrappers, self._wrappers = old def _maybe_apply_history(self, method): if self.is_historic(): for kwargs, proc in self._call_history: res = self._hookexec(self, [method], kwargs) if res and proc is not None: proc(res[0]) class HookImpl: def __init__(self, plugin, plugin_name, function, hook_impl_opts): self.function = function self.argnames = varnames(self.function) self.plugin = plugin self.opts = hook_impl_opts self.plugin_name = plugin_name self.__dict__.update(hook_impl_opts) class PluginValidationError(Exception): """ plugin failed validation. """ if hasattr(inspect, 'signature'): def _formatdef(func): return "%s%s" % ( func.__name__, str(inspect.signature(func)) ) else: def _formatdef(func): return "%s%s" % ( func.__name__, inspect.formatargspec(*inspect.getargspec(func)) ) pluggy-0.3.1/CHANGELOG0000664000175000017500000000020312576504560013631 0ustar hpkhpk000000000000000.3.1 ----- - avoid using deprecated-in-python3.5 getargspec method. Thanks Michael Droettboom. 0.3.0 ----- initial release pluggy-0.3.1/testing/0000775000175000017500000000000012576504560014101 5ustar hpkhpk00000000000000pluggy-0.3.1/testing/test_pluggy.py0000664000175000017500000006423012576504560017026 0ustar hpkhpk00000000000000 import sys import types import pytest from pluggy import (PluginManager, varnames, PluginValidationError, HookimplMarker, HookspecMarker) from pluggy import (_MultiCall, _TagTracer, HookImpl, _formatdef) hookspec = HookspecMarker("example") hookimpl = HookimplMarker("example") @pytest.fixture def pm(): return PluginManager("example") @pytest.fixture def he_pm(pm): class Hooks: @hookspec def he_method1(self, arg): return arg + 1 pm.add_hookspecs(Hooks) return pm class TestPluginManager: def test_plugin_double_register(self, pm): 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(self, pm): class A: pass a1, a2 = A(), A() pm.register(a1) assert pm.is_registered(a1) pm.register(a2, "hello") assert pm.is_registered(a2) l = pm.get_plugins() assert a1 in l assert a2 in l assert pm.get_plugin('hello') == a2 assert pm.unregister(a1) == a1 assert not pm.is_registered(a1) l = pm.list_name_plugin() assert len(l) == 1 assert l == [("hello", a2)] def test_register_dynamic_attr(self, he_pm): 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(self, pm): class A: pass a1 = A() name = pm.register(a1, name="hello") assert name == "hello" pm.unregister(a1) assert pm.get_plugin(a1) 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(a1) is None assert not pm.is_registered(a1) assert not pm.get_plugins() def test_set_blocked(self, pm): class A: pass a1 = A() name = pm.register(a1) 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") def test_register_mismatch_method(self, he_pm): class hello: @hookimpl def he_method_notexists(self): pass he_pm.register(hello()) with pytest.raises(PluginValidationError): he_pm.check_pending() def test_register_mismatch_arg(self, he_pm): class hello: @hookimpl def he_method1(self, qlwkje): pass with pytest.raises(PluginValidationError): he_pm.register(hello()) def test_register(self, pm): class MyPlugin: pass my = MyPlugin() pm.register(my) assert my in pm.get_plugins() my2 = MyPlugin() pm.register(my2) assert set([my, my2]).issubset(pm.get_plugins()) assert pm.is_registered(my) assert pm.is_registered(my2) pm.unregister(my) assert not pm.is_registered(my) assert my not in pm.get_plugins() def test_register_unknown_hooks(self, pm): class Plugin1: @hookimpl def he_method1(self, arg): return arg + 1 pname = pm.register(Plugin1()) 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] assert len(pm.get_hookcallers(pm.get_plugin(pname))) == 1 def test_register_historic(self, pm): 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)) l = [] class Plugin: @hookimpl def he_method1(self, arg): l.append(arg) pm.register(Plugin()) assert l == [1] class Plugin2: @hookimpl def he_method1(self, arg): l.append(arg * 10) pm.register(Plugin2()) assert l == [1, 10] pm.hook.he_method1.call_historic(kwargs=dict(arg=12)) assert l == [1, 10, 120, 12] def test_with_result_memorized(self, pm): class Hooks: @hookspec(historic=True) def he_method1(self, arg): pass pm.add_hookspecs(Hooks) he_method1 = pm.hook.he_method1 he_method1.call_historic(lambda res: l.append(res), dict(arg=1)) l = [] class Plugin: @hookimpl def he_method1(self, arg): return arg * 10 pm.register(Plugin()) assert l == [10] def test_register_historic_incompat_hookwrapper(self, pm): class Hooks: @hookspec(historic=True) def he_method1(self, arg): pass pm.add_hookspecs(Hooks) l = [] class Plugin: @hookimpl(hookwrapper=True) def he_method1(self, arg): l.append(arg) with pytest.raises(PluginValidationError): pm.register(Plugin()) def test_call_extra(self, pm): class Hooks: @hookspec def he_method1(self, arg): pass pm.add_hookspecs(Hooks) def he_method1(arg): return arg * 10 l = pm.hook.he_method1.call_extra([he_method1], dict(arg=1)) assert l == [10] def test_subset_hook_caller(self, pm): class Hooks: @hookspec def he_method1(self, arg): pass pm.add_hookspecs(Hooks) l = [] class Plugin1: @hookimpl def he_method1(self, arg): l.append(arg) class Plugin2: @hookimpl def he_method1(self, arg): l.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 l == [10, 1] l[:] = [] hc = pm.subset_hook_caller("he_method1", [plugin1]) hc(arg=2) assert l == [20] l[:] = [] hc = pm.subset_hook_caller("he_method1", [plugin2]) hc(arg=2) assert l == [2] l[:] = [] pm.unregister(plugin1) hc(arg=2) assert l == [] l[:] = [] pm.hook.he_method1(arg=1) assert l == [10] def test_add_hookspecs_nohooks(self, pm): with pytest.raises(ValueError): pm.add_hookspecs(10) class TestAddMethodOrdering: @pytest.fixture def hc(self, pm): class Hooks: @hookspec def he_method1(self, arg): pass pm.add_hookspecs(Hooks) return pm.hook.he_method1 @pytest.fixture def addmeth(self, hc): def addmeth(tryfirst=False, trylast=False, hookwrapper=False): def wrap(func): hookimpl(tryfirst=tryfirst, trylast=trylast, hookwrapper=hookwrapper)(func) hc._add_hookimpl(HookImpl(None, "", func, func.example_impl)) return func return wrap return addmeth def funcs(self, hookmethods): return [hookmethod.function for hookmethod in hookmethods] def test_adding_nonwrappers(self, hc, addmeth): @addmeth() def he_method1(): pass @addmeth() def he_method2(): pass @addmeth() def he_method3(): pass assert self.funcs(hc._nonwrappers) == [he_method1, he_method2, he_method3] def test_adding_nonwrappers_trylast(self, hc, addmeth): @addmeth() def he_method1_middle(): pass @addmeth(trylast=True) def he_method1(): pass @addmeth() def he_method1_b(): pass assert self.funcs(hc._nonwrappers) == \ [he_method1, he_method1_middle, he_method1_b] def test_adding_nonwrappers_trylast3(self, hc, addmeth): @addmeth() def he_method1_a(): pass @addmeth(trylast=True) def he_method1_b(): pass @addmeth() def he_method1_c(): pass @addmeth(trylast=True) def he_method1_d(): pass assert self.funcs(hc._nonwrappers) == \ [he_method1_d, he_method1_b, he_method1_a, he_method1_c] def test_adding_nonwrappers_trylast2(self, hc, addmeth): @addmeth() def he_method1_middle(): pass @addmeth() def he_method1_b(): pass @addmeth(trylast=True) def he_method1(): pass assert self.funcs(hc._nonwrappers) == \ [he_method1, he_method1_middle, he_method1_b] def test_adding_nonwrappers_tryfirst(self, hc, addmeth): @addmeth(tryfirst=True) def he_method1(): pass @addmeth() def he_method1_middle(): pass @addmeth() def he_method1_b(): pass assert self.funcs(hc._nonwrappers) == \ [he_method1_middle, he_method1_b, he_method1] def test_adding_wrappers_ordering(self, hc, addmeth): @addmeth(hookwrapper=True) def he_method1(): pass @addmeth() def he_method1_middle(): pass @addmeth(hookwrapper=True) def he_method3(): pass assert self.funcs(hc._nonwrappers) == [he_method1_middle] assert self.funcs(hc._wrappers) == [he_method1, he_method3] def test_adding_wrappers_ordering_tryfirst(self, hc, addmeth): @addmeth(hookwrapper=True, tryfirst=True) def he_method1(): pass @addmeth(hookwrapper=True) def he_method2(): pass assert hc._nonwrappers == [] assert self.funcs(hc._wrappers) == [he_method2, he_method1] def test_hookspec(self, pm): class HookSpec: @hookspec() def he_myhook1(self, arg1): pass @hookspec(firstresult=True) def he_myhook2(self, arg1): pass @hookspec(firstresult=False) def he_myhook3(self, arg1): pass pm.add_hookspecs(HookSpec) assert not pm.hook.he_myhook1.spec_opts["firstresult"] assert pm.hook.he_myhook2.spec_opts["firstresult"] assert not pm.hook.he_myhook3.spec_opts["firstresult"] def test_hookimpl(self): for name in ["hookwrapper", "optionalhook", "tryfirst", "trylast"]: for val in [True, False]: @hookimpl(**{name: val}) def he_myhook1(self, arg1): pass if val: assert he_myhook1.example_impl.get(name) else: assert not hasattr(he_myhook1, name) def test_decorator_functional(self, pm): class HookSpec: @hookspec(firstresult=True) def he_myhook(self, arg1): """ add to arg1 """ pm.add_hookspecs(HookSpec) class Plugin: @hookimpl() def he_myhook(self, arg1): return arg1 + 1 pm.register(Plugin()) results = pm.hook.he_myhook(arg1=17) assert results == 18 def test_load_setuptools_instantiation(self, monkeypatch, pm): pkg_resources = pytest.importorskip("pkg_resources") def my_iter(name): assert name == "hello" class EntryPoint: name = "myname" dist = None def load(self): class PseudoPlugin: x = 42 return PseudoPlugin() return iter([EntryPoint()]) monkeypatch.setattr(pkg_resources, 'iter_entry_points', my_iter) num = pm.load_setuptools_entrypoints("hello") assert num == 1 plugin = pm.get_plugin("myname") assert plugin.x == 42 assert pm.list_plugin_distinfo() == [(plugin, None)] def test_load_setuptools_not_installed(self, monkeypatch, pm): monkeypatch.setitem(sys.modules, 'pkg_resources', types.ModuleType("pkg_resources")) with pytest.raises(ImportError): pm.load_setuptools_entrypoints("qwe") def test_add_tracefuncs(self, he_pm): l = [] class api1: @hookimpl def he_method1(self): l.append("he_method1-api1") class api2: @hookimpl def he_method1(self): l.append("he_method1-api2") he_pm.register(api1()) he_pm.register(api2()) def before(hook_name, hook_impls, kwargs): l.append((hook_name, list(hook_impls), kwargs)) def after(outcome, hook_name, hook_impls, kwargs): l.append((outcome, hook_name, list(hook_impls), kwargs)) undo = he_pm.add_hookcall_monitoring(before, after) he_pm.hook.he_method1() assert len(l) == 4 assert l[0][0] == "he_method1" assert len(l[0][1]) == 2 assert isinstance(l[0][2], dict) assert l[1] == "he_method1-api2" assert l[2] == "he_method1-api1" assert len(l[3]) == 4 assert l[3][1] == l[0][0] undo() he_pm.hook.he_method1() assert len(l) == 4 + 2 def test_hook_tracing(self, he_pm): 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()) l = [] he_pm.trace.root.setwriter(l.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(l) == 2 assert 'he_method1' in l[0] assert 'finish' in l[1] l[:] = [] 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() def test_prefix_hookimpl(self): pm = PluginManager(hookspec.project_name, "hello_") class HookSpec: @hookspec def hello_myhook(self, arg1): """ add to arg1 """ pm.add_hookspecs(HookSpec) class Plugin: def hello_myhook(self, arg1): return arg1 + 1 pm.register(Plugin()) pm.register(Plugin()) results = pm.hook.hello_myhook(arg1=17) assert results == [18, 18] def test_parse_hookimpl_override(): 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 = {} return opts class Plugin: def x1meth(self): pass @hookimpl(hookwrapper=True, tryfirst=True) def x1meth2(self): pass class Spec: @hookspec def x1meth(self): pass @hookspec def x1meth2(self): pass pm = MyPluginManager(hookspec.project_name) pm.register(Plugin()) pm.add_hookspecs(Spec) assert not pm.hook.x1meth._nonwrappers[0].hookwrapper assert not pm.hook.x1meth._nonwrappers[0].tryfirst assert not pm.hook.x1meth._nonwrappers[0].trylast assert not pm.hook.x1meth._nonwrappers[0].optionalhook assert pm.hook.x1meth2._wrappers[0].tryfirst assert pm.hook.x1meth2._wrappers[0].hookwrapper def test_varnames(): def f(x): i = 3 # noqa class A: def f(self, y): pass class B(object): def __call__(self, z): pass assert varnames(f) == ("x",) assert varnames(A().f) == ('y',) assert varnames(B()) == ('z',) def test_varnames_default(): def f(x, y=3): pass assert varnames(f) == ("x",) def test_varnames_class(): class C: def __init__(self, x): pass class D: pass assert varnames(C) == ("x",) assert varnames(D) == () def test_formatdef(): 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)" class Test_MultiCall: def test_uses_copy_of_methods(self): l = [lambda: 42] mc = _MultiCall(l, {}) repr(mc) l[:] = [] res = mc.execute() return res == 42 def MC(self, methods, kwargs, firstresult=False): hookfuncs = [] for method in methods: f = HookImpl(None, "", method, method.example_impl) hookfuncs.append(f) return _MultiCall(hookfuncs, kwargs, {"firstresult": firstresult}) def test_call_passing(self): class P1: @hookimpl def m(self, __multicall__, x): assert len(__multicall__.results) == 1 assert not __multicall__.hook_impls return 17 class P2: @hookimpl def m(self, __multicall__, x): assert __multicall__.results == [] assert __multicall__.hook_impls return 23 p1 = P1() p2 = P2() multicall = self.MC([p1.m, p2.m], {"x": 23}) assert "23" in repr(multicall) reslist = multicall.execute() assert len(reslist) == 2 # ensure reversed order assert reslist == [23, 17] def test_keyword_args(self): @hookimpl def f(x): return x + 1 class A: @hookimpl def f(self, x, y): return x + y multicall = self.MC([f, A().f], dict(x=23, y=24)) assert "'x': 23" in repr(multicall) assert "'y': 24" in repr(multicall) reslist = multicall.execute() assert reslist == [24 + 23, 24] assert "2 results" in repr(multicall) def test_keyword_args_with_defaultargs(self): @hookimpl def f(x, z=1): return x + z reslist = self.MC([f], dict(x=23, y=24)).execute() assert reslist == [24] def test_tags_call_error(self): @hookimpl def f(x): return x multicall = self.MC([f], {}) pytest.raises(KeyError, multicall.execute) def test_call_subexecute(self): @hookimpl def m(__multicall__): subresult = __multicall__.execute() return subresult + 1 @hookimpl def n(): return 1 call = self.MC([n, m], {}, firstresult=True) res = call.execute() assert res == 2 def test_call_none_is_no_result(self): @hookimpl def m1(): return 1 @hookimpl def m2(): return None res = self.MC([m1, m2], {}, {"firstresult": True}).execute() assert res == 1 res = self.MC([m1, m2], {}, {}).execute() assert res == [1] def test_hookwrapper(self): l = [] @hookimpl(hookwrapper=True) def m1(): l.append("m1 init") yield None l.append("m1 finish") @hookimpl def m2(): l.append("m2") return 2 res = self.MC([m2, m1], {}).execute() assert res == [2] assert l == ["m1 init", "m2", "m1 finish"] l[:] = [] res = self.MC([m2, m1], {}, {"firstresult": True}).execute() assert res == 2 assert l == ["m1 init", "m2", "m1 finish"] def test_hookwrapper_order(self): l = [] @hookimpl(hookwrapper=True) def m1(): l.append("m1 init") yield 1 l.append("m1 finish") @hookimpl(hookwrapper=True) def m2(): l.append("m2 init") yield 2 l.append("m2 finish") res = self.MC([m2, m1], {}).execute() assert res == [] assert l == ["m1 init", "m2 init", "m2 finish", "m1 finish"] def test_hookwrapper_not_yield(self): @hookimpl(hookwrapper=True) def m1(): pass mc = self.MC([m1], {}) with pytest.raises(TypeError): mc.execute() def test_hookwrapper_too_many_yield(self): @hookimpl(hookwrapper=True) def m1(): yield 1 yield 2 mc = self.MC([m1], {}) with pytest.raises(RuntimeError) as ex: mc.execute() assert "m1" in str(ex.value) assert "test_pluggy.py:" in str(ex.value) @pytest.mark.parametrize("exc", [ValueError, SystemExit]) def test_hookwrapper_exception(self, exc): l = [] @hookimpl(hookwrapper=True) def m1(): l.append("m1 init") yield None l.append("m1 finish") @hookimpl def m2(): raise exc with pytest.raises(exc): self.MC([m2, m1], {}).execute() assert l == ["m1 init", "m1 finish"] class TestHookRelay: def test_hapmypath(self, pm): class Api: @hookspec def hello(self, arg): "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) l = hook.hello(arg=3) assert l == [4] assert not hasattr(hook, 'world') pm.unregister(plugin) assert hook.hello(arg=3) == [] def test_argmismatch(self, pm): 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(self, pm): class Api: @hookspec def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) pytest.raises(TypeError, lambda: pm.hook.hello(3)) def test_firstresult_definition(self, pm): class Api: @hookspec(firstresult=True) def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) class Plugin: @hookimpl def hello(self, arg): return arg + 1 pm.register(Plugin()) res = pm.hook.hello(arg=3) assert res == 4 class TestTracer: def test_simple(self): rootlogger = _TagTracer() log = rootlogger.get("pytest") log("hello") l = [] rootlogger.setwriter(l.append) log("world") assert len(l) == 1 assert l[0] == "world [pytest]\n" sublog = log.get("collection") sublog("hello") assert l[1] == "hello [pytest:collection]\n" def test_indent(self): rootlogger = _TagTracer() log = rootlogger.get("1") l = [] log.root.setwriter(lambda arg: l.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(l) == 7 names = [x[:x.rfind(' [')] for x in l] assert names == ['hello', ' line1', ' line2', ' line3', ' line4', ' line5', 'last'] def test_readable_output_dictargs(self): rootlogger = _TagTracer() 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(self): rootlogger = _TagTracer() log = rootlogger.get("1") log2 = log.get("2") assert log2.tags == tuple("12") l = [] rootlogger.setprocessor(tuple("12"), lambda *args: l.append(args)) log("not seen") log2("seen") assert len(l) == 1 tags, args = l[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",) def test_setmyprocessor(self): rootlogger = _TagTracer() log = rootlogger.get("1") log2 = log.get("2") l = [] log2.setmyprocessor(lambda *args: l.append(args)) log("not seen") assert not l log2(42) assert len(l) == 1 tags, args = l[0] assert "1" in tags assert "2" in tags assert args == (42,) pluggy-0.3.1/.gitignore0000664000175000017500000000130412576504560014412 0ustar hpkhpk00000000000000# 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 nosetests.xml coverage.xml *,cover # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ *.swp pluggy-0.3.1/setup.py0000664000175000017500000000260412576504560014140 0ustar hpkhpk00000000000000import os import sys import setuptools from setuptools import setup classifiers = [ 'Development Status :: 4 - Beta', '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 :: %s' % x) for x in '2 2.6 2.7 3 3.3 3.4 3.5'.split()] with open('README.rst') as fd: long_description = fd.read() def get_version(): p = os.path.join(os.path.dirname( os.path.abspath(__file__)), "pluggy.py") with open(p) as f: for line in f.readlines(): if "__version__" in line: return line.strip().split("=")[-1].strip(" '") raise ValueError("could not read version") def main(): setup( name='pluggy', description='plugin and hook calling mechanisms for python', long_description=long_description, version=get_version(), license='MIT license', platforms=['unix', 'linux', 'osx', 'win32'], author='Holger Krekel', author_email='holger at merlinux.eu', classifiers=classifiers, py_modules=['pluggy'], ) if __name__ == '__main__': main()