Fixture in behave is not getting applied

Viewed 825

I need a fixture in my behave code so that all the users that I create during testing automatically gets cleaned up. As a result, I added the following code

#test/features/steps/environment.py

@fixture()
def user_cleanup(context):
    # -- SETUP-FIXTURE PART:
    context.users_to_be_cleaned_up = []
    print ("Creating Fixture")
    yield context.users_to_be_cleaned_up
    # -- CLEANUP-FIXTURE PART:
    for userid in context.users_to_be_cleaned_up:
        resp = delete_database_entry("users", userid)
        print (resp)
    context.users_to_be_cleaned_up = []


def before_feature(context, feature):
    if "fixture.user.cleanup" in feature.tags:
        use_fixture(user_cleanup, context)

In my features file, I added the following

@fixture.user.cleanup
Feature: Validating backend from the app side
    
    Scenario Outline: Super Admin has permission to create other users
        Given a set of existing users:
                | user                  | details     |
                | superadmin   | userdetails |             
        When "superadmin" successfully logs in
        Then he can create non-existing "<user>" with "<details>"
            and "<user>" can login successfully with "<details>"

        Examples: User Roles
                | user                | details      |
                | superadmin_1        | user details | 

The idea was to have the test append all the users into context.users_to_be_cleaned_up. But in the test, when I try to append, it says that property users_to_be_cleaned_up is not present in context.

Any idea what I am doing wrong here?

1 Answers

I got an answer for this and recording this here for posterity.

You need to keep your environments.py at the feature level and not at the steps level.

So the structure as it stands today

|
|-test.feature
|_environment.py
|--steps
    |
    |- steps.py
Related