2

I'm trying to write a unit-test using pytest and the class I'm testing is importing a type for another library which open a socket during it's import. The type itself is pretty simple, it only implements __call__ and return a plain-old-python-object that is easy to mock.

Is there a way I can monkey-patch that import so that the real python file will not get called before my test starts?

Ido Ran
  • 10,584
  • 17
  • 80
  • 143

1 Answers1

0

You can use mock.patch to mock any attribute from any module.

For example, to mock the attribute name type from module module1, just add this to the top of the unittest file

from unittest.mock import patch
patch('module1.type')

Incase you like to mock that module attribute just for one testcase, use patch as a decorator

from unittest.mock import patch

@patch('module1.type')
def test1(...):
    ...
Prem Anand
  • 2,469
  • 16
  • 16