Help with mocks/patching in Python unittest

chennes

Ars Scholae Palatinae
701
Subscriptor++
I'm working on writing tests for a Python module that looks like this (edited for compactness and clarity, of course):
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?
 
D

Deleted member 43669

Guest
Mocking makes my head hurt, but I think your code works reasonably?

I played a bit:

a.py:

Python:
try:
    import woo
    print("worked")
    woo.foo("hi")
except:
    print("didn't work")

b.py:

Python:
import sys
from unittest import mock

with mock.patch.dict(sys.modules, {"woo": mock.Mock()}):
    import a
    print(sys.modules["woo"].foo.call_args_list)

Bash:
$ python b.py
worked
[call('hi')]
 

chennes

Ars Scholae Palatinae
701
Subscriptor++
Thanks -- it took me two days of fighting, but I finally found out what was going wrong with my tests, which I had oversimplified in my post above. It turns out that if you do something like this (note the patch decorator):
Python:
    @patch("that_module_outlined_above.logging")
    def test_log_with_freecad(self, mock_logger):
        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)
...the import statement does NOT execute where it looks like it does in that code! Something about the decorator causes the import to basically be moved to the very top, so it runs before anything else, and thus the mock has no effect. Doh! Dropping the decorator and using a second "with" resolved the issue.