我有以下测试方案:


检查是否创建了具有特定名称的项目
编辑这个专案
确认它已被编辑
在拆卸程序中删除此项目


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

  @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函数。

有什么好办法可以将参数以某种方式传递到特征级别的夹具?在全球范围内?
我试图使用全局变量作为选项,但是在此框架中开始变得有点脏和成问题。

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

最佳答案

因为上下文清除了场景执行期间创建的变量,所以您需要一种在功能上持久存在的机制。一种方法是在设置夹具期间在上下文中创建字典或其他容器,以使其在整个功能中持久存在。这些场景可以设置属性或添加到容器中,并且由于字典是在功能期间添加的,因此在销毁灯具期间仍将存在该字典。例如。,

@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 - Python行为-如何从场景传递值以在功能级别的固定装置中使用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59085587/

10-13 05:02