1

Trying to write a unit test on a Class with a class inheritance from a Class in another script ( both in the same directory ). Patch to sys.module, verify it's in the sys.module but still getting ModuleNotFound error.

Wonder if I'm doing anything incorrectly. A second eye on this would be great. Thanks!

  • Project structure
root
|-- src
   |-- steps
      |-- project
         |-- script1.py
         |-- script2.py
   |-- test
      |-- steps
         |-- project
            |-- test_script1.py
            |-- test_script2.py
  • script1.py

class A:
  def __init__(self):
    self.name = None
  • script2.py
# Not using the full path. we're running this on AWS when uploading ( submit py ) to s3, both scripts exist in the same folder.

from script1 import A

class B(A):
  def __init__(self):
     self.age = None
  def get_name(self):
     print(self.name)

  • test_script2.py
from unittest import TestCase, mock
from src.steps.project.script1 import A

class TestB(TestCase):
   @classmethod
   def setUpClass(cls):
        modules = {"script1.A": A()}
        cls.module_patcher = mock.patch.dict("sys.modules", modules)
        cls.module_patcher.start()
   def setUp(self):
       # ModuleNotFoundError : No module name 'script1'
       from src.steps.project.script2 import B

Tried the above patch to sys.modules It is indeed patched to system modules when script2 is being imported. Still giving the same error ModuleNotFoundError.

Amy
  • 11
  • 3

1 Answers1

0

A possible solution is to add a path search in sys.path in the script test_script2.py. So the test_file2.py becomes:

import sys
sys.path.insert(1, '/path/to/root')

# add here your code

In the file script2.py you have to correct the import instruction of the module script1.py with a relative path:

#from script1 import A  <--- this is your import

from .script1 import A  <--- this is the correct import
frankfalse
  • 1,553
  • 1
  • 4
  • 17