BDD - Python Behave 配置文件 behave.ini

BDD - Python Behave 配置文件 behave.ini

  • 引言
  • behave.ini
    • 配置参数的类型
    • 配置项
  • behave.ini 应用
    • feature 文件
    • step 文件
    • 创建 behave.ini
    • 执行 Behave
    • 查看配置默认值 behave -v

引言

前面文章 《BDD - Python Behave Runner Script》就是为了每次执行 Behave 时不用手动敲一长串选项,其实还有另外一种实现方式,那就是通过配置文件指定 Behave 的命令行参数和设置。今天就来了解一下 Behave 的配置。

想了解更多 Behave 相关的文章,欢迎阅读《Python BDD Behave 系列》,持续更新中。

behave.ini

behave.ini 文件是 Behave 的配置文件,用于设置 Behave 命令行选项,配置文件必须以标签 “[behave]” 开头。

配置参数的类型

  1. text 文本
    将提供的任何文本分配给配置设置
tags=smoke
  1. bool 布尔值
    为配置设置分配一个布尔值。文本描述当值为 true 时的功能。
    True 值为" 1 “,” yes ", " True “和” on "。
    False 值为“0”、“no”、“False”和“off”。
dry_run = false
  1. sequence 系列文本
    字段在新行上接受一个或多个值,例如 tags 的配置
    tag 带不带 @, Behave 都无所谓能识别到。
tags=@foo,~@bar@zap

相当于 --tags= @foo,~@bar --tags=@zap

配置项

基本上 Behave 的配置项跟 Behave 命令行选项是对应的,但是这里请注意配置项的名字并不是一一对应的,具体可参考官方文档 Behave Configuration

例如:
命令选项 –dry-run,配置项名字却是 dry_run
命令选项 –o 或 --outfile,配置项名字却是 outfiles

查看 Behave 命令行选项
执行命令:behave -h

PS C:\Automation\Test> behave -h
usage: behave [options] [ [DIR|FILE|FILE:LINE] ]+Run a number of feature tests with behave.positional arguments:paths                 Feature directory, file or file location (FILE:LINE).optional arguments:-h, --help            show this help message and exit-c, --no-color        Disable the use of ANSI color escapes.--color               Use ANSI color escapes. This is the default behaviour. This switch is    used to override a configuration file setting.-d, --dry-run         Invokes formatters without executing the steps.-D NAME=VALUE, --define NAME=VALUEDefine user-specific data for the config.userdata dictionary. Example:   -D foo=bar to store it in config.userdata["foo"].-e PATTERN, --exclude PATTERNDon't run feature files matching regular expression PATTERN.-i PATTERN, --include PATTERNOnly run feature files matching regular expression PATTERN.--no-junit            Don't output JUnit-compatible reports.--junit               Output JUnit-compatible reports. When junit is enabled, all stdout and   stderr will be redirected and dumped to the junit report, regardless of  the "--capture" and "--no-capture" options.--junit-directory PATHDirectory in which to store JUnit reports.-f FORMAT, --format FORMATSpecify a formatter. If none is specified the default formatter is       used. Pass "--format help" to get a list of available formatters.        --steps-catalog       Show a catalog of all available step definitions. SAME AS:--format=steps.catalog --dry-run --no-summary -q-k, --no-skipped      Don't print skipped steps (due to tags).--show-skipped        Print skipped steps. This is the default behaviour. This switch is used  to override a configuration file setting.--no-snippets         Don't print snippets for unimplemented steps.--snippets            Print snippets for unimplemented steps. This is the default behaviour.   This switch is used to override a configuration file setting.-m, --no-multiline    Don't print multiline strings and tables under steps.--multiline           Print multiline strings and tables under steps. This is the default      behaviour. This switch is used to override a configuration filesetting.-n NAME, --name NAME  Only execute the feature elements which match part of the given name.    If this option is given more than once, it will match against all the    given names.--no-capture          Don't capture stdout (any stdout output will be printed immediately.)    --capture             Capture stdout (any stdout output will be printed if there is afailure.) This is the default behaviour. This switch is used tooverride a configuration file setting.--no-capture-stderr   Don't capture stderr (any stderr output will be printed immediately.)    --capture-stderr      Capture stderr (any stderr output will be printed if there is afailure.) This is the default behaviour. This switch is used tooverride a configuration file setting.--no-logcapture       Don't capture logging. Logging configuration will be left intact.        --logcapture          Capture logging. All logging during a step will be captured anddisplayed in the event of a failure. This is the default behaviour.      This switch is used to override a configuration file setting.--logging-level LOGGING_LEVELSpecify a level to capture logging at. The default is INFO - capturing   everything.--logging-format LOGGING_FORMATSpecify custom format to print statements. Uses the same format as used  by standard logging handlers. The default is"%(levelname)s:%(name)s:%(message)s".--logging-datefmt LOGGING_DATEFMTSpecify custom date/time format to print statements. Uses the same       format as used by standard logging handlers.--logging-filter LOGGING_FILTERSpecify which statements to filter in/out. By default, everything is     captured. If the output is too verbose, use this option to filter out    needless output. Example: --logging-filter=foo will capture statements   issued ONLY to foo or foo.what.ever.sub but not foobar or other logger.  Specify multiple loggers with comma: filter=foo,bar,baz. If any logger   name is prefixed with a minus, eg filter=-foo, it will be excluded       rather than included.--logging-clear-handlersClear all other logging handlers.--no-summary          Don't display the summary at the end of the run.--summary             Display the summary at the end of the run.-o FILE, --outfile FILEWrite to specified file instead of stdout.-q, --quiet           Alias for --no-snippets --no-source.-s, --no-source       Don't print the file and line of the step definition with the steps.     --show-source         Print the file and line of the step definition with the steps. This is   the default behaviour. This switch is used to override a configuration   file setting.--stage STAGE         Defines the current test stage. The test stage name is used as name      prefix for the environment file and the steps directory (instead of      default path names).--stop                Stop running tests at the first failure.-t TAG_EXPRESSION, --tags TAG_EXPRESSIONOnly execute features or scenarios with tags matching TAG_EXPRESSION.    Pass "--tags-help" for more information.-T, --no-timings      Don't print the time taken for each step.--show-timings        Print the time taken, in seconds, of each step after the step has        completed. This is the default behaviour. This switch is used tooverride a configuration file setting.-v, --verbose         Show the files and features loaded.-w, --wip             Only run scenarios tagged with "wip". Additionally: use the "plain"      formatter, do not capture stdout or logging output and stop at the       first failure.-x, --expand          Expand scenario outline tables in output.--lang LANG           Use keywords for a language other than English.--lang-list           List the languages available for --lang.--lang-help LANG      List the translations accepted for one language.--tags-help           Show help for tag expressions.--version             Show version.

behave.ini 应用

下面通常简单的实例来应用一下 Behave 的配置,项目结构如下:

在这里插入图片描述

feature 文件

创建 shopping_cart.feature,加上一些 tags

# shopping_cart.featureFeature: Shopping Cart and Order Process@cart @smokeScenario: Guest user adds items to the cartGiven the user is on the home pageWhen the user adds an item to the cartThen the user should see the item in the cart@cart @regressionScenario: Registered user removes items from the cartGiven the user is logged inAnd the user has items in the cartWhen the user removes an item from the cartThen the user should see the updated cart@order @smokeScenario: Guest user places an orderGiven the user is on the home pageWhen the user adds an item to the cartAnd the user proceeds to checkoutAnd the user completes the orderThen the user should receive an order confirmation@order @regressionScenario: Registered user tracks an orderGiven the user is logged inAnd the user has placed an orderWhen the user checks the order statusThen the user should see the current order status

step 文件

创建 calculator_steps.py 文件

# calculator_steps.pyfrom behave import given, when, then@given('the calculator is turned on')
def step_calculator_turned_on(context):context.calculator_on = True    @when('I add {num1:d} and {num2:d}')
def step_add_numbers(context, num1, num2):context.result = num1 + num2@then('the result should be {expected_result:d}')
def step_check_result(context, expected_result):assert context.result == expected_result, f"Actual result: {context.result}, Expected result: {expected_result}"

创建 behave.ini

这里将配置文件和 feature, steps 文件夹是同级的, 配置了一些常用的 Behave 命令选项:

  • 配置 feature 的路径:paths=BDD/Features/tag_example
  • disable dry-run 执行步骤:dry_run = false
  • 配置标签为 smoke 且 为 cart 的测试用例:tags=smoke
    cart
  • 配置 format 为自定义的 my_html:format = my_html
  • 配置输出文件为 my_report.html :outfiles = my_report.html
  • 配置自定义输出格式 my_html
 [behave.formatters]
my_html = behave_html_formatter:HTMLFormatter

上面就是配置自定义的 my_html 的输出格式是 behave_html_formatter

behave.formatters 模块是 Behave 框架中用于处理格式化输出的模块,可以自定义。它包含了一些用于定义和管理不同输出格式的类。这些类负责将测试结果以各种方式呈现,比如在终端上显示、生成报告文件等。详情请参考 Behave Formatter

所以整个配置内容如下:

# behave.ini
[behave]
paths=BDD/Features/tag_example
dry_run = false
tags=smokecart
format = my_html
outfiles = my_report.html[behave.formatters]
my_html = behave_html_formatter:HTMLFormatter

执行 Behave

只需执行命令 behave,不用敲那么命令了,只有 BDD/Features/tag_example 文件夹下的 标签为 smoke 且为 cart 的测试用例执行了,并且生成了自定义的 html 测试报告。

PS C:\Automation\Test> behave
Feature: Shopping Cart and Order Process # BDD/Features/tag_example/shopping_cart.feature:3@cart @smokeScenario: Guest user adds items to the cart     # BDD/Features/tag_example/shopping_cart.feature:6Given the user is on the home page            # BDD/steps/shopping_cart_steps.py:27When the user adds an item to the cart        # BDD/steps/shopping_cart_steps.py:40Then the user should see the item in the cart # BDD/steps/shopping_cart_steps.py:61@cart @regressionScenario: Registered user removes items from the cart  # BDD/Features/tag_example/shopping_cart.feature:12Given the user is logged in                          # NoneAnd the user has items in the cart                   # NoneWhen the user removes an item from the cart          # NoneThen the user should see the updated cart            # None@order @smokeScenario: Guest user places an order                 # BDD/Features/tag_example/shopping_cart.feature:19Given the user is on the home page                 # NoneWhen the user adds an item to the cart             # NoneAnd the user proceeds to checkout                  # NoneAnd the user completes the order                   # NoneThen the user should receive an order confirmation # None@order @regressionScenario: Registered user tracks an order           # BDD/Features/tag_example/shopping_cart.feature:27Given the user is logged in                       # NoneAnd the user has placed an order                  # NoneWhen the user checks the order status             # NoneThen the user should see the current order status # None1 feature passed, 0 failed, 0 skipped
1 scenario passed, 0 failed, 3 skipped
3 steps passed, 0 failed, 13 skipped, 0 undefined
Took 0m0.000s

生成了 html 测试报告:

在这里插入图片描述

查看配置默认值 behave -v

如果您想知道 behave 从哪里获得其配置默认值,您可以使用 “-v” 命令行参数,它会告诉您。

PS C:\Automation\Test> behave -v
Loading config defaults from "./behave.ini"
Using defaults:color Falseshow_snippets Trueshow_skipped Truedry_run Falseshow_source Trueshow_timings Truestdout_capture Truestderr_capture Truelog_capture Truelogging_format %(levelname)s:%(name)s:%(message)slogging_level 20steps_catalog Falsesummary Truejunit Falsestage Noneuserdata {}default_format prettydefault_tags
scenario_outline_annotation_schema {name} -- @{row.id} {examples.name}format ['my_html']outfiles ['my_report.html']paths ['BDD\\Features\\tag_example']tags ['smoke', 'cart']
more_formatters {'my_html': 'behave_html_formatter:HTMLFormatter'}
Supplied path: "BDD\Features\tag_example"
Trying base directory: C:\Automation\Test\BDD\Features\tag_example
Trying base directory: C:\Automation\Test\BDD\Features
Trying base directory: C:\Automation\Test\BDD
Feature: Shopping Cart and Order Process # BDD/Features/tag_example/shopping_cart.feature:3@cart @smokeScenario: Guest user adds items to the cart     # BDD/Features/tag_example/shopping_cart.feature:6Given the user is on the home page            # BDD/steps/shopping_cart_steps.py:27When the user adds an item to the cart        # BDD/steps/shopping_cart_steps.py:40Then the user should see the item in the cart # BDD/steps/shopping_cart_steps.py:61@cart @regressionScenario: Registered user removes items from the cart  # BDD/Features/tag_example/shopping_cart.feature:12Given the user is logged in                          # NoneAnd the user has items in the cart                   # NoneWhen the user removes an item from the cart          # NoneThen the user should see the updated cart            # None@order @smokeScenario: Guest user places an order                 # BDD/Features/tag_example/shopping_cart.feature:19Given the user is on the home page                 # NoneWhen the user adds an item to the cart             # NoneAnd the user proceeds to checkout                  # NoneAnd the user completes the order                   # NoneThen the user should receive an order confirmation # None@order @regressionScenario: Registered user tracks an order           # BDD/Features/tag_example/shopping_cart.feature:27Given the user is logged in                       # NoneAnd the user has placed an order                  # NoneWhen the user checks the order status             # NoneThen the user should see the current order status # None1 feature passed, 0 failed, 0 skipped
1 scenario passed, 0 failed, 3 skipped
3 steps passed, 0 failed, 13 skipped, 0 undefined
Took 0m0.000s

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/226497.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

磁盘管理 :逻辑卷、磁盘配额

一 LVM可操作的对象:①完成的磁盘 ②完整的分区 PV 物理卷 VG 卷组 LV 逻辑卷 二 LVM逻辑卷管理的命令 三 建立LVM逻辑卷管理 虚拟设置-->一致下一步就行-->确认 echo "- - -" > /sys/class/scsi_host/host0/scan;echo "- -…

【小程序】如何获取特定页面的小程序码

一、进入到小程序管理后台,进入后点击上方的“工具”》“生成小程序码” 小程序管理后台 二、进入开发者工具,打开对应的小程序项目,复制底部小程序特定页面的路径 三、粘贴到对应位置的文本框,点击确定即可

Oracle 12c rac 搭建 dg

环境 rac 环境 (主)byoradbrac 系统版本:Red Hat Enterprise Linux Server release 6.5 软件版本:Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit byoradb1:172.17.38.44 byoradb2:…

Redis管道

问题引出 Redis是一种基于客户端-服务端模型以及请求/响应协议的TCP服务。一个请求会遵循以下步骤: 1 客户端向服务端发送命令分四步(发送命令→命令排队→命令执行→返回结果),并监听Socket返回,通常以阻塞模式等待服务端响应。 2 服务端…

Lunix的奇妙冒险————权限篇

文章目录 一.什么是权限二.用户权限和类别。1.用户2.角色3.更换文件角色 三.文件的类别和对应权限1.文件的类别。2.文件属性权限1.权限说明。2.默认生成文件权限来源3.更改权限 3.文件的执行与删除 四.不同用户共同在一个目录下的权限。1.普通用户家目录2.在同一目录下文件的权…

【Vulnhub 靶场】【Hms?: 1】【简单】【20210728】

1、环境介绍 靶场介绍:https://www.vulnhub.com/entry/hms-1,728/ 靶场下载:https://download.vulnhub.com/hms/niveK.ova 靶场难度:简单 发布日期:2021年07月28日 文件大小:2.9 GB 靶场作者:niveK 靶场系…

别再羡慕别人了!教你如何打造属于自己的私域流量!

目前,随着公域流量的成本不断上升,获取难度越来越大,私域流量的建设已经成为了许多企业和个人品牌的重要选择。私域流量可以实现“一次获取,循环使用”的目标,不仅降低了流量的获取成本,而且可以最大化地发…

探索Apache Commons Imaging处理图像

第1章:引言 大家好,我是小黑,咱们今天来聊聊图像处理。在这个数字化日益增长的时代,图像处理已经成为了一个不可或缺的技能。不论是社交媒体上的照片编辑,还是专业领域的图像分析,图像处理无处不在。而作为…

再谈动态SQL

专栏精选 引入Mybatis Mybatis的快速入门 Mybatis的增删改查扩展功能说明 mapper映射的参数和结果 Mybatis复杂类型的结果映射 Mybatis基于注解的结果映射 Mybatis枚举类型处理和类型处理器 文章目录 专栏精选摘要引言正文动态sql标签ifchoose...when...otherwisewhere、…

【XR806开发板试用】XR806串口驱动CM32M对小厨宝的控制实验

一.说明 非常感谢基于安谋科技STAR-MC1的全志XR806 Wi-FiBLE开源鸿蒙开发板试用活动,并获得开发板试用。 XR806是全志科技旗下子公司广州芯之联研发设计的一款支持WiFi和BLE的高集成度无线MCU芯片,支持OpenHarmony minisystem和FreeRTOS,具有集成度高、…

什么是骨传导耳机?骨传导能保护听力吗?

骨传导耳机是一种非常特殊的蓝牙耳机,它通过骨传导技术将声音直接传送到内耳。这种技术不同于传统耳机,它不通过空气传送声音,而是通过头骨的振动来传送声音。 并且骨传导耳机能够在一定程度上起到保护听力的作用,主要是因为它们不…

python统计分析——单变量描述统计

资料来源于:用Python动手学统计学 1、求和 numpy.sum():要求求和的对象为数组格式。 也可以使用python的标准函数sum()。 2、平均数 numpy.mean() 3、计数 len() 4、方差 np.var(); 注意ddof的参数设置。ddof即Delta Degrees of Fr…

uniapp:全局消息是推送,实现app在线更新,WebSocket,apk上传

全局消息是推送,实现app在线更新,WebSocket 1.在main.js中定义全局的WebSocket2.java后端建立和发送WebSocket3.通知所有用户更新 背景: 开发人员开发后app后打包成.apk文件,上传后通知厂区在线用户更新app。 那么没在线的怎么办&…

Linux中的gcc\g++使用

文章目录 gcc\g的使用预处理编译汇编链接函数库gcc选项 gcc\g的使用 这里我们需要知道gcc和g实际上是对应的c语言和c编译器,而其他的Java(半解释型),PHP,Python等语言实际上是解释型语言,因此我们经常能听…

DML语言(重点)———update

格式:update 要修改的对象 set 原来的值新值 -- 修改学员名字,带了简介 代码案例: -- 修改学员名字,带了简介 UPDATE student SET name清宸 WHERE id 1; -- 不指定条件情况下,会改动所有表! 代码案例…

边缘计算网关:在智慧储能系统中做好储能通信管家

背景 目前储能系统主要由储能单元和监控与调度管理单元组成,储能单元包含储能电池组(BA)、电池管理系统(BMS)、储能变流器(PCS)等;监控与调度管理单元包括中央控制系统(MGCC)、能量管理系统(EMS)等。 2021年8月,国家发改委发布《电化学储能…

Vscode新手安装与使用

安装与版本选择 VS Code 有两个不同的发布渠道:一个是我们经常使用的稳定版(Stable),每个月发布一个主版本;另外一个发布渠道叫做 Insiders,每周一到周五 UTC 时间早上6点从最新的代码发布一个版本&#x…

基于Java车间工时管理系统(源码+部署文档)

博主介绍: ✌至今服务客户已经1000、专注于Java技术领域、项目定制、技术答疑、开发工具、毕业项目实战 ✌ 🍅 文末获取源码联系 🍅 👇🏻 精彩专栏 推荐订阅 👇🏻 不然下次找不到 Java项目精品实…

【银行测试】金融银行-理财项目面试/分析总结(二)

目录:导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结(尾部小惊喜) 前言 银行理财相关的项…

Redis 分布式锁总结

在一个分布式系统中,由于涉及到多个实例同时对同一个资源加锁的问题,像传统的synchronized、ReentrantLock等单进程情况加锁的api就不再适用,需要使用分布式锁来保证多服务实例之间加锁的安全性。常见的分布式锁的实现方式有zookeeper和redis…