BDD - Python Behave 用户自定义命令行选项 -D

引言

日常运行测试用例,有时需要自定义命令行参数,比如不同环境的对应的配置是不一样的,这样就需要传一个环境参数来执行,根据执行的环境选择对应的配置文件。今天就来了解一下用户自定义命令行参数选项。

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

behave -D

执行下面命令来查看 Behave 命令行选项

behave -h

其中 behave -D 选项是 Behave 命令行工具的一个功能,用于从命令行传递用户定义的配置参数。通过 -D 或 --define 选项,您可以设置键值对,这些键值对将存储在 context.config.userdata 中,以供测试脚本中使用,可以通过 context.config.userdata 字典来访问这些变量

-D NAME=VALUE, --define NAME=VALUE
Define user-specific data for the config.userdata dictionary. Example: -D foo=bar to
store it in config.userdata[“foo”].

使用方式如下:

behave -D key1=value1 -D key2=value2 ...

其中,key1=value1、key2=value2 是您想要传递给 Behave 测试的配置参数。
例如,如果您有一个测试需要使用用户名和密码,您可以这样传递:

behave -D username=myuser -D password=mypassword

然后,在测试脚本中,您可以通过 context.config.userdata 访问这些参数:

# 在 Behave 测试脚本中访问配置参数
username = context.config.userdata.get('username', '')
password = context.config.userdata.get('password', '')

还有一种方式,通过在配置文件 behave.ini 定义
如:

[behave.userdata]
env = dev

step 脚本里可以通过 context.config.userdata[‘env’] 访问

behave -D 应用

下面举个简单粗暴的例子
在这里插入图片描述

feature 文件

创建 user_data.feature 文件

# user_data.feature 

Feature: Context User Data Example

@user_data
Scenario: User data scenario
	Given user data is set
	Then get the user data

behave.ini 配置文件

定义了用户自定义参数:
[behave.userdata]
env = dev

# behave.ini
[behave]
paths=BDD/Features/user_data
dry_run = false
format = my_html
stdout_capture = false
outfiles = my_report.html

[behave.formatters]
my_html = behave_html_formatter:HTMLFormatter

[behave.userdata]
env = dev

step 文件

创建 user_data_steps.py 文件
通过 context.config.userdata[‘param_name’] 来访问用户自定义的参数

# user_data_steps.py

from behave import *

@given('user data is set')
def step_user_data_is_set(context):
    pass

@then('get the user data')
def then_get_user_data(context):
    print(f"env:{context.config.userdata['env']}")
    print(f"user:{context.config.userdata['user']}")
    print(f"pw:{context.config.userdata['pw']}")

执行

在当前目录 BDD,执行命令 behave -D user=zhang -D pw=2024

-D user=zhang -D pw=2024 定义了两个自定义的变量参数

step 实现可以访问到这些参数,分别打印出了这些变量

PS C:\Automation\Test\BDD> behave -D user=zhang -D pw=2024
Feature: Context User Data Example # BDD/Features/user_data/user_data.feature:1

  @user_data
  Scenario: User data scenario  # BDD/Features/user_data/user_data.feature:4
    Given user data is set      # BDD/steps/user_data_steps.py:3
    Then get the user data      # BDD/steps/user_data_steps.py:7
env:dev
user:zhang
pw:2024

1 feature passed, 0 failed, 0 skipped
1 scenario passed, 0 failed, 0 skipped
2 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.000s
  • 18
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值