You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Radish框架Python变量描述符的可用类型及使用方法咨询

Radish BDD 步骤参数类型:名称与使用方法

这个特性在Radish BDD里叫做参数类型(Parameter Types),核心作用是将Gherkin步骤中的字符串参数自动转换为对应Python数据类型,直接传递给步骤定义函数,省去手动类型转换的麻烦。

内置参数类型及说明

Radish提供了多种开箱即用的参数类型,常用的有:

  • :w:匹配由字母、数字、下划线组成的单词字符串,转换为Python str 类型
  • :g:匹配浮点数格式字符串(如123.45),转换为Python float 类型
  • :d:匹配整数格式字符串(如123),转换为Python int 类型
  • :s:匹配任意包含空格的字符串,转换为Python str 类型
  • 自定义正则:直接写正则表达式作为类型标识,比如:^[a-zA-Z]+$,仅匹配纯字母字符串,转换为str 类型

使用方法

  1. 在Gherkin步骤的占位符中,通过{参数名:类型标识}的格式声明参数类型
  2. 步骤定义函数的参数会自动接收转换后的对应类型值

示例(对应你提供的代码):

@given("I have the number {number1:g} and the name {name1:w}")
def have_record(step, number1, name1):
    step.context.number1 = number1  # number1已自动转为float类型
    step.context.name1 = name1      # name1已自动转为str类型

你之前遇到的步骤无法识别问题,就是因为将字符串类型的name1错误声明为:g(浮点数类型),当传入非浮点数格式的名称时,无法匹配导致步骤不生效。

自定义参数类型(可选)

如果内置类型无法满足需求,可以自定义参数类型并注册:

from radish import register_parameter_type
from datetime import datetime

# 定义类型解析函数
def parse_date(date_str):
    return datetime.strptime(date_str, "%Y-%m-%d")

# 注册自定义参数类型
register_parameter_type(
    "date",          # 类型名称(步骤中用{参数名:date}调用)
    r"\d{4}-\d{2}-\d{2}",  # 匹配该类型的正则表达式
    parse_date       # 字符串转目标类型的解析函数
)

内容的提问来源于stack exchange,提问作者Luke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 08:52:13