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

标签 python testing contextmanager python-behave

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

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

一些例子

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/

相关文章:

python - 可选重定向 I/O 的上下文管理器

php - 有没有办法让 PHPUnit 确定 @method 声明的代码覆盖率?

python - 如何从 Python 中的标准输出重定向转义

python - 如何在 OS X 上进行 PyS60 开发

python - 字符串格式对齐

testing - 在Azure Pipelines上执行Visual Studio测试任务: Updating DontShowUI to 1 failed due to exception

maven - 使用 Maven react 器时如何跳过测试?

python - 如何在不使用 python 2.7 中的类的情况下使上下文管理器也作为装饰器?

python - 套接字使用随机端口,我需要一个

python - __init__() 得到了一个意外的关键字参数 'required'