gpt4 book ai didi

python-behave - 如何在python行为.feature文件中传递像列表或字典这样的对象

转载 作者:行者123 更新时间:2023-12-03 20:16:40 39 4
gpt4 key购买 nike

如何在行为 .feature 文件中将列表或字典之类的对象作为参数传递,以便我可以在我的 python 函数步骤中使用该参数?请参阅下面我试图实现的示例:

Feature:
Scenario: Given the inputs below
Given a "<Dictionary>" and "<List>"
When we insert "<Dictionary>" and "<List>"
Then we confirm the result in the database

Examples: Input Variables
|Input1 |Input2 |
|Dictionary(json) |List |

最佳答案

您可以将数据提供为 json,并在步骤中使用 json.loads 对其进行解析。

注意,要使用 Examples: 我们需要一个 Scenario Outline 而不是一个Scenario

# features/testing_objects.feature
Feature: Testing objects
Scenario Outline: Given the inputs below
Given a <Dictionary> and <List>
When we insert them
Then we confirm the result in the database

Examples: Input Variables
|Dictionary |List |
|{"name": "Fred", "age":2} |[1,2,"three"]|

在步骤中使用 json.loads 解析它:

# features/steps/steps.py
import json
from behave import given, when, then

@given('a {dictionary} and {a_list}')
def given_dict_and_list(context, dictionary, a_list):
context.dictionary = json.loads(dictionary)
context.a_list = json.loads(a_list)

@when('we insert them')
def insert_data(context):
print('inserting dictionary', context.dictionary)
print('inserting list', context.a_list)

@then('we confirm the result in the database')
def confirm(context):
print('checking dictionary', context.dictionary)
print('checking list', context.a_list)

除了使用 Examples:,您还可以使用多行字符串文字
然后通过 context.text 在单独的步骤中访问每个对象。
Feature: String literal JSON
Scenario:
Given a dictionary
"""
{
"name": "Fred",
"age": 2
}
"""
And a list
"""
[1, 2, "three"]
"""
Then we can check the dictionary
And check the list

@given('a dictionary')
def given_a_dictionary(context):
context.dictionary = json.loads(context.text)

@given('a list')
def given_a_list(context):
context.a_list = json.loads(context.text)

@then('we can check the dictionary')
def check_the_dictionary(context):
assert context.dictionary == {
'name': 'Fred',
'age': 2
}

@then('check the list')
def check_the_list(context):
assert context.a_list == [1, 2, 'three']

关于python-behave - 如何在python行为.feature文件中传递像列表或字典这样的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52635025/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com