I'm working on writing tests for a Python module that looks like this (edited for compactness and clarity, of course):
What I need to be able to do is test both paths of the import statement. I thought I could do something like
But I guess I am misunderstanding something here, because it's failing that assertion. What is the correct way to fix it up so that during testing the "import FreeCAD" statement works, but yields a mock object, that then yields another mock for Console?
Python:
try:
import FreeCAD
Console = FreeCAD.Console # This is a function
except ImportError:
FreeCAD = None
class ReplacementConsole:
pass # Obviously there's a real class here... details omitted
def Console():
return ReplacementConsole()
What I need to be able to do is test both paths of the import statement. I thought I could do something like
Code:
class TestConsole(unittest.TestCase):
def test_log_with_freecad(self):
with patch.dict(sys.modules, {"FreeCAD": MagicMock()}):
from that_module_outlined_above import Console
Console().PrintLog("A log message")
self.assertTrue(sys.modules["FreeCAD"].Console.called)
But I guess I am misunderstanding something here, because it's failing that assertion. What is the correct way to fix it up so that during testing the "import FreeCAD" statement works, but yields a mock object, that then yields another mock for Console?