gpt4 book ai didi

python - 如何断言模拟对象中的方法已被调用?

转载 作者:太空宇宙 更新时间:2023-11-03 13:15:19 25 4
gpt4 key购买 nike

我正在学习 python 模拟,并且在检查模拟对象上的方法是否已被调用时遇到问题。

我要测试的代码是这样的:

def main(flags, directory_service):
if flags.has_schema:
directory_service.HasSchema(SCHEMA_NAME)
sys.exit(1)

我的测试代码是:

def testHaltsAfterCheckingSchema(self):
mock_flags = self._CreateDefaultFlags()
mock_flags.has_schema = True
mock_directory_service = MagicMock()

with self.assertRaises(SystemExit) as cm:
key_distributor.main(mock_flags, mock_directory_service)
self.assertTrue(mock_directory_service.HasSchema.assert_called_with(key_distributor.SCHEMA_NAME))
self.assertEqual(cm.exception.code, 1)

当我运行它时,我得到了这个异常:

FAIL: testHaltsAfterCheckingSchema (test123.Test123)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test123.py", line 34, in testHaltsAfterCheckingSchema
self.assertTrue(mock_directory_service.HasSchema.assert_called_with(key_distributor.SCHEMA_NAME))
AssertionError: None is not true

最佳答案

assert_called_with 直接进行断言,并返回 None。您根本不需要在这里使用 TestCase.assertTrue()

换句话说,以下就足够了:

mock_directory_service.HasSchema.assert_called_with(key_distributor.SCHEMA_NAME)

如果此断言失败(即 directory_service.HasSchema() 未被调用或使用不同的参数调用),则 assert_called_with 引发 AssertError exception ,其中 TestCase 为您捕获并记录为测试失败:

>>> from unittest.mock import MagicMock
>>> mock_directory_service = MagicMock()
>>> mock_directory_service.HasSchema('SCHEMA_NAME')
<MagicMock name='mock.HasSchema()' id='4562465232'>
>>> mock_directory_service.HasSchema.assert_called_with('SCHEMA_NAME')
>>> mock_directory_service.HasSchema.assert_called_with('foobar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/unittest/mock.py", line 771, in assert_called_with
raise AssertionError(_error_message()) from cause
AssertionError: Expected call: HasSchema('foobar')
Actual call: HasSchema('SCHEMA_NAME')

关于python - 如何断言模拟对象中的方法已被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32257458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com