0

I have the following directory structure

directory structure

when I use the test runner I get

File "/home/kyle/dev/tests/test_foo.py", line 2, in <module> import foo ModuleNotFoundError: No module named 'foo'

I'm at a loss as what could be wrong. The test code looks like:

import unittest
import foo

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual(foo.f(), 'FOO3')

if __name__ == '__main__':
    unittest.main()

I'm using a virtual environment (.venv) I've set that to my interpreter.

2
  • 1
    How exactly are you starting the test runner? What is the exact command, and what directory are you in? Commented Sep 5 at 23:34
  • I'm in dev and I'm using the test runner in VScode. Commented Sep 6 at 17:05

1 Answer 1

0

The error happens because foo.py lives under src/, but when you run your tests Python doesn’t automatically know to look there. By default it only searches the current directory, the standard library, and installed site-packages.

From the project root, run the following command to fix:

PYTHONPATH=src python -m unittest discover tests
  • PYTHONPATH=src tells Python “also look in the src/ directory when resolving imports.”

  • -m unittest discover tests makes unittest discover and run all test files under tests/.

Now import foo will work because src/foo.py is on the import path.

Sign up to request clarification or add additional context in comments.

2 Comments

Well that works in as much as the command runs the test but when I run the test in VSCodes test runner I still get the fail to import error
I'm not sure but VSCode may run code with different Current Working Directory (which you can check in code using os.getcwd()) and it may need to use PYTHONPATH=/full/path/to/scr

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.