[Tutor] importing modules from a src directory to test in a module in a testing directory

Leam Hall leamhall at gmail.com
Wed Feb 5 09:12:05 EST 2025


On 2/2/25 19:35, Alex Kleider via Tutor wrote:
> 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

Hey Alex!

I apologize for not responding sooner, my mailer has been acting up and I just got this a few minutes ago. You can mangle sys.path to have it look for things, but the consensus is not to do that.

My solution has been to use unittest, and to have whatever modules I'm writing tests for to be in the same directory as my tests directory:

TopLevel
├── myprogram.py
└── tests
     ├── __init__.py
     └── test_myprogram.py


Note that a lot of people like PyTest, and it's pretty good, too.

Leam


Linux Software Engineer   (reuel.net/career)
Scribe: The Domici War    (domiciwar.net)
Coding Ne'er-do-well      (github.com/LeamHall)

Between "can" and "can't" is a gap of "I don't know", a place of discovery. For the passionate, much of "can't" falls into "yet". -- lh

Practice allows options and foresight. -- lh


More information about the Tutor mailing list