我正在为烧瓶应用程序编写一系列的单元测试。每个测试的设置如下:
- 在测试模式(
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固定装置,类似的东西:
@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
这是有道理的,因为我试图多次添加相同的视图...为什么每次运行新测试时都不会获得新的应用程序实例?
我什至不确定这是烧瓶问题还是pytest问题... :(
我可以通过将您实例化的设置实例化来解决类似的问题(甚至是您在此使用的库的导入)。当然,这可以通过使用Create_app()方法来以更优雅的方式完成,就像您为整个烧瓶应用程序所做的那样。在这里带走的重要点是将状态(此处的端点)置于全局范围之外,然后将其移至create_app()方法中。
告诉我您是否需要有关此的更多信息。