-1

I am having trouble to patch a class that is imported and set in a dictionary.

Given these files:

lib/
  foo/
    conf.py
    foo.py
# conf.py
from .foo import Foo

CONF = {"class": Foo}
# foo.py
class Foo():
    pass

Why Foo is not MagicMock in the CONF variable? How to change this?

In [1]: from unittest.mock import patch
In [2]: with patch('lib.foo.conf.Foo') as mock:
      2     from lib.foo.conf import *
      3     print(f'CONF: {CONF}')
      4     print(f'Foo: {Foo}')
CONF: {'class': <class 'lib.foo.foo.Foo'>}
Foo: <MagicMock name='Foo' id='140340109160656'>
Mike
  • 63
  • 7

1 Answers1

-1

Answering my own question.

The problem I was facing is that I am mocking where it is defined, and I should patch where it is used.

The "it" being the CONF dict, not the Foo class.

So I came up with this:

from unittest.mock import patch
with patch('lib.foo.conf.Foo') as Foo_mock:
    with patch.dict('lib.foo.conf.CONF', {"class": Foo_mock}) as CONF_mock:
        from lib.foo.conf import *
        print(f'CONF: {CONF}')
        print(f'Foo: {Foo}')

Output working as expected:

CONF: {'class': <MagicMock name='Foo' id='140349148304320'>}
Foo: <MagicMock name='Foo' id='140349148304320'>
Mike
  • 63
  • 7