【问题标题】:Mocking a function called inside another function inside a class python模拟类python中另一个函数内部调用的函数
【发布时间】:2021-06-09 00:56:38
【问题描述】:

我需要模拟一个函数(this_function()),它在另一个函数(receive())、函数蓝图、A 类中调用。我该怎么做? 我在包含所有测试的文件中为 this_function() 创建了一个模拟。

class A: 
       def blueprint(): 
           @route("/", method = ["POST"])
           async def receive(): 
                  ....
              test = await this_function()

我在与我的测试相同的文件中创建了一个模拟函数:

def mock_this_function(): 
   return ..

class Tests(unittest.TestCase): 
   @patch("path.to.classA.this_function")
    def test(mock_this_function):

this_function 在 helper.py 模块中定义。

我无法连接/使用 mock_this_function。它总是将我与 this_function 联系起来......有什么解决方案吗?任何提示如何正确模拟它?

【问题讨论】:

标签: python mocking


【解决方案1】:

在您的模拟中尝试此路径:"path.to.classA.this_function" 相反,您可能走错了路径。我的意思是,你的函数有多嵌套并不重要。如果是导入的,则只需正确引用模拟路径即可,@HallerPatrick 提供的链接中对此进行了很好的描述。

【讨论】:

  • 谢谢,我明白了,但由于函数是异步的,我收到一个错误:TypeError: object MagicMock can't be used in 'await' expression
  • 哦,在这种情况下,我认为这可以帮助您:stackoverflow.com/questions/51394411/…
猜你喜欢
  • 2017-05-08
  • 2019-04-18
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
相关资源
最近更新 更多