Q:

How to test python class which calls a missing module?

I try to test python class with pytest. 
I have python module like so:
import module_A
from module_b import module_c

class classToTest():
    def foo():
        return module_c.func() + 1

    def bar():
        return module_A.func() + 2

So, how to properly test bar() function if I don’t have any modules imported in the instance above?
I decided to mock patch module_A.func(), but patched object should be imported before. 
I’ve created a fake module_A locally and do so:
import module_A
from mock import patch
@patch(‘module_A.func’, return_value=10)
def test_bar()
    MyClass = ClassToTest()
    assert MyClass.bar() == 12

I have an import error because I don’t have module_b installed. How to solve it? Probably it’s beter to reorganize the code to make it more testable or I should use another approaches to build a good test?

A:

something like this may help, but you have to position it before your import of whatever holds classToTest.
import sys
try:
    import module_b

except (ImportError,) as e: 

    from unittest.mock import Mock

    module_b = Mock()
    module_b.module_c = module_b

    def func():
        return 10

    module_b.func = func

    sys.modules["module_b"] = module_b

#import your code under test

With self.assertEqual(classToTest().foo(), 12) I got an asserterror that 11 <> 12, it wasn't happy with the numbers not matching, so the fake module_b was accepted.  
Please note, I was only playing around with faking out a module_b import.  The whole test structure probably has issues, as Code-Apprentice pointed out.
2nd warning:  I would not do this to somehow fake out an installed module_b not being installed.  system.modules, once it has that mock in it registered, will need tidying up.  reload ought to do it, but who knows?  in that case, the usual mock/patch might yield better results.

