[英]Flask unit testing - How to reset app.url_map for each test?
我正在為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固定裝置,可創建一個新的測試應用程序,如下所示:
@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
這是有道理的,因為我試圖多次添加同一視圖...為什么每次運行新測試時都沒有得到一個新的應用程序實例?
我什至不確定這是Flask問題還是pytest問題... :(
我可以通過將您為安裝實例化的所有內容移動到安裝中(甚至導入您正在使用的庫)來解決類似的問題。 當然,可以像在整個燒瓶應用程序中一樣使用create_app()方法,以一種更為優雅的方式完成此操作。 這里要注意的重要一點是,將使狀態(此處是端點)不在全局范圍內的實例,然后將其移入create_app()方法。
告訴我您是否需要更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.