How To Access Subdirectory from Tests

Viewed 40

I have a python project where I cannot run tests on a class in a subdirectory from the command line. It works in Pycharm, but not from the command line. I simplified it to the following:

/utils
  __init__.py
  util.py

/tests
  test.py

Where util.py looks like:

class UtilClass:
    def __init__(self):
        print(" in __init__ ")

And utils/__init__.py is:

from .util import (
    UtilClass
)

And test.py just tries to call it:

from utils import UtilClass
x = UtilClass()

When I run (from the top level directory): % python tests/test.py is says ModuleNotFoundError: No module named 'utils'. Do I need to do something with the path to include utils? Or some sort of init.py in the top level dir?

1 Answers

The issue is that python does not include the current directory in the path when you do % python tests/test.py. If you add 'import sys;print(sys.path)' to the beginning of test.py, you will see that the 'tests/' directory is part of the path, but the top level directory where you ran the command from is not there. A couple of solutions:

Option 1: Add Current Directory Explicitly (temporary)

Do PYTHONPATH='.' python tests/test.py. If you do that, the top level directory will be in the path, so test.py will find utils/ and can find UtilClass. This is purely temporary, so good for running tests.

You could also do export PYTHONPATH='/path/to/top/level' and it will stick around for the lifetime of that command line.

Option 2: Install Current Directory (lasts)

Do pip install -e . from the top level directory. This will install the directory as '--editable', intended for developing modules, which means that it creates a link to your development area. Since its now installed, python will find it. This will stick around until you uninstall it.

Related