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

Flask/Pytest多测试用例触发AssertionError:before_request无法重复调用

问题:多测试用例下Flask Blueprint触发AssertionError:before_request无法重复调用

此问题并非另外两个相似问题的重复。当单元测试套件中存在多个测试函数时,会触发AssertionError: The setup method 'before_request' can no longer be called。

问题原因

全局Blueprint对象仅创建一次,但被两个测试函数重复使用:test_1先调用before_request装饰器,再执行register_blueprint;test_2对同一Blueprint对象重复执行上述操作,导致报错。

现有尝试与困境

  • 已知可通过工厂函数创建蓝图解决,但项目包含多模块的大量蓝图,不想仅为测试需求修改全部蓝图,希望找到更简便的方案。
  • 尝试过Blueprint的record_once方法,但问题反而更严重——即使仅运行单个测试用例也会报错。
  • 目前临时方案:判断蓝图是否已注册,若已注册则跳过@before_request装饰器,但这属于临时hack,不够优雅。

寻求合适的解决方案,感谢帮助!

相关代码示例

app.py

import flask

blp = flask.Blueprint('admin', __name__)
@blp.route('/', methods=['GET'])
def login():
    return('OK')

def add_blueprint(app):
    @blp.before_request
    def before_request():
        return
    with app.app_context():
        app.register_blueprint(blp)

def make_app():
    app = flask.Flask('dham_wsgi')
    add_blueprint(app)
    return app

conftest.py

import pytest
from .app import make_app

@pytest.fixture
def app():
    app = make_app()
    yield app

@pytest.fixture
def client(app):
    yield app.test_client()

test_app.py

def test_1(client):
    rv = client.open('a')

def test_2(client):
    rv = client.open('b')

使用record_once的app.py

import flask

blp = flask.Blueprint('admin', __name__)
@blp.route('/', methods=['GET'])
def login():
    return('OK')

def add_before_request(setup):
    @setup.blueprint.before_request
    def before_request():
        return

blp.record_once(add_before_request)

def add_blueprint(app):
    app.register_blueprint(blp)

def make_app():
    app = flask.Flask('dham_wsgi')
    add_blueprint(app)
    return app

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 20:25:38