Running certain steps once before a scenario outline - Python Behave

Nightsreach picture Nightsreach · Dec 7, 2015 · Viewed 9.2k times · Source

As the title suggests, I wish to run some certain configuration / environment setup steps before a scenario outline. I know there is Background to do this for scenarios, but Behave splits a scenario outline into multiple scenarios and thus runs the background for every input in the scenario outline.

This is not what I want. For certain reasons I cannot provide the code I am working with however I will write up an example feature file.

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      |

What would happen in this case is Behave would power cycle and check USB connection for each output Hi, No, Yes resulting in three power cycles and three connection checks

What I want is for Behave to power cycle once and check the connection once and then run all three tests.

How would I go about doing this?

Answer

TomDotTom picture TomDotTom · Dec 2, 2016

Your best bet is probably to use the before_feature environment hook and either a) tags on the feature and/or b) the feature name directly.

For example:

some.feature

@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.

steps/enviroment.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
        ''')

alternate steps/enviroment.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
        ''')