Search code examples
pythonpython-3.6python-behave

Testing with Behave - cannot find modules


I'm starting to write some BDD tests with Behave, but I'm having issues with trying to import my util modules in the tests.

Here is my current folder structure:

root/
    __init__.py
    README
    features/
        __init__.py
        test.feature
        environment.py
        steps/
            __init__.py
            steps_test.py
            utils/
              __init__.py
              string_utils.py
              user_utils.py

In my environment.py, I want some setup code to run before a feature:

import steps.utils.user_utils
def before_feature(context, feature):
    username = user_utils.create_username()
    print(username)

In my user_utils.py:

import string_utils
def create_username():
    name = string_utils.gen_str(10, 3)
    return name

But when I run behave from the project root/ folder, I'm getting the error:

$ behave

...

File "root/features/steps/utils/user_utils.py", line 1, in <module>
    import string_utils
ModuleNotFoundError: No module named 'string_utils'

But if I run python user_utils.py inside the utils/ folder, I don't get any errors, which indicates to me that it does find the module fine.

How can I get my module recognized with Behave?


Solution

  • The problem is that Behave is expecting a fairly strict directory structure. Namely, it does not search recursively through folders within the steps/ folder. So, you need to move the contents of your utils/ folder up into the steps/ folder and it'll work fine.