gpt4 book ai didi

python - Flask 单元测试 - 如何为每个测试重置 app.url_map?

转载 作者:行者123 更新时间:2023-12-03 17:00:31 25 4
gpt4 key购买 nike

我正在为 Flask 应用编写一系列单元测试。每个测试的设置如下:

  • 在测试模式下创建一个 Flask 应用程序 (app.testing = True)。
  • 在测试应用内的蓝图上安装测试端点(路由)。
  • (然后,在端点上进行一些测试...)

问题是我的测试中使用的应用程序实例累积了从之前的测试中添加的路由,而不是从头开始。就好像 app.url_map 永远不会重置,即使我每次都创建一个新应用......

这是我的设置函数的代码,它在每次测试之前运行(我使用的是 pytest):

def setup(flask_app):
app = flask_app

# Mount a test endpoint on the API blueprint.
bp = app.blueprints["api"]
bp.add_url_rule('/foo', view_func=test_view, methods=['GET', ])

print(app.url_map)

flask_app 是一个创建新测试应用程序的 pytest fixture,如下所示:

@pytest.fixture()
def flask_app():
from my_app import create_app
app = create_app('testing')
# Configure a bunch of things on app...
return app

如果我编写三个测试,我的 setup 函数将被调用三次并为 app.url_map 记录以下内容:

# 1st test — My new '/api/foo' rule doesn't even show yet...
# For that, I'd need to re-register the blueprint after adding the URL to it.

Map([<Rule '/' (HEAD, OPTIONS, GET) -> main.index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>])


# 2nd test — Rule '/api/foo' added once

Map([<Rule '/' (HEAD, OPTIONS, GET) -> main.index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/api/foo' (HEAD, OPTIONS, GET) -> api.test_view>])


# 3rd test — Rule '/api/foo' added twice

Map([<Rule '/' (HEAD, OPTIONS, GET) -> main.index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/api/foo' (HEAD, OPTIONS, GET) -> api.test_view>],
<Rule '/api/foo' (HEAD, OPTIONS, GET) -> api.test_view>]

在我的实际代码中(有点复杂),我得到以下错误:

AssertionError: View function mapping is overwriting an existing endpoint function:
lib/flask/app.py:1068: AssertionError

这是有道理的,因为我试图多次添加相同的 View ...为什么我每次运行新测试时都没有得到一个新的应用程序实例?

我什至不确定这是 Flask 问题还是 pytest 问题...:(

最佳答案

我可以通过将您为设置实例化的所有内容移动到设置中(甚至是您在那里使用的库的导入)来解决类似的问题。当然,这可以通过使用 create_app() 方法以更优雅的方式完成,就像您为整个 flask 应用程序所做的那样。这里要注意的重点是将保持状态(此处为端点)的实例移出全局范围并将其移动到 create_app() 方法中。

如果您需要这方面的更多信息,请告诉我。

关于python - Flask 单元测试 - 如何为每个测试重置 app.url_map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41171254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com