运行特定步骤一次,前情场景概述 - Python Beh

2024-05-16 00:48:44 发布

您现在位置:Python中文网/ 问答频道 /正文

如标题所示,我希望在场景大纲之前运行一些特定的配置/环境设置步骤。我知道有Background可以为场景执行此操作,但是Behave将场景大纲拆分为多个场景,从而为场景大纲中的每个输入运行后台。

这不是我想要的。出于某些原因,我无法提供我正在使用的代码,但是我将编写一个示例功能文件。

Background: Power up module and connect
Given the module is powered up
And I have a valid USB connection

Scenario Outline: Example
    When I read the arduino
    Then I get some <'output'>

Example: Outputs
| 'output' |
| Hi       |
| No       |
| Yes      |

在这种情况下,将发生的是行为将关闭电源并检查每个输出的USB连接HiNoYes,从而导致三次电源关闭和三次连接检查

我想要的是Behave重启一次,检查一次连接,然后运行所有三个测试。

我该怎么做呢?


Tags: theno标题output环境example场景hi
2条回答

我也面临同样的问题。 有一个昂贵的Background,每个Feature应该只执行一次。 解决这个问题实际上需要的是在Scenarios之间存储状态的能力

对于这个问题,我的解决方案是使用behave.runner.Context#_root,它在整个运行过程中都保持不变。我知道什么访问私人会员不是一个好的做法-我会很高兴学习更清洁的方式。

# XXX.feature file
Background: Expensive setup
  Given we have performed our expensive setup

# steps/XXX.py file
@given("we have performed our expensive setup")
def step_impl(context: Context):    
    if not context._root.get('initialized', False):
        # expensive_operaion.do()
        context._root['initialized'] = True

您最好的选择可能是使用before_feature环境钩子和 特征上的标记和/或b)特征名称。

例如:

一些功能

@expensive_setup
Feature: some name
  description
  further description

  Background: some requirement of this test
    Given some setup condition that runs before each scenario
      And some other setup action

  Scenario: some scenario
      Given some condition
       When some action is taken
       Then some result is expected.

  Scenario: some other scenario
      Given some other condition
       When some action is taken
       Then some other result is expected.

步骤/环境.py

def before_feature(context, feature):
    if 'expensive_setup' in feature.tags:
        context.excute_steps('''
            Given some setup condition that only runs once per feature
              And some other run once setup action
        ''')

替代步骤/环境.py

def before_feature(context, feature):
    if feature.name == 'some name':
        context.excute_steps('''
            Given some setup condition that only runs once per feature
              And some other run once setup action
        ''')

相关问题 更多 >