1

I have a package that's imported in my code that I'd like to mock, since I'm developing it in an environment where that package is not available. I get the impression I should be able to do this easily with mock, but have not used it before. In my calling script I put at the top

import sys
sys.modules['packageneeded'] = mock.MagicMock()

and this fixed my downstream errors when importing the package packageneeded. However, I also need to be able to access some attributes downstream, such as packageneeded.__version__. How do I define these attributes in my calling script (or a separate file, if need be).

gammapoint
  • 1,083
  • 2
  • 15
  • 27
  • Related: [Mocking a module import in pytest](https://stackoverflow.com/q/43162722/674039) – wim Nov 20 '19 at 00:04

1 Answers1

2

You can initialize the MagicMock object with additional attributes by passing them as keyword arguments to the constructor:

sys.modules['packageneeded'] = mock.MagicMock(__version__='1.2.3')
blhsing
  • 91,368
  • 6
  • 71
  • 106