Skip to main content
 首页 » 编程设计

python之模拟 Flask before_first_request

2025年02月15日8lvdongjie

我有一个 Flask 应用程序,它定义了一个 before_first_request 方法。该方法为应用程序加载一些缓存数据。我正在尝试运行一些单元测试,但缓存数据挡住了。我如何模拟该方法。

@app.before_first_request 
def load_caches(): 
    print "loading caches..." 
# cache loading here. 

在我的测试文件中,我定义了一个全局的 test_client 如下:

from unittest import TestCase 
from .. import application 
import mock 
 
 
test_app = application.app.test_client() 

我的测试类(class)遵循这一点。问题是我的 test_app 加载了缓存,我需要在我的测试中模拟它。

请您参考如下方法:

您可以手动删除测试客户端中的 Hook :

test_app = application.app.test_client() 
test_app.before_first_request_funcs = []