问题
I have the following project files (using Python3):
pyproj
├── __init__.py
├── main.py
├── module1.py
├── module2.py
└── tests
├── __init__.py
└── test_module.py
module1 contains no imports.
module2 imports from module 1 as follows:
import module1
main.py imports from module1 and module2 as follows:
from module1 import *
from module2 import *
I would like tests/test_module to be able to import from module2 and from module1, and to be able to run it using pytest
from the pyproj
directory. However attempting to import module2 using:
from ..module2 import *
causes the following error when running pytest
from either the pyproj
directory or the tests
directory:
tests/test_module.py:1: in <module>
from ..module2 import *
module2.py:1: in <module>
import module1
E ImportError: No module named 'module1'
The problem seems to be when module1 is importing module2. python3 main.py
runs correctly however.
I've tried numerous changes, but none seem to allow both main.py
and the tests to work correctly. What is the correct way to structure the project and appropriately import files to do this?
回答1:
Use absolute import: from module2 import *
in tests and configure PYTHONPATH to pyproj before running tests. Or run tests in virtual env with pyproj installed. Or use tox which creates such venvs for you.
回答2:
My solution may not be best practice, but works, after a bit of experimenting:
use from myproj.module2 import something
make PYTHONPATH include myproj
use init.py in tests directory
My experiment repo is here: https://github.com/epogrebnyak/question-package-structure-for-testing/tree/master/which
来源:https://stackoverflow.com/questions/44742593/python3-pytest-directory-structure-and-imports