Submodule Couldn't Import Parentmodule (python)
Solution 1:
For the module test.test_file1
, test
is your top-level package. You can't go outside that for relative imports; you can only reach other modules within the test
package.
Either run python3 -m unittest mymodule.test.test_file1
(with your working directory set to the parent directory of mymodule
) or add mymodule
to your Python path and use from mymodule import file1
.
Generally, best practice is to put a tests
directory next to your project:
mymodule
|-__init__.py
|-file1.py
|-file2.py
tests
|-test_file1.py
|-test_file2.py
Note that there is no __init__.py
file, but some test runners (specifically pytest
, may require one).
This is how the Django project itself organises tests, as do most other Python projects (see, for example, click
, requests
or flake8
). Use a test runner to discover tests, like nose
.
You'd need to add your mymodule
parent directory to the Python path for this to work, of course, so you may want to add
import os
import sys
here = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(here))
to the top of your test files, or to put that into a utils.py
file you put in your tests directory.
Also see the Structure section of the Hitchhikers Guide to Python.
Post a Comment for "Submodule Couldn't Import Parentmodule (python)"