BDD - Python Behave 配置文件 behave.ini

2023-12-29 12:28

本文主要是介绍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

这篇关于BDD - Python Behave 配置文件 behave.ini的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/549433

相关文章

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

nudepy,一个有趣的 Python 库!

更多资料获取 📚 个人网站:ipengtao.com 大家好,今天为大家分享一个有趣的 Python 库 - nudepy。 Github地址:https://github.com/hhatto/nude.py 在图像处理和计算机视觉应用中,检测图像中的不适当内容(例如裸露图像)是一个重要的任务。nudepy 是一个基于 Python 的库,专门用于检测图像中的不适当内容。该

pip-tools:打造可重复、可控的 Python 开发环境,解决依赖关系,让代码更稳定

在 Python 开发中,管理依赖关系是一项繁琐且容易出错的任务。手动更新依赖版本、处理冲突、确保一致性等等,都可能让开发者感到头疼。而 pip-tools 为开发者提供了一套稳定可靠的解决方案。 什么是 pip-tools? pip-tools 是一组命令行工具,旨在简化 Python 依赖关系的管理,确保项目环境的稳定性和可重复性。它主要包含两个核心工具:pip-compile 和 pip

HTML提交表单给python

python 代码 from flask import Flask, request, render_template, redirect, url_forapp = Flask(__name__)@app.route('/')def form():# 渲染表单页面return render_template('./index.html')@app.route('/submit_form',

web群集--nginx配置文件location匹配符的优先级顺序详解及验证

文章目录 前言优先级顺序优先级顺序(详解)1. 精确匹配(Exact Match)2. 正则表达式匹配(Regex Match)3. 前缀匹配(Prefix Match) 匹配规则的综合应用验证优先级 前言 location的作用 在 NGINX 中,location 指令用于定义如何处理特定的请求 URI。由于网站往往需要不同的处理方式来适应各种请求,NGINX 提供了多种匹

Python QT实现A-star寻路算法

目录 1、界面使用方法 2、注意事项 3、补充说明 用Qt5搭建一个图形化测试寻路算法的测试环境。 1、界面使用方法 设定起点: 鼠标左键双击,设定红色的起点。左键双击设定起点,用红色标记。 设定终点: 鼠标右键双击,设定蓝色的终点。右键双击设定终点,用蓝色标记。 设置障碍点: 鼠标左键或者右键按着不放,拖动可以设置黑色的障碍点。按住左键或右键并拖动,设置一系列黑色障碍点

Python:豆瓣电影商业数据分析-爬取全数据【附带爬虫豆瓣,数据处理过程,数据分析,可视化,以及完整PPT报告】

**爬取豆瓣电影信息,分析近年电影行业的发展情况** 本文是完整的数据分析展现,代码有完整版,包含豆瓣电影爬取的具体方式【附带爬虫豆瓣,数据处理过程,数据分析,可视化,以及完整PPT报告】   最近MBA在学习《商业数据分析》,大实训作业给了数据要进行数据分析,所以先拿豆瓣电影练练手,网络上爬取豆瓣电影TOP250较多,但对于豆瓣电影全数据的爬取教程很少,所以我自己做一版。 目