当我使用以下代码时:
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'
。
这完全不是我的预期。显然我希望它能像我想要的那样设置值...但显然配置只是dict-ish,不幸的是。
我如何修补此问题,config['db']
是我想要的值,仅仅是我测试的生命周期?
答案 0 :(得分:1)
看来问题是我有一点误会。虽然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格式:
>>> parser = configparser.ConfigParser()
>>> parser.read_dict({'section1': {'key1': 'value1',
... 'key2': 'value2',
... 'key3': 'value3'},
... 'section2': {'keyA': 'valueA',
... 'keyB': 'valueB',
... 'keyC': 'valueC'},
... 'section3': {'foo': 'x',
... 'bar': 'y',
... 'baz': 'z'}
... })
来自docs
无法进行单键访问。要使此示例起作用,您必须执行以下操作:
with mock.patch.dict(config, {'db': {'db': expected_value}}):
# rest of code
注意:值将转换为字符串对应的值。因此,如果您尝试在此处存储实际的数据库连接(或类似),则无法正常工作。