Mad*_*kul 5 python unit-testing assert
我想对函数进行单元测试并断言是否在函数工作流()内部进行的函数调用序列。就像是,
[1st called] fetch_yeargroup_ls()
[2nd called] invoke_get_links().......
Run Code Online (Sandbox Code Playgroud)
我搜索了许多讨论,但从未找到一个能回答我的问题。
如果您正在使用,mock
则可以在修补这些函数时创建模拟作为父模拟的属性:
try:
# Python 3
from unittest.mock import MagicMock, patch, call
except ImportError:
# Python 2, install from PyPI first
from mock import MagicMock, patch, call
import unittest
from module_under_test import function_under_test
class TestCallOrder(unittest.TestCase):
def test_call_order(self):
source_mock = MagicMock()
with patch('module_under_test.function1', source_mock.function1), \
patch('module_under_test.function2', source_mock.function2), \
patch('module_under_test.function3', source_mock.function3)
# the test is successful if the 3 functions are called in this
# specific order with these specific arguments:
expected = [
call.function1('foo'),
call.function2('bar'),
call.function3('baz')
]
# run your code-under-test
function_under_test()
self.assertEqual(source_mock.mock_calls, expected)
Run Code Online (Sandbox Code Playgroud)
因为这 3 个函数附加到source_mock
,所以对它们的所有调用都记录在Mock.mock_calls
属性中的父模拟对象上,您可以对它们的调用顺序进行断言。
我简单地通过将 3 个函数模拟作为对象的属性查找来附加它们source_mock
,但您也可以使用该Mock.attach_mock()
方法将您以不同方式创建的模拟附加到父级。
归档时间: |
|
查看次数: |
1486 次 |
最近记录: |