[pytest源码3]-pluggy代码结构与核心设计

前言

现在我们开始分析,按照demo代码顺序先进行简单分析。
个人拙见,有错请各位指出。
如果的我的文章对您有帮助,不符动动您的金手指给个Star,予人玫瑰,手有余香,不胜感激。 GitHub



pluggy代码结构

按照前面demo中的代码顺序,在分析pluggy的核心逻辑之前,我们先来了解HookspecMarkerHookspecMarker的用处是什么?

1.HookspecMarker的实现逻辑是什么?

我们来先来看它的代码注释
class HookspecMarker(object):
      """ 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
  • 我们可以传入project_name实例化HookspecMarker以获得装饰器,当我们调用PluginManager.add_hookspec将会寻找所有与当前PluginManagerproject_name的标记函数,这也是前面要求整个项目project name一致的原因之一。
def __call__(
        self, function=None, firstresult=False, historic=False, warn_on_impl=None
    ):
        """ 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,
                    warn_on_impl=warn_on_impl,
                ),
            )
            return func

        if function is not None:
            return setattr_hookspec_opts(function)
        else:
            return setattr_hookspec_opts
  • 通过分析__call__的逻辑代码可以发现,主要功能是调用了一个setattr(object, name, value),给被装饰的函数新增一个属性project_nam + _spec,并且该属性的value为装饰器参数取值。


2.HookspecMarker的实现逻辑是什么?

HookimplMarker的实现逻辑类似,区别在于被装饰的函数新增的属性为project_name + _impl,下面只显示了部分代码
        def setattr_hookimpl_opts(func)
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值