0

Is it possible to mock a global object, such as an imported module, in a specific method from a different module?

Example:

import some_module

class MyClass():
    def a_method(self):
        some_module.do_something(1)
    def b_method(self):
        some_module.do_something(2)

I would like to patch some_module so as to set the return value of do_somthing(), but only in a_method() and not in b_method(). Of course I could use a decorator, however I would like to patch from a different module.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359

1 Answers1

1

You cannot patch out some_module.do_something() limited to MyClass().a_method(), no.

You'd normally be selective in time when to patch instead. Apply the patch only when MyClass().a_method() is being called and make sure the patch is undone again before MyClass().b_method() is called.

A good unittest already ensures that you test just a_method() anyway. If a_method() is not under test but used by other code that is, then patch out a_method() directly.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343