我开始使用 Flask 和 Pytest 来通过单元测试实现休息服务,但我遇到了一些麻烦。
我想为我的简单端点做一个简单的测试,但我不断得到一个Working outside of application context.
运行测试时出错。
这是终点:
from flask import jsonify, request, Blueprint
STATUS_API = Blueprint('status_api', __name__)
def get_blueprint():
"""Return the blueprint for the main app module"""
return STATUS_API
@STATUS_API.route('/status', methods=['GET'])
def get_status():
return jsonify({
'status' : 'alive'
})
这就是我尝试测试它的方式(我知道它应该无法通过测试):
import pytest
from routes import status_api
def test_get_status():
assert status_api.get_status() == ''
我猜我只是无法在不构建整个应用程序的情况下尝试该方法。但如果是这样的话我真的不知道如何解决这个问题
The Flask 测试文档还不错。
您应该创建一个所谓的视图函数,而不是导入视图函数test client
,例如作为 pytest 固定装置。
对于我的最后一个 Flask 应用程序,它看起来像:
@pytest.fixture
def client():
app = create_app()
app.config['TESTING'] = True
with app.app_context():
with app.test_client() as client:
yield client
(create_app
是我的应用程序工厂)
然后您可以轻松创建测试,如下所示:
def test_status(client):
rv = client.get('/stats')
assert ...
正如一开始所提到的,官方文档真的很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)