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.mzph.cn/news/583493.shtml

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

相关文章

VSCode Python开发环境配置

目录 1 插件安装2 Debug和测试配置常见问题 1 插件安装 1.1 基础编译插件,Python、Pylance 1.2 修改语言服务器类型,进入用户配置页面搜索Python: Language Server,选择Pylance(一定要修改可以提供很多语法提示) 1…

根据commitID删除某一次提交

1.查看提交历史 git log --prettyoneline2.找到需要删除的那个commit,然后找到上次提交的commitID 比如想要删除下面这一条 我们找到上次提交的commitID 3.执行rebase git rebase -i efa11da0a684977bf8ac047ebb803e2ded2063a4 进入编辑状态显示如下 将需要删除的那个提交前…

探索 EndNote:卓越文献管理工具的功能与应用

引言 在当今科研与学术写作的领域,文献管理是每一位研究者都不可避免面对的挑战。为了有效地整理、引用和协作,研究者需要强大而灵活的文献管理工具。EndNote作为一款备受推崇的文献管理软件,在解决这一问题上发挥着关键作用。本文将深入探讨…

设备健康管理系统助力制造企业实现数字化转型

在当今快速变革的制造业环境中,数字化转型已成为制造企业保持竞争力和实现可持续发展的关键。在这个数字化转型的浪潮中,设备健康管理系统正发挥着重要的作用。设备健康管理系统通过实时监测、预测分析和智能诊断等功能,为制造企业提供了全面…

基于PyQt5自定义UI的详细教程

PyQt5和Qt designer的详细安装教程:https://blog.csdn.net/qq_43811536/article/details/135185233?spm1001.2014.3001.5501Qt designer界面和所有组件功能的详细介绍:https://blog.csdn.net/qq_43811536/article/details/135186862?spm1001.2014.3001…

运行天地图Cesium.js三维服务案例

零、技术选型及相关网址 技术选型:Vue2、VueCli5、Cesium.js、天地图 相关网址:三维服务 - 天地图 帮助文档 一、cesium 初始化参数解析 initializeCesium() {this.viewer new Cesium.Map("cesiumContainer", {shouldAnimate: true, // 是否…

gem5学习(7):内存系统中创建 SimObjects--Creating SimObjects in the memory system

目录 一、gem5 master and slave ports 二、Packets 三、Port interface 1、主设备发送请求时从设备忙 2、从设备发送响应时主设备忙 四、Simple memory object example 1、Declare the SimObject 2、Define the SimpleMemobj class 3、Define the SimpleMemobj class…

EST-100身份证社保卡签批屏按捺终端PC版web版本http协议接口文档,支持web网页开发对接使用

<!DOCTYPE html><html lang"zh-CN"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width,initial-scale1.0"><title>演示DEMO</title><script type"text/…

亚马逊SEO是什么意思?亚马逊标题的SEO方法是什么?-站斧浏览器

亚马逊SEO是什么意思&#xff1f; 亚马逊SEO主要包括了对标题、描述、五点简介等元素的优化&#xff0c;以及评价和评论的管理等方面。下面将详细分析亚马逊SEO的相关内容&#xff0c;帮助卖家更好地理解和应用。 在亚马逊平台上进行SEO优化需要考虑以下几个方面&#xff1a;…

gin框架使用系列之四——json和protobuf的渲染

系列目录 《gin框架使用系列之一——快速启动和url分组》《gin框架使用系列之二——uri占位符和占位符变量的获取》《gin框架使用系列之三——获取表单数据》 上篇我们介绍了如何获取数据&#xff0c;本篇我们介绍一下如何返回固定格式的数据。 一、返回JSON数据 在web开发中…

Linux管理LVM逻辑卷

目录 一、LVM逻辑卷介绍 1. 概述 2. LVM基本术语 2.1 PV&#xff08;Physical Volume&#xff0c;物理卷&#xff09; 2.2 VG (Volume Group&#xff0c;卷组&#xff09; 2.3 LV (Logical Volume&#xff0c;逻辑卷&#xff09; 3. 常用的磁盘命令 4. 查看系统信息的命…

golang第一卷---go入门

go入门 对于使用go的好处环境变量配置开发工具 参考网站 &#xff1a;go入门 对于使用go的好处 简单好记的关键词和语法。轻松上手&#xff0c;简单易学。更高的效率。比Java&#xff0c;C等拥有更高的编译速度&#xff0c;同时运行效率媲美C&#xff0c;同时开发效率非常高。…

爬虫工作量由小到大的思维转变---<第三十三章 Scrapy Redis 23年8月5日后会遇到的bug)>

前言: 收到回复评论说,按照我之前文章写的: 爬虫工作量由小到大的思维转变---&#xff1c;第三十一章 Scrapy Redis 初启动/conn说明书)&#xff1e;-CSDN博客 在启动scrapy-redis后,往redis丢入url网址的时候遇到: TypeError: ExecutionEngine.crawl() got an unexpected …

数据资产专题3:估值

欢迎关注主页个人介绍及相关链接&#xff0c;获取更多算法源码材料 2023数据资源入表白皮书&#xff0c;推荐系统源码下载-CSDN博客 浅析研发支出费用化和资本化的区别-CSDN博客 商业银行数据资产估值白皮书&#xff0c;推荐系统源码下载-CSDN博客 用友BIP数据资产入表解决…

飞企互联-FE企业运营管理平台 登录绕过漏洞复现

0x01 产品简介 飞企互联-FE企业运营管理平台是一个基于云计算、智能化、大数据、物联网、移动互联网等技术支撑的云工作台。这个平台可以连接人、链接端、联通内外&#xff0c;支持企业B2B、C2B与O2O等核心需求&#xff0c;为不同行业客户的互联网转型提供支持。 0x02 漏洞概…

【12.28】转行小白历险记-刷算法04

01两两交换链表中的节点 整体思路 1.要修改后一个节点的指向一定要知道前一个节点的指向才可以改变后面一个节点的 2.分情况奇数和偶数节点&#xff0c;终止条件很重要 3.虚拟头节点&#xff0c;是对我们操作的指针是不是头节点进行判断 02删除链表的倒数第N个节点 思路 …

QT应用篇 二、QML用Image组件实现Progress Bar 的效果

QT应用篇 一、QT上位机串口编程 二、QML用Image组件实现Progress Bar 的效果 三、QML自定义显示SpinBox的加减按键图片及显示值效果 文章目录 QT应用篇前言一、qml需求二、使用组件1.Image组件2.Image中fillMode的使用例子 总结 前言 记录自己学习QML的一些小技巧方便日后查找…

前端使用高德api的AMap.Autocomplete无效,使用AMap.Autocomplete报错

今天需要一个坐标拾取器&#xff0c;需要一个输入框输入模糊地址能筛选的功能 查看官方文档&#xff0c;有一个api可以直接满足我们的需求 AMap.Autocomplete 上代码 AMapLoader.load({"key": "你的key", // 申请好的Web端开发者Key&#xff0c;首次调…

C语言 linux文件操作(二)

文章目录 一、获取文件长度二、追加写入三、覆盖写入四、文件创建函数creat 一、获取文件长度 通过lseek函数&#xff0c;除了操作定位文件指针&#xff0c;还可以获取到文件大小&#xff0c;注意这里是文件大小&#xff0c;单位是字节。例如在file1文件中事先写入"你好世…

通过Python将PDF转为文本,快速提取PDF中的文字

快速高效地从PDF文档中提取信息对于专业人士来说非常重要。处理大量PDF文件时&#xff0c;将PDF转换为可编辑的文本格式可以节省时间和精力。而强大的Python语言正是在这些方面发挥其作用。利用Python中丰富的API&#xff0c;我们可以轻松在Python程序中将PDF转换为文本&#x…