我正在尝试使用 pytest 为 Flask 应用程序编写单元测试。我有一个应用程序工厂:
def create_app():
from flask import Flask
app = Flask(__name__)
app.config.from_object('config')
import os
app.secret_key = os.urandom(24)
from models import db
db.init_app(app)
return app
还有一个测试类:
class TestViews(object):
@classmethod
def setup_class(cls):
cls.app = create_app()
cls.app.testing = True
cls.client = cls.app.test_client()
@classmethod
def teardown_class(cls):
cls.app_context.pop()
def test_create_user(self):
"""
Tests the creation of a new user.
"""
view = TestViews.client.get(url_for('create_users')).status_code == 200
但是当我运行测试时,出现以下错误:
RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.
谷歌搜索告诉我(我认为)使用测试客户端应该创建一个自动应用程序上下文。我错过了什么?
最佳答案
向测试客户端发出请求确实会(间接)推送应用程序上下文。但是,您混淆了 url_for
在视觉上位于测试请求调用内部的事实与实际上在内部调用它的想法。 url_for
调用首先被评估,结果被传递给 client.get
。
url_for
通常用于在应用 内生成 URL,单元测试是外部。通常,您只需在请求中准确写入您要测试的 URL,而不是生成它。
self.client.get('/users/create')
如果你真的想在这里使用 url_for
,你必须在应用上下文中使用。请注意,当您处于应用上下文而非请求上下文中时,您必须设置 SERVER_NAME
配置并传递 _external=False
。但同样,您可能应该只写出您要测试的 URL。
app.config['SERVER_NAME'] = 'localhost'
with self.app.app_context():
url = url_for(..., _external=False)
self.client.get(url, ...)
关于python - 使用 url_for 函数为 Flask 测试客户端生成 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46646603/