Mock Patchers

The patch decorators are used for patching objects only within the scope of the function they decorate. The most important key is to do the patching in the right namespace otherwise you will be lost in a maze (like me )

Where to patch

For patching to work you must ensure that you patch the name used by the system under test. Patch where an object is looked up which is not necessarily the same place as where it is defined. It means you do not need to patch exact directory of the function or object . Now see some examples

# a. py
class SomeClass:
  # ...

# b.py
from a import SomeClass

def some_function(SomeClass)

How to test b.some_function with mocking out SomeClass using patch()? If we use patch() to mock out a.SomeClass then it will have no effect on our test because module b already has a reference to the real SomeClass and it looks like our patching had no effect. (If we import module b, it imports SomeClass from module a.)

The key is to patch out SomeClass where it is used (or where it is looked up) In this case some_function will actually look up SomeClass in module b, where we have imported it. So the patching should look like:

@patch('b.SomeClass')

Let’s think about alternative scenario.

# a. py
class SomeClass:
  # ...

# b.py
import a

def some_function:
  a.SomeClass.xxx # call method in a.SomeClass

Now, b module just import a and use methods in module a at some_function. In this case the class we want to patch is being looked up in the module a, so we have to patch like this:

@patch('a.SomeClass')

태그: ,

업데이트:

댓글남기기