1

I'm trying to get a behave test done in Python.

A simple behave test per se is no problem. But I'm struggling as soon as I try to use a module from a package I've already created and which is in a parallel directory.

The directory structure is something like:

src
 ├── connection
 │    │
 │    └── api_connector.py
 │
 ├── behave_tests
 │    │
 │    ├─ steps
 │    │  │
 │    │  └ testCommands.py
 │    │
 │    ├── testConnection.feature
 │    └── testCommands.feature
 │
 └── unit_tests

Normally, behave is started from inside the behave_tests directory. And at first, it run fine. All Python code for the behave test was in the file testCommands.py, only packages from the python core were used.

But then I changed testCommands.py to use code from my own package connection which is tested and working.

In testCommands.py I wrote the input line

from connection.api_connector import ApiConnector, SerialApiConnector

But this input line isn't resolved by behave, it outputs:

ModuleNotFoundError: No module named 'connection'

I tried to append my package connection to the python module path by adding the following lines to the top of test_commands.py

import sys
sys.path.append('/home/username/projects/projectname/src/connection/')

But it didn't help.

How can I tell behave to use my connection package?

phibel
  • 151
  • 1
  • 14
  • 1
    Similar question has been answered here: https://stackoverflow.com/questions/14886143/how-to-import-a-python-module-from-a-sibling-folder – prayingMantis Jul 01 '20 at 14:19

1 Answers1

0

After some further reading I was able to find the solution.

  1. To make Python recognize the directory connection as a package I had to add empty __init__.py files into both directories: src and connection.
  2. To be able to address the package connection using absolute imports, the PYTHONPATH environment variable must point into the src directory.

E.g. in a linux shell I set PYTHONPATH by typing

export PYTHONPATH=/home/{username}/test_project/src

Then the python interpreter and also behave find and resolve the module in question as long as they are started from within this shell.

phibel
  • 151
  • 1
  • 14