如何通过Flask.test_client单元测试验证after_this_request中my_task已执行?
在Flask测试客户端中验证after_this_request内的函数调用
我们的Flask代码通过after_this_request搭配response.call_on_close,实现了请求响应返回后执行my_task()的逻辑,线上运行正常。但用Flask.test_client做单元测试时,默认不会触发这些后续动作,现在要验证测试过程中my_task()确实被调用了。
解决方案:手动触发响应的call_on_close回调
Flask测试客户端返回的响应对象不会自动执行call_on_close里的回调(这部分逻辑原本由WSGI服务器在请求收尾时处理),所以我们需要在测试中手动触发它,再结合Mock来断言函数调用情况。
示例测试代码(以pytest+unittest.mock为例):
from flask import Flask import pytest from unittest.mock import patch app = Flask(__name__) class Service: def my_task(self): # 实际业务逻辑 pass service = Service() @app.route('/') def index(): msg = 'Hello World!' @app.after_this_request def add_close_action(response): @response.call_on_close def process_after_request(): service.my_task() return response return msg def test_my_task_is_called(): with app.test_client() as client: # Mock my_task方法 with patch.object(service, 'my_task') as mock_task: # 发送请求获取响应 response = client.get('/') # 手动触发响应的close回调 response.call_on_close() # 断言my_task被调用了一次 mock_task.assert_called_once()
关键说明
response.call_on_close()会执行所有绑定到该响应的关闭回调,包括我们定义的process_after_request,进而触发my_task()。- 使用Mock可以精准捕获函数调用情况,除了
assert_called_once(),还可以用assert_called_with()验证调用参数(如果有的话)。
内容的提问来源于stack exchange,提问作者pete19
相关产品推荐
相关产品推荐

