#!/usr/bin/env python # coding: utf-8 # ## 导入依赖 # In[5]: from unittest.mock import patch from module import call_func # ## 错误的用法 # In[6]: def test_call_func(): def mocked_funny_func(): return "not funny at all" with patch("dependency.some_funny_func", mocked_funny_func): return_value = call_func() assert return_value == "not funny at all" print("pass") # In[7]: test_call_func() # ## 正确的用法 # In[10]: def test_call_func(): def mocked_funny_func(): return "not funny at all" with patch("module.some_funny_func", mocked_funny_func): return_value = call_func() assert return_value == "not funny at all" print("pass") # In[11]: test_call_func() # ## 解析原理 # In[13]: # 模拟 dependency.some_funny_func dependency = {} dependency["some_funny_func"] = "some_value" # 模拟 module.some_funny_func module = {} module["some_funny_func"] = dependency["some_funny_func"] # 模拟 mock dependency["some_funny_func"] = "some_other_value" # 查看结果 print(dependency["some_funny_func"]) print(module["some_funny_func"])