我想从特定函数中模拟一些嵌套函数:
# tools.py
def cpu_count():
def get_cpu_quota():
return int(load("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"))
def get_cpu_period():
return int(load("/sys/fs/cgroup/cpu/cpu.cfs_period_us"))
def get_cpus():
try:
cfs_quota_us = get_cpu_quota()
cfs_period_us = get_cpu_period()
if cfs_quota_us > 0 and cfs_period_us > 0:
return int(math.ceil(cfs_quota_us / cfs_period_us))
except:
pass
return multiprocessing.cpu_count()
return get_cpus()
# test_tools.py
class TestTools(unittest.TestCase):
@patch("tools.cpu_count")
def test_cpu_count_in_container(self, cpu_count_mock):
cpu_count_mock.return_value.get_cpu_quota.return_value = 5000
cpu_count_mock.return_value.get_cpu_period.return_value = 1000
cpus = tools.cpu_count()
self.assertEqual(5, cpus)
但是,运行此测试时,出现以下错误:
FAIL: test_cpu_count_in_container (tests.util.tools_test.ToolsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/uilian/Development/foo/venv/lib/python3.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "/home/uilian/Development/foo/tests/util/tools_test.py", line 154, in test_cpu_count_in_container
self.assertIsInstance(cpus, int)
AssertionError: <MagicMock name='cpu_count()' id='140490818322384'> is not an instance of <class 'int'>
是否可以模拟嵌套函数?
如果没有,这种情况下最好的方法是什么?