You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Quart框架运行pytest时如何禁用或Mock before_serving函数

解决方案

你可以根据实际场景选择以下两种方案处理Quart测试时跳过before_serving逻辑的需求:

方案1:Mock before_serving中调用的外部服务(更推荐)

该方案无需改动业务代码,仅在测试侧屏蔽外部服务调用,不会影响其他初始化逻辑的执行:

  1. 先确认你before_serving函数中调用的外部服务的导入路径,例如你调用的是third_party.service.connect()
  2. 在test_app fixture中用Mock替换该方法即可,示例如下:
import pytest
from unittest import mock

@pytest.fixture(name="test_app", scope="function")
async def _test_app(s3_client, tmp_path, async_mongodb):
    os.environ["BLOB_STORE"] = str(tmp_path)
    db_config['db'] = async_mongodb
    # Mock外部服务调用,替换为你实际的外部服务路径
    with mock.patch("your.module.path.third_party.service.connect") as mock_connect:
        mock_connect.return_value = None # 按需设置返回值
        async with app.test_app() as test_app:
            yield test_app

如果安装了pytest-mock插件,可以直接用mocker fixture简化写法:

@pytest.fixture(name="test_app", scope="function")
async def _test_app(mocker, s3_client, tmp_path, async_mongodb):
    os.environ["BLOB_STORE"] = str(tmp_path)
    db_config['db'] = async_mongodb
    mocker.patch("your.module.path.third_party.service.connect")
    async with app.test_app() as test_app:
        yield test_app

方案2:清空所有before_serving回调

如果你不需要执行任何before_serving逻辑,可以直接在启动测试应用前清空Quart实例的回调列表:

@pytest.fixture(name="test_app", scope="function")
async def _test_app(s3_client, tmp_path, async_mongodb):
    os.environ["BLOB_STORE"] = str(tmp_path)
    db_config['db'] = async_mongodb
    # 清空所有注册的before_serving函数
    app.before_serving_funcs.clear()
    async with app.test_app() as test_app:
        yield test_app

注意:该方案会清除所有注册的before_serving逻辑,如果有其他必须的初始化操作,请勿使用该方案。

内容的提问来源于stack exchange,提问作者NVS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:45:02