首页 > 其他分享 >【原创】Invoke用例分析

【原创】Invoke用例分析

时间:2024-07-02 09:54:37浏览次数:13  
标签:原创 Invoke invoke yaml 用例 任务 inactive download console

Nextgen的测试自动化系统(以下称为NextgenTA)使用Invoke来作为命令行工具。Invoke 是一个 Python 库,用于构建和执行任务。它提供了一种简单且灵活的方式来定义、组织和执行命令行任务,是 Fabric 的现代替代品。由于Fabric的设计比较老旧且依赖 SSH,这导致了很多使用场景受限,仅适用于远程服务器管理。为了提供一个更加通用和现代的任务执行工具,Invoke 便应运而生了。

项目:

https://github.com/pyinvoke/invoke

以下将以NextgenTA的常用任务为例,解析NextgenTA对Invoke的使用。

功能

  1. 任务定义

    以NexgenTA常用的一些任务为例。

    • 使用 Python 函数定义任务,通过装饰器将这些函数标记为任务。
    • 支持为任务添加描述和参数,参数可以有默认值,也可以是必需的。

    以下载模拟器任务为例:

    @task(default=True, aliases=["dl", "download"])
    def download_interactive(c, include_inactive=False, skip_tools=False):
        """Interactive download of nextgen SW simulators (actively being developed), middleware and tools
    
        Answer questions "Y/N" which simulator variants to wipeoff, download and unzip in proper place.
        "No" means don't touch the current simulator.
    
        Simulators which are not actively being developed has "active: False" directive in the Invoke.yaml file.
        If for some reason, you want such simulator to be dowloaded, you can use option: --include-inactive
    
        Default artifacts are the latest _green_ from "default" branch (invoke.yaml contains the defaults).
    
        If you need to download an specific build and/or branch of an artifact, create custom `invoke.yaml`
        file with similar data and use `-f invoke-custom.yaml` to override default download parameters.
        """
        hwcompat_excludes = set()
    
        from rich.console import Console
        from rich.panel import Panel
        from rich.prompt import Confirm
    
        console = Console()
        text = f"[yellow]Destination directory: [b]{DEST_DIR}[/b]"
        console.print(Panel(text))
    
        if not include_inactive:
            inactive_hwcompats = list(iter_inactive_hwcompats(c))
            for variant in c.HWCOMPATS.keys():
                if variant in inactive_hwcompats:
                    hwcompat_excludes.add(variant)
    
        if not Confirm.ask("Download all HW variants?", default=True):
            for variant in c.HWCOMPATS.keys():
                if variant not in hwcompat_excludes and not Confirm.ask(
                    f"Download HW variant {variant}?", default=True
                ):
                    hwcompat_excludes.add(variant)
    
        if not Confirm.ask("Continue?", default=True):
            return
    
        mao = wbtool = suuntoplus = sds = not skip_tools
        dl_list = list(
            _iter_teamcity_downloads(
                c,
                hwcompat_excludes,
                simu=True,
                sds=sds,
                mao=mao,
                wbtool=wbtool,
                suuntoplus=suuntoplus,
            )
        )
    
        loop = asyncio.get_event_loop()
        try:
            console.rule("[bold red] Empty directories")
            with console.status("[bold green]Cleaning directories..."):
                loop.run_until_complete(empty_dir_task(dl_list))
            console.rule("[bold red] Download builds")
            loop.run_until_complete(download_task(dl_list))
            console.rule("[bold red] Unzip archives")
            with console.status("[bold green]Unzipping..."):
                loop.run_until_complete(unzip_task(dl_list))
        finally:
            loop.close()
        console.print(":thumbs_up: [green]Done")
    
    

    在该任务中:

    @task 装饰器是任务标志,其参数中 aliases=["dl", "download"]设置任务别名,所以在执行命令时,以下三种写法都正确:

    pipenv run invoke builds

    pipenv run invoke builds.dl

    pipenv run invoke builds.download

    函数 def download_interactive(c, include_inactive=False, skip_tools=False): 是任务的具体定义,从上到下依次为命令行美化,命令行交互,以及异步下载部分。

  2. 任务组织

    • 可以将任务组织在模块中,并通过命名空间进行管理。
    • 支持分层命名空间,便于大型项目的任务组织。
    from invoke import Collection
    
    ns = Collection()
    ns.add_collection(builds)
    
  3. 命令行接口

    • 提供一个强大的命令行接口来执行任务。
    • 支持自动生成帮助信息,方便用户了解可用的任务和参数。
    $ pipenv run inv builds --help
    Loading .env environment variables...
    Usage: inv[oke] [--core-opts] builds.download-interactive [--options] [other tasks here ...]
    
    Docstring:
      Interactive download of nextgen SW simulators (actively being developed), middleware and tools
    
      Answer questions "Y/N" which simulator variants to wipeoff, download and unzip in proper place.
      "No" means don't touch the current simulator.
    
      Simulators which are not actively being developed has "active: False" directive in the Invoke.yaml file.
      If for some reason, you want such simulator to be dowloaded, you can use option: --include-inactive
    
      Default artifacts are the latest _green_ from "default" branch (invoke.yaml contains the defaults).
    
      If you need to download an specific build and/or branch of an artifact, create custom `invoke.yaml`
      file with similar data and use `-f invoke-custom.yaml` to override default download parameters.
    
    Options:
      -i, --include-inactive
      -s, --skip-tools
    
  4. 参数处理

    • 支持位置参数和关键字参数,参数可以是字符串、整数、布尔值等。
    • 支持命令行参数解析和类型转换。
    @task(default=True, aliases=["dl", "download"])
    def download_interactive(c, include_inactive=False, skip_tools=False):
        """Interactive download of nextgen SW simulators (actively being developed), middleware and tools
        ...
    
  5. 任务依赖

    • 支持任务之间的依赖关系,一个任务可以其他任务,确保任务按顺序执行。(以停止sds为例)
    **@task(post=[status])**
    def stop(c):
        """Terminate SDS Application Server"""
        stop_server()
        time.sleep(1)
    
  6. 运行命令

    • 提供便捷的方法在任务中运行系统命令,通过 run 方法执行 shell 命令,并获取输出。(以robot.clean任务为例)
    @task
    def clean(c):
        """Wipe out old Robot results from filesystem"""
        path = "results"
        if os.path.isdir(path):
            shutil.rmtree(path)
        os.mkdir(path)
    
        if os.path.isdir(DEBUGLOGS_DIR):
            logging.shutdown()
            shutil.rmtree(DEBUGLOGS_DIR)
        os.mkdir(DEBUGLOGS_DIR)
        **c.run(f"git restore {DEBUGLOGS_DIR}")**
    
        Console().print(
            f":thumbs_up: [green]Robot [i]outputdir[/i] ([b]{path}[/b]) is empty"
        )
    
    
  7. 配置管理

    • 支持全局配置、本地配置和环境变量配置。
    • 配置可以通过 .invoke.yaml 文件进行管理,方便定制和扩展: 以下是Por模拟器下载在invoke.ymal的配置内容
        ...
        
        M:
          project: Products_Porvoo_VisualStudio2015Application
          test_builds:
            high: Testing_AcceptanceTests_DockerizedTests_ShortTests_AcceptanceTestsPorvooHighImpactDocker
            low: Testing_AcceptanceTests_DockerizedTests_Long_AcceptanceTestsPorvooLowImpactDocker
          branch: develop
          build: ".lastSuccessful"
          target_dir: "{basedir}/simulator/hwcompat_M"
          filename: simulator.zip
         
         ...
    
  8. 并行执行

    • 支持任务并行执行,可以通过 ThreadingMultiprocessing 实现并行任务处理,提高效率。

标签:原创,Invoke,invoke,yaml,用例,任务,inactive,download,console
From: https://www.cnblogs.com/fRe-Bourne/p/18279326

相关文章

  • 【pytest】失败用例,桌面截图
    @pytest.hookimpl(tryfirst=True,hookwrapper=True)defpytest_runtest_makereport(item,call):#executeallotherhookstoobtainthereportobjectoutcome=yieldrep=outcome.get_result()#rep可以拿到用例的执行结果详情ifrep.when=="ca......
  • 妙笔生词是AI音乐创作领域自动写原创歌词的软件
    妙笔生词是一个通过AI人工智能技术实现智能写歌词的软件,是歌词创作必不可少的辅助工具,可以给作词人带来灵感、带来好的词句、好的韵脚、好的意境等等,能够根据作词人的要求,写出各种风格的歌词,比如流行歌词,民谣歌词,摇滚歌词,中国风歌词,儿歌等等,还能根据押韵要求,写出符合作词人要求的......
  • 独家原创 | Matlab实现CNN-Transformer多变量回归预测
    独家原创|Matlab实现CNN-Transformer多变量回归预测目录独家原创|Matlab实现CNN-Transformer多变量回归预测效果一览基本介绍程序设计参考资料效果一览基本介绍1.Matlab实现CNN-Transformer多变量回归预测;2.运行环境为Matlab2023b及以上;3.data为数......
  • VBox和HBox的用法及用例
    JavaFX中的VBox和HBox是两种常用的布局组件,分别用于垂直和水平布局。它们继承自Pane类,可以包含多个子节点,并且子节点会按照指定的方向排列。VBox(垂直框)VBox组件按照垂直方向排列子节点,子节点上下排列。基本用法:使用getChildren().add(node)方法添加子节点。可以通......
  • 基于Springboot的原创歌曲分享平台(有报告)。Javaee项目,springboot项目。
    演示视频:基于Springboot的原创歌曲分享平台(有报告)。Javaee项目,springboot项目。项目介绍:采用M(model)V(view)C(controller)三层体系结构,通过Spring+SpringBoot+Mybatis+Vue+Maven+Layui+Elementui来实现。MySQL数据库作为系统数据储存平台,实现了基于B/S结构的Web系统......
  • 测试:设计测试用例
    文章目录概念设计正交法判定表法本篇总结的是测试用例的概念和设计方法概念测试用例是为了实施测试而向被测试的系统提供的一组集合,这个集合中包含的内容有测试环境,操作步骤,测试数据,预期结果等要素在测试用例的设计中,一个原则是,测试用例要对于预期的结果做出定义,......
  • 【pytest】 用例运行时间统计
    使用 --duration 参数:pytest 提供了一个 --duration 参数,它可以在测试运行后显示最慢的N个测试用例的运行时间。例如,要显示最慢的10个测试用例的运行时间,你可以使用以下命令: pytest--duration=10 使用 pytest-benchmark 插件:虽然 pytest-benchmark ......
  • 【原创】EtherCAT主站IgH解析(二)-- Linux/Windows/RTOS等多操作系统IgH EtherCAT主站
    版权声明:本文为本文为博主原创文章,转载请注明出处。如有问题,欢迎指正。博客地址:https://www.cnblogs.com/wsg1100/前言目前,EtherCAT商用主站有:Acontis、TwinCAT3、KPA、Codesys等,开源EtherCAT主站则主要有两大方案:igh与SOEM,两者设计天差地别,SOEM开源于2008年底1.1.2版本,具备良好......
  • 转:重磅原创)冬之焱: 谈谈Linux内核的栈回溯与妙用
     unwind.c//SPDX-License-Identifier:GPL-2.0-only/**arch/arm/kernel/unwind.c**Copyright(C)2008ARMLimited**StackunwindingsupportforARM**AnARMEABIversionofgccisrequiredtogeneratetheunwind*tables.Forinformationab......
  • 用Automa做的抖音博主视频批量采集器升级版-实战原创
    文章目录前言一、抖音博主视频批量采集器升级版是什么?二、抖音博主视频批量采集器工作流流程图三、流程拆解1.第一步2.第二步3.第三步4.第四步5.第五步6.第六步总结前言Automa开发2年时间,开发应用100多款,分享开发记录市面上的抖音批量下载的工具非常多,用Automa......