Reputation: 195
I've searched for a solution here and on other sites, but it feels like all import problems I come across are subtly different.
I have a project with the following setup:
In b.py:
from .a import Foo
In the tests:
import a, b
package1, package2, and package3 are essentially smaller packages that are bundled together in the same project/super-package as utilities. The purpose of this project is to be nested inside another package (say, package4) and to have these packages/modules imported by package4. Hence, relative imports to other files in the package are required, if I don't want to modify the path.
As an example, package4:
I'm omitting the __init__.py's in the hierarchy above. In main.py, I might do:
import src.external.project_from_above.package1.a
My problem: this structure works fine, except for unit testing. I am in the habit of running python3 -m unittest discover tests
from each package (package1, package2, package3). This works fine when there are not relative imports. However, running with relative imports will yield the following error: "SystemError: Parent module '' not loaded, cannot perform relative import"
I desire: A way of running the unit tests in package1/tests from the package1 directory, with no imports changing (or at least, maintaining the ability to use this entire project inside the aforementioned package4 as a sub-package). I'd like to avoid any manipulation of the path, but if we can restrict it to a run_tests.py file in package1, then that is okay.
Upvotes: 1
Views: 369
Reputation: 195
Here's one solution: add a file called run_tests in package1. In it, do the following:
cd ..
python -m unittest discover package1/tests
This requires you to use absolute imports in your tests (e.g., import package1.a
)
Upvotes: 1