zoukankan      html  css  js  c++  java
  • pytest插件探索——hook开发

    前言

    参考官方的这篇文章,我尝试翻译其中一些重点部分,并且拓展了相关的pluggy部分的知识。由于pytest是在pluggy基础上构建的,强烈建议先阅读一下pluggy的官方文档,这样理解起来更加容易一点。

    正文

    conftest.py可以作为最简单的本地plugin调用一些hook函数,以此来做些强化功能。pytest整个框架通过调用如下定义良好的hooks来实现配置,收集,执行和报告这些过程:

    • 内置plugins:从代码内部的_pytest目录加载;
    • 外部插件(第三方插件):通过setuptools entry points机制发现的第三方插件模块;
    • conftest.py形式的本地插件:测试目录下的自动模块发现机制;

    原则上,每个hook都是一个 1:N 的python函数调用, 这里的 N 是对一个给定hook的所有注册调用数。所有的hook函数都使用pytest_xxx的命名规则,以便于查找并且同其他函数区分开来。

    资源网站大全 https://55wd.com 我的007办公资源网站 https://www.wode007.com

    decorrator

    pluggy里提供了两个decorator helper类,分别是HookspecMarkerHookimplMarker,通过使用相同的project_name参数初始化得到对应的装饰器,后续可以用这个装饰器将函数标记为hookspechookimpl

    hookspec

    hook specification (hookspec)用来validate每个hookimpl,保证hookimpl被正确的定义。

    hookspec 通过 add_hookspecs()方法加载,一般在注册hookimpl之前先加载;

    hookimpl

    hook implementation (hookimpl) 是一个被恰当标记过的回调函数。hookimpls 通过register()方法加载。

    注:为了保证hookspecs在项目里可以不断演化, hookspec里的参数对于hookimpls是可选的,即可以定义少于spec里定义数量的参数。

    hookwrapper

    hookimpl 里还有一个hookwrapper选项,用来表示这个函数是个hookwrapper函数。hookwrapper函数可以在普通的非wrapper的hookimpls执行的前后执行一些其他代码, 类似于@contextlib.contextmanager,hookwrapper必须在它的主体包含单一的yield,用来实现生成器函数,例如:

    import pytest
    
    @pytest.hookimpl(hookwrapper=True)
    def pytest_pyfunc_call(pyfuncitem):
        do_something_before_next_hook_executes()
    
        outcome = yield
        # outcome.excinfo may be None or a (cls, val, tb) tuple
    
        res = outcome.get_result()  # will raise if outcome was exception
    
        post_process_result(res)
    
        outcome.force_result(new_res)  # to override the return value to the plugin system
    

      

    生成器发送一个 pluggy.callers._Result对象 , 这个对象可以在 yield表达式里指定并且通过 force_result()或者get_result() 方法重写或者拿到最终结果。

    注:hookwrapper不能返回结果 (跟所有的生成器函数一样);

    hookimpl的调用顺序

    默认情况下,hook的调用顺序遵循注册时的顺序LIFO(后进先出),hookimpl允许通过tryfirst, trylast*选项调整这一项顺序。

    举个例子,对于如下的代码:

    # Plugin 1
    @pytest.hookimpl(tryfirst=True)
    def pytest_collection_modifyitems(items):
        # will execute as early as possible
        ...
    
    
    # Plugin 2
    @pytest.hookimpl(trylast=True)
    def pytest_collection_modifyitems(items):
        # will execute as late as possible
        ...
    
    
    # Plugin 3
    @pytest.hookimpl(hookwrapper=True)
    def pytest_collection_modifyitems(items):
        # will execute even before the tryfirst one above!
        outcome = yield
        # will execute after all non-hookwrappers executed
    

      

    执行顺序如下:

    1. Plugin3的pytest_collection_modifyitems先调用,直到yield点,因为这是一个hook warpper。
    2. Plugin1的pytest_collection_modifyitems被调用,因为有 tryfirst=True参数。
    3. Plugin2的pytest_collection_modifyitems被调用,因为有 trylast=True参数 (不过即使没有这个参数也会排在tryfirst标记的plugin后面)。
    4. Plugin3的pytest_collection_modifyitems调用yield后面的代码. yield接收非Wrapper的result返回. Wrapper函数不应该修改这个result。

    当然也可以同时将 tryfirst 和 trylast与 hookwrapper=True 混用,这种情况下它将影响hookwrapper之间的调用顺序.

    hook执行结果处理和firstresult选项

    默认情况下,调用一个hook会使底层的hookimpl函数在一个循环里按顺序执行,并且将其非空的执行结果添加到一个list里面。例外的是,hookspec里有一个firstresult选项,如果指定这个选项为true,那么得到第一个返回非空的结果的hookimpl执行后就直接返回,后续的hookimpl将不在被执行,参考后面的例子。

    注: hookwrapper还是正常的执行

    hook的调用

    每一个pluggy.PluginManager 都有一个hook属性, 可以通过调用这个属性的call函数来调用hook,需要注意的是,调用时必须使用关键字参数语法来调用。

    请看下面这个firstresult和hook调用例子:

    from pluggy import PluginManager, HookimplMarker, HookspecMarker
    
    hookspec = HookspecMarker("myproject")
    hookimpl = HookimplMarker("myproject")
    
    
    class MySpec1(object):
        @hookspec
        def myhook(self, arg1, arg2):
            pass
    
    
    class MySpec2(object):
        # 这里将firstresult设置为True
        @hookspec(firstresult=True)
        def myhook(self, arg1, arg2):
            pass
    
    
    class Plugin1(object):
        @hookimpl
        def myhook(self, arg1, arg2):
            """Default implementation.
            """
            return 1
    
    
    class Plugin2(object):
        # hookimpl可以定义少于hookspec里定义数量的参数,这里只定义arg1
        @hookimpl
        def myhook(self, arg1):
            """Default implementation.
            """
            return 2
    
    
    class Plugin3(object):
        # 同上,甚至可以不定义hookspec里的参数 
        @hookimpl
        def myhook(self):
            """Default implementation.
            """
            return 3
    
    
    pm1 = PluginManager("myproject")
    pm2 = PluginManager("myproject")
    pm1.add_hookspecs(MySpec1)
    pm2.add_hookspecs(MySpec2)
    pm1.register(Plugin1())
    pm1.register(Plugin2())
    pm1.register(Plugin3())
    pm2.register(Plugin1())
    pm2.register(Plugin2())
    pm2.register(Plugin3())
    # hook调用必须使用关键字参数的语法
    print(pm1.hook.myhook(arg1=None, arg2=None))
    print(pm2.hook.myhook(arg1=None, arg2=None))
    

      

    得到结果如下:

    [3, 2, 1]
    3

    可以看到,由于pm2里的hookspec里有firstresult参数,在得到3这个非空结果时就直接返回了。

  • 相关阅读:
    laravel如何自定义一个路由文件
    RGAC-laravel权限管理
    导航栏下划线跟随
    php简单的判断用户登陆
    php判断文件上传的类型
    git 如何删除仓库中的文件
    laravle中config( )函数的使用
    [leetcode] Count and Say
    [leetcode] Sudoku Solver
    [leetcode] Search Insert Position
  • 原文地址:https://www.cnblogs.com/ypppt/p/13371060.html
Copyright © 2011-2022 走看看