Python - 模拟导入的字典 [英] Python - mock imported dictionary

查看:35
本文介绍了Python - 模拟导入的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我想测试的代码的顶部,我有一个像这样的导入:

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

from resources import RESOURCES

其中 RESOURCES 是值的字典.

如何在测试中模拟它?

我想要的是,不管真正的模块是什么,返回一个众所周知的字典.

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

例如在一个测试中,我希望 RESOURCES 是:

For example in one test I want RESOURCES to be:

{
  'foo': 'bar'
}

在另一个测试中我希望它是:

while in another test I want it to be:

{
  'something': 'else'
}

推荐答案

我用来patch RESOURCE 对象的方法是:

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')

这篇关于Python - 模拟导入的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆