gpt4 book ai didi

Python Behave - 如何从场景传递值以在功能级别的固定装置中使用?

转载 作者:太空宇宙 更新时间:2023-11-03 20:03:44 25 4
gpt4 key购买 nike

我有以下测试场景:

  1. 检查是否已创建具有特定名称的项目
  2. 编辑此项目
  3. 验证是否已编辑
  4. 作为拆卸过程的一部分删除此项目

下面是实现此目的的示例代码:场景:

  @fixture.remove_edited_project
@web
Scenario: Edit a project data
Given Project was created with the following parameters
| project_name |
| my_project_to_edit |
When I edit the "my_project_to_edit" project
Then Project is edited

将数据保存在要在拆卸函数(固定装置)中使用的某个变量中的步骤:

@step('I edit the "{project_name}" project')
def step_impl(context, project_name):
# steps related to editing the project

# storing value in context variable to be used in fixture
context.edited_project_name = project_name

以及一个用于在场景后删除项目的示例固定功能:

@fixture
def remove_edited_project(context):
yield
logging.info(f'Removing project: "{context.edited_project_name}"')

# Part deleting a project with name stored in context.edited_project_name

在这样的配置中,一切正常,并且在任何情况下(测试失败或通过)项目都会被固定装置删除。没关系。

但是,当我想在功能级别上执行此类功能时,意味着将 @fixture.remove_edited_project 装饰器放在功能关键字之前:

@fixture.remove_edited_project
Feature: My project Edit feature

,那么这不起作用。我已经知道原因了 - context.edited_project_name 变量在每个场景后都会被清除,并且稍后不再可用于此固定功能。

有什么好的方法可以将参数以某种方式传递给功能级别的固定装置吗?不知何故全局?我试图使用全局变量作为一个选项,但这在这个框架中开始有点肮脏和有问题。

理想情况下,应该有类似 @fixture.edited_project_name('my_project_to_edit')

最佳答案

由于上下文会清除场景执行期间创建的变量,因此您需要一种在该功能中持续存在的机制。实现此目的的一种方法是在 fixture 设置期间在上下文中创建字典或其他容器,以便它将在整个功能中持续存在。场景可以设置属性或添加到容器中,并且由于字典是在功能期间添加的,因此在 fixture 销毁期间它仍然存在。例如,

@fixture
def remove_edited_project(context):
context.my_fixture_properties = {}
yield
logging.info(f'Removing project: "{context.my_fixture_properties['edited_project_name']}"')

@step('I edit the "{project_name}" project')
def step_impl(context, project_name):
# steps related to editing the project

# storing value in context variable to be used in fixture
context.my_fixture_properties['edited_project_name'] = project_name

关于Python Behave - 如何从场景传递值以在功能级别的固定装置中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59085587/

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