我正在尝试开始使用unittest.mock的动作/断言模式而不是mox的记录/重播/验证模式。
# foo.py
def op_1(param):
pass
def op_2(param):
pass
def do_stuff(param_1, param_2):
global config
global log
try:
op_1(param_1)
if config.getboolean('section','option'):
op_2(param_2)
except:
log.error("an error occured")
而且,这是我的 unittest 文件的示例。
# test_foo.py
class TestFoo(unittest.TestCase):
def test_do_stuff(self):
param_1 = None
param_2 = None
foo.config = MagicMock()
foo.config.getboolean('section','option', return_value = True)
foo.op_1 = MagicMock()
foo.op_2 = MagicMock()
do_stuff(param_1, param_2)
foo.op_1.assert_called_once_with(param_1)
foo.op_2.assert_called_once_with(param_2)
foo.config.getboolean.assert_called_once_with('section','option')
此测试是否验证以下项目/我是否使用模拟正确?
- do_stuff 调用返回没有错误
- op_1 是用 param_1 调用的
- op_2 是用 param_2 调用的
- 配置解析器对象已被使用,但具体调用无关紧要