Search code examples
pythontestingautomated-testspython-behave

Execute precondition only once before running behave tests


I would like to run precondition only once before running a bunch of tests (defined in scenario outlines).

Let's say I've feature file like this:

Background:
    Given Fan is powered

#Test to check fan speed
@TEST_FAN-1 @SuperFan
Scenario Outline: Checking fan speed
    Given fan is not running
    When send speed command with <speed>
    Then fan is running with <speed>


    Examples:
        | speed |          
        | 5     |
        | 50    |
        | 100   |

I've defined Given Fan is powered as below:

@given("Fan is powered")
def step_impl(context):
    assert conetxt.fan.is_powered

This precondition is executed before every test defined in scenario outline. Is there a way to run it only once?


Solution

  • One possibility is to add a context attribute in before_all to keep track of whether the step in question has executed before or not. This will still show the step in the logs but subsequent attempts will be no-ops.

    def before_all(context):
        context.precondition_cache = set()
    
    @given("fan is powered")
    def step_impl(context):
        if "fan is powered" not in context.precondition_cache:
            # power up the fan
            context.precondition_cache.add("fan is powered")