Reputation: 469
I was wondering how I can setup my directory structure to enable importing any python file from project
in the tests
directory to test it?
Currently I'm getting a Module not found error when trying to import a class from some_file.py
in some_file_tests.py
.
Traceback (most recent call last):
File "e:\Documents\GitHub\Project\tests\util\some_file_test.py", line 3, in <module>
from project.util.some_file import SomeFile
ModuleNotFoundError: No module named 'project'
tests/util.some_file_test.py
from project.util.some_file import SomeClass
Here is the directory structure
📦Project
┣ 📂project
┃ ┣ 📂util
┃ ┃ ┣ 📜some_file.py
┃ ┃ ┗ 📜__init__.py
┃ ┗ 📜__init__.py
┣ 📂tests
┃ ┣ 📂util
┃ ┃ ┗ 📜some_file_test.py
And here is an example of what the __init__.py
files contain.
project/__init__.py
from . import util
project/util/__init__.py
from . import some_file
Upvotes: 1
Views: 1234
Reputation: 469
So after some reasearch (thanks @gftea) I found that in each __init__
file, doing from . import ___
is unecessary and can be removed (for my use case anyways).
Then I created these files in the root folder:
setup.py
from setuptools import setup
setup()
setup.cfg
[metadata]
name = <NAME>
version = 0.0.1
description = <DESCRIPTION>
long_description = file: README.md
long_description_content_type = text/markdown
url = <GITHUB REPOSITORY URL>
author = <AUTHOR(S)>
license = GPL-3.0
license_file = LICENSE
classifiers =
License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Programming Language :: Python :: 3
Programming Language :: Python :: 3 :: Only
Programming Language :: Python :: 3.8
Programming Language :: Python :: 3.9
Programming Language :: Python :: 3.10
[options]
packages = find:
install_requires =
python-dotenv==0.19.2
requests==2.27.1
python_requires = >=3.8
tests_require =
pytest
coverage
[options.packages.find]
exclude =
tests*
[options.extras_require]
dev =
black==22.1.0
pylint==2.12.2
Afterwards I installed my package using pip install -e .
Then in the test python file I can do from project.util.some_file import SomeClass
Upvotes: 0
Reputation: 568
two ways
project
path to PYTHONPATH environment variable before running test.project
path to sys.path programmatically in your test file before importing modules in projectimport sys
sys.path.append("path/to/project")
from project.util.some_file import SomeClass
Upvotes: 2