如何修补ConfigParser键/值?

2024-04-18 23:47:10 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用以下代码时:

from unittest import mock
import configparser

configtext = '''
[SECTION]
whatever=True
'''

config = configparser.ConfigParser()
config.read_string(configtext)


def test_fails():
    expected_value = 'fnord'
    with mock.patch.dict(config, {'db': expected_value}):
        assert config['db'] is expected_value

我的测试失败,因为AttributeError: 'str' object has no attribute 'items'。在

这完全不是我所期望的。显然我希望它能像我想要的那样设置值。。。但不幸的是,显然配置只是命令式的。在

我怎样才能修补这个config['db']是我想要的值,只在测试的生命周期内使用?在


Tags: 代码fromimportconfigtruedbvaluesection
1条回答
网友
1楼 · 发布于 2024-04-18 23:47:10

看来问题是我有点小误会。虽然ConfigParser看起来像是dict,但实际上不是。堆栈跟踪包含以下证据:

    def test_fails():
        expected_value = 'whatever'
>       with mock.patch.dict(config, {'db': expected_value}):

test.py:15: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/lib/python3.5/unittest/mock.py:1593: in __enter__
    self._patch_dict()
/usr/lib/python3.5/unittest/mock.py:1619: in _patch_dict
    in_dict[key] = values[key]
/usr/lib/python3.5/configparser.py:969: in __setitem__
    self.read_dict({key: value})
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <configparser.ConfigParser object at 0x7f1be6d20f98>, dictionary = {'db': 'whatever'}
source = '<dict>'

注意,它试图在这里执行read_dict。这是因为它需要一个section-ish格式:

^{pr2}$

来自文档

单密钥访问是不可能的。要使此示例生效,必须执行以下操作:

with mock.patch.dict(config, {'db': {'db': expected_value}}):
    # rest of code

注意:值将转换为字符串形式的对应值。因此,如果您试图在这里存储一个实际的数据库连接(或类似的),它将不起作用。在

相关问题 更多 >