1

There are a lot of threads on SO about unit tests and module imports, but still I'm having trouble importing modules into my testing script, when the module that I'm testing itself imports anoter module.

Here's my project structure:

enter image description here

Here's util1:

def add(x, y):
    return x + y


if __name__ == "__main__":
    pass

Here's util2:

from util1 import add

def add_then_string(x, y):
    z = add(x, y)
    return str(z)


if __name__ == "__main__":
    pass

And here's the test file:

import unittest


class TestProject(unittest.TestCase):
    def test_dummy(self):
        self.assertTrue(True)

    def test_add(self):
        from Scripts.Project.util1 import add
        self.assertEqual(add(1,1), 2)

    def test_add_then_string(self):
        from Scripts.Project.util2 import add_then_string
        self.assertEqual(add_then_string(1,1), "2")


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

The problem is that util2 can't find util1 when it's called from the test file via Scripts.Project.

I've put __init__.py files everywhere, but that doesn't help.

Here's the error when I run the tests:

Error
Traceback (most recent call last):
  File path\to\dummy_test_project\UnitTests\test_project.py", line 13, in test_add_then_string
    from Scripts.Project.util2 import add_then_string
  File path\to\dummy_test_project\Scripts\Project\util2.py", line 1, in <module>
    from util1 import add
ModuleNotFoundError: No module named 'util1'

How do I make this work so that I can test the add_then_string function in util2?

EDIT: As so often happens, something has occurred to me immediately after I post on SO. When I change the import in util2 to

from Scripts.Project.util1 import add

then the tests pass. My real repository has lots and lots of imports. Do I need to prepend Scripts.Project to all of them to get this to work?

generic_user
  • 3,430
  • 3
  • 32
  • 56
  • In util2, try having `from Scripts.Project.util1 import add` – ddg Nov 10 '21 at 14:13
  • Thanks @ddg! This occurred to me almost immediately after posting, and it works. Is there any other way? Doing this would require heavy refactor. If there is no other way and you'd like some SO points, please go ahead and make an answer. – generic_user Nov 10 '21 at 14:17

0 Answers0