Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - mock imported dictionary

At the top of the code I want to test I have an import like:

from resources import RESOURCES

where RESOURCES is a dictionary of values.

How can I mock it in the test?

What I would like to is, no matter what is in the real module, return a well known dictionary.

For example in one test I want RESOURCES to be:

{
  'foo': 'bar'
}

while in another test I want it to be:

{
  'something': 'else'
}
like image 216
teone Avatar asked Jun 30 '17 23:06

teone


2 Answers

The way I made it to patch the RESOURCE object is using:

from default import RESOURCES
from mock import patch

with patch.dict(RESOURCES, {'foo': 'bar'}, clear=True):
    assert(RESOUCES['foo'], 'bar')

Note that you'll need to import the dictionary you want to patch in the test suite

It's also possible to use the decorator syntax:

from default import RESOURCES
from mock import patch

@patch.dict(RESOURCES, {'foo': 'bar'}, clear=True)
def test(self):
    self.assert(RESOUCES['foo'], 'bar')
like image 136
teone Avatar answered Sep 28 '22 08:09

teone


Take a look at unittest.mock.patch.object. I think that it will meet your needs.

like image 24
D.Shawley Avatar answered Sep 28 '22 08:09

D.Shawley