python 如何使用MagicMock处理回调

j0pj023g  于 2023-11-16  发布在  Python
关注(0)|答案(1)|浏览(140)
import unittest
from mock import Mock, MagicMock
import time

wait = False

def pushback_callback(self, res):
  print("Received callback")
  wait = True
  
def pushback_fcn(callback):
  print("pushback_fcn")
  
def execute():
  pushback_fcn(pushback_callback)
  while wait == False:
      time.sleep(5)
      
  print("done")
            
#********* Test code ************#
pushback_fcn = MagicMock()
execute()

字符串
由于测试代码从不调用回调,等待值总是为False,因此测试代码永远等待。有什么方法可以从MagicMock中获得函数指针?

vd2z7a6w

vd2z7a6w1#

我创建了一个类似的代码来测试mocking一个接收回调的函数。安装并运行pytest来测试它。
模拟回调的方法是使用@patchside_effect(关于patch和side_effect如何工作的文档)
该脚本包含两个测试,一个没有mock,一个有mock(将通过回调发送的值从done更改为mocked)。

from unittest.mock import patch
import threading
import time

event = threading.Event()
result = "pending"

def on_finished(msg):
    global result
    result = msg

def async_fn(callback):
    time.sleep(1)
    event.set()
    callback("done")

def execute():
    async_fn(on_finished)
    event.wait()
    print(f"done with result: {result}")

# ============================================================
# Tests

def test_without_mock():
    execute()
    assert result == "done"

@patch("test_mock_fn_with_callback.async_fn")
def test_with_mock(async_fn):
    async_fn.side_effect = lambda callback: callback("mocked")
    execute()
    assert result == "mocked"

字符串

相关问题