gpt4 book ai didi

python - 在 behave python 中定义上下文变量

转载 作者:太空狗 更新时间:2023-10-29 21:59:38 36 4
gpt4 key购买 nike

有时,您需要动态定义值(例如现在的日期时间、随机字符串、随机整数、文件内容等)并在不同步骤中使用它们,而无需显式或硬编码值。

所以,我的问题是如何在步骤中定义变量(正确的方法)以在后续步骤中使用这些变量。

一些例子

Given A random string of length "100" as "my_text"
And I log in to my platform
And I ask to add the following post:
| title | description |
| Some example of title | {{my_text}} |
When I submit the post form
Then The posts table shows these posts:
| title | description |
| Some example of title | {{my_text}} |
And I delete any post containing in the description "{{my_text}}"

这是一个基本示例,试图解释为什么我想在步骤中定义变量并将它们保存在上下文中以便在后续步骤中使用它。

我的想法是修改 before_step 和 after_step 方法...在上下文中设置一个变量来存储我的自定义变量,如下所示:

def before_step(context):
if not hasattr(context, 'vars'):
context.vars = {}

if hasattr(context, table) and context.table:
parse_table(context)

def parse_table(context):
# Here use a regex to check each cell and look for `"{{<identifier>}}"` and if match, replace the cell value by context.vars[identifier] so the step "the posts table shows these posts will never know what is `{{my_text}}` it will be abstract seeing the random string.

场景大纲,使用类似这样的定义变量,如 "<some_identifier>"然后为每个示例替换步骤中的值。

它基本上是为了重现行为,但对于任何类型的步骤,简单的或使用表格。

这样做是正确的方法吗?

最佳答案

来自 Behave docs on the context :

When behave launches into a new feature or scenario it adds a new layer to the context, allowing the new activity level to add new values, or overwrite ones previously defined, for the duration of that activity. These can be thought of as scopes:

@given('I request a new widget for an account via SOAP')
def step_impl(context):
client = Client("http://127.0.0.1:8000/soap/")
// method client.Allocate(...) returns a dict
context.response = client.Allocate(customer_first='Firstname',
customer_last='Lastname', colour='red')
// context vars can be set more directly
context.new_var = "My new variable!"

@then('I should receive an OK SOAP response')
def step_impl(context):
eq_(context.response['ok'], 1)
cnv = str(context.new_var)
print (f"This is my new variable:'{cnv}'"

因此,可以使用点表示法设置值并检索相同的值。

关于python - 在 behave python 中定义上下文变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29499470/

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