断言一个函数是否在另一个函数内部被调用

Assert whether a function is being called inside another function

我有2个函数,另一个只有当传递的参数为True时才会调用。

def func1(para1 = True):
       // Some lines of code
       if para1 == True:
               func2()

def func2():
       // Some lines of code

现在,我正在尝试创建一个单元测试来检查是否正在调用嵌套函数 func2(当传递给 func1 的参数为真时)。我在网上查了一下,发现了一些与 Mock() 相关的东西,但不明白如何用于这个特定的测试用例。我该如何处理?

example.py:

def func1(para1=True):
    if para1 == True:
        func2()


def func2():
    pass

test_example.py:

from unittest import TestCase
import unittest
from unittest.mock import patch
from example import func1


class TestExample(TestCase):
    @patch('example.func2')
    def test_func1__should_call_func2(self, mock_func2):
        func1()
        mock_func2.assert_called_once()

    @patch('example.func2')
    def test_func1__should_not_call_func2(self, mock_func2):
        func1(False)
        mock_func2.assert_not_called()


if __name__ == '__main__':
    unittest.main()

测试结果:

..
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK