Python unittest pip package

Viewed 134

I have a pip packages project with the following folder structure:

/mypackage
  /src
    /mypackage
      __init__.py
      ...
  /tests
    __init__.py
    test_numer1.py
    test_numer2.py
  ...

if I try to run my unittests with pycharm everything works just fine, all test get detected and no problem with imports. But if I try to run the unittest over the console via

python3 -m unittest

I get the error module named mypackage not found everywhere where I try to do from my package import .... I've tried to add/remove an __init__.py at all possible folders but it is still not working. I've also tried to move the tests folder in the /src folder, also not working. I've also tried to run the command from basically all possible folder positions still same error.

The pip package itself is working. In another project I can do

pip install mypackage

and then also use from mypackage import ...

Is there something wrong in general with my project structure?

2 Answers

I had a similar problem and solved it with relative imports.

from ..src.mypackage import pyfile in your case.

Though you'd have to put a __init__.py in your srcfolder for it to work, methinks. Not sure why you would need asrcdirectory with a python project. Might be worth it just to put thetestsandmypackage``` at the same level and then change all imports to

from . import pyfile <- This is assuming all files are in mypackage and at the same level in the file tree.

You can try adding an empty conftest.py inside src folder. This will add it to the sys.path, so in your tests directory, you should be able to import like this:

from mypackage import ...

However, I think installing the package in editable mode (pip install -e .) is still a better way, because you don't need to modify the sys.path.

You may want to take a look at Good Integration Practices.

Related