0

I know this is an hot topic in the community and a lot of people asked the same thing. Unfortunately, after I read a huge number of these topics I did not find yet a proper solution. I am asking your kind support to find the best way to deal with unittest and imports so that I don't get the popular message "No module "a.py" found.."

My project structure is:

my_project
    ├── some_script.sh
    ├── log
    ├── README.md
    ├── requirements.txt
    ├── src
    │   ├── __init__.py
    │   ├── config.yml
    │   ├── a.py
    │   ├── b.py
    │   ├── c.py
    ├── tests
    │   ├── __init__.py
    │   ├── test_a.py
    │   ├── test_b.py
    │   ├── test_c.py

About the imports, I use this schema:

a.py

import b
import c

test_a.py

from src import a

When I run the tests I use the autodiscovery, so I do something like:

cd my_project
python3 -m unittest -v

This way the directory my_project should be automatically included in the sys path and python should found all the imported modules inside it.

The issue is that when I import the module "a.py" in in "test_a.py" python complains that module b and c are not found. This is quite reasonable because modules "b.py" and "c.py" are inside "src" and not inside "tests". How should I deal with imports and unittest in the cleanest way possible? With cleanest I mean without hacking the pythonpath or adding the dir to the syspath in my python code. Thank you.

Rick
  • 11
  • 2
  • You are missing a `setup.py` in the root of your package, thus you are not providing the standardised way to tell Python how to install your package into the environment. Please turn your project into a [pip installable package](https://stackoverflow.com/questions/5360873/how-do-i-package-a-python-application-to-make-it-pip-installable) and that should fix your issue. – metatoaster Jan 22 '21 at 11:29
  • Since it was not a package to distribute, I did not plan to write a setup.py. Anyway, you were right, writing a setup.py will resolve most of the issues you have with imports. Once your package has been installed, you can just import it in every module (tests included) using "import my_package" or "from my_package import a". – Rick Jan 25 '21 at 11:31

0 Answers0