[Tutor] importing modules from a src directory to test in a module in a testing directory
Alex Kleider
akleider at pm.me
Sun Feb 2 20:35:44 EST 2025
How to import a module from a src directory for testing
in a test program found in a sister test directory?
Using Debian Linux...
Here's my project's directory structure:
TopLevel
├── __init__.py
├── src
│ ├── __init__.py
│ └── myprogram.py
└── tests
├── __init__.py
└── test_myprogram.py
... and content of relevant files:
$ cat src/myprogram.py
#!/usr/bin/env python3
# File: utils/myprogram.py
def print_greeting():
greeting = "Helo world"
print(greeting)
return greeting
if __name__ == "__main__":
print_greeting()
$ cat tests/test_myprogram.py
#!/usr/bin/env python3
# File: tests/test_myprogram.py
from .. src import myprogram
... then attempting to run the test:
$ ./tests/test_myprogram.py
Traceback (most recent call last):
File "/home/alex/Projects/TopLevel/./tests/test_myprogram.py", line 5, in <module>
from ..src import myprogram
ImportError: attempted relative import with no known parent package
Any help as to how this can be fixed would be most welcome!
Cheers,
Alex Kleider
Alex Kleider (he/him)
...sent from my current gismo!
More information about the Tutor
mailing list