模拟 ConfigObj 实例
Mocking ConfigObj instances
使用 ConfigObj, I want to test some section 创建代码:
def create_section(config, section):
config.reload()
if section not in config:
config[session] = {}
logging.info("Created new section %s.", section)
else:
logging.debug("Section %s already exists.", section)
我想写一些单元测试,但我遇到了问题。例如,
def test_create_section_created():
config = Mock(spec=ConfigObj) # ← This is not right…
create_section(config, 'ook')
assert 'ook' in config
config.reload.assert_called_once_with()
显然,测试方法将失败,因为 TypeError
因为类型 'Mock' 的参数不可迭代。
如何将 config
对象定义为模拟对象?
这就是为什么你永远不应该,永远,post在你完全清醒之前:
def test_create_section_created():
logger.info = Mock()
config = MagicMock(spec=ConfigObj) # ← This IS right…
config.__contains__.return_value = False # Negates the next assert.
create_section(config, 'ook')
# assert 'ook' in config ← This is now a pointless assert!
config.reload.assert_called_once_with()
logger.info.assert_called_once_with("Created new section ook.")
我会把 answer/question 留在这里是为了 post 以防万一其他人脑部衰竭...
使用 ConfigObj, I want to test some section 创建代码:
def create_section(config, section):
config.reload()
if section not in config:
config[session] = {}
logging.info("Created new section %s.", section)
else:
logging.debug("Section %s already exists.", section)
我想写一些单元测试,但我遇到了问题。例如,
def test_create_section_created():
config = Mock(spec=ConfigObj) # ← This is not right…
create_section(config, 'ook')
assert 'ook' in config
config.reload.assert_called_once_with()
显然,测试方法将失败,因为 TypeError
因为类型 'Mock' 的参数不可迭代。
如何将 config
对象定义为模拟对象?
这就是为什么你永远不应该,永远,post在你完全清醒之前:
def test_create_section_created():
logger.info = Mock()
config = MagicMock(spec=ConfigObj) # ← This IS right…
config.__contains__.return_value = False # Negates the next assert.
create_section(config, 'ook')
# assert 'ook' in config ← This is now a pointless assert!
config.reload.assert_called_once_with()
logger.info.assert_called_once_with("Created new section ook.")
我会把 answer/question 留在这里是为了 post 以防万一其他人脑部衰竭...