[Tutor] importing modules to be tested

Alex Kleider alexkleider at gmail.com
Wed Jan 10 16:18:39 EST 2024


It's been my impression that tests are usually placed in their own
separate directory. The problem then arises how to import the
modules that are to be tested.
My solution has been to use the following code:
"""
import os
import sys
sys.path.insert(0, os.path.split(sys.path[0])[0])
"""
Is there a "better way?"
I'm using Debian/GNU/Linux and python 3.9
Thanks in advance for any advice you might have.
Sincerely,
Alex Kleider


The following may or may not be helpful as background:

$ pwd
/home/alex/Git/Lib/Question

$ ls -lA
total 28
-rwxr-xr-x 1 alex alex   100 Jan 10 12:25 code2test.py
drwxr-xr-x 2 alex alex  4096 Jan 10 12:26 tests

$ cat code2test.py
#!/usr/bin/env python3
# file: code2test.py
def code():
    return "code2test.code() has been run"

$ cat tests/test_code.py
#!/usr/bin/env python3
# File: tests/test_code.py
import os
import sys
sys.path.insert(0, os.path.split(sys.path[0])[0])
import code2test
assert code2test.code() ==  "code2test.code() has been run"
print("Test passes")

$ ./tests/test_code.py
Test passes

$ cat tests/test_code.py
#!/usr/bin/env python3
# File: tests/test_code.py
"""
import os
import sys
sys.path.insert(0, os.path.split(sys.path[0])[0])
"""
import code2test
assert code2test.code() ==  "code2test.code() has been run"
print("Test passes")

$ ./tests/test_code.py
Traceback (most recent call last):
  File "/home/alex/Git/Lib/Question/./tests/test_code.py", line 8, in <module>
    import code2test
ModuleNotFoundError: No module named 'code2test'


-- 
alex at kleider.ca  (he/him)
(sent from my current gizmo)


More information about the Tutor mailing list