gpt4 book ai didi

python - 如何测试 Connexion/Flask 应用程序?

转载 作者:太空狗 更新时间:2023-10-29 17:07:25 26 4
gpt4 key购买 nike

我正在使用 Connexion Flask 的框架构建微服务。我想使用 py.test 为我的应用程序编写测试。

pytest-flask 文档中,它说要在 conftest.py 中创建一个 fixture,它会像这样创建应用程序:

conftest.py

import pytest

from api.main import create_app


@pytest.fixture
def app():
app = create_app()
return app

在我的测试中,我使用这样的 client fixture:

test_api.py

def test_api_ping(client):
res = client.get('/status')
assert res.status == 200

但是,当我运行 py.test 时,我收到以下错误消息:

==================================== ERRORS ====================================
_______________________ ERROR at setup of test_api_ping ________________________

request = <SubRequest '_monkeypatch_response_class' for <Function 'test_api_ping'>>
monkeypatch = <_pytest.monkeypatch.MonkeyPatch instance at 0x7f9f76b76518>

@pytest.fixture(autouse=True)
def _monkeypatch_response_class(request, monkeypatch):
"""Set custom response class before test suite and restore the original
after. Custom response has `json` property to easily test JSON responses::

@app.route('/ping')
def ping():
return jsonify(ping='pong')

def test_json(client):
res = client.get(url_for('ping'))
assert res.json == {'ping': 'pong'}

"""
if 'app' not in request.fixturenames:
return

app = request.getfuncargvalue('app')
monkeypatch.setattr(app, 'response_class',
> _make_test_response_class(app.response_class))
E AttributeError: 'App' object has no attribute 'response_class'

如何让 py.test 工作?这是我的 create_app 函数:

main.py

import connexion


def create_app():
app = connexion.App(__name__, port=8002,)
app.add_api('swagger.yaml')
return app


if __name__ == "__main__":
create_app().run()

最佳答案

使用固定装置

test_api.py

import pytest
import connexion

flask_app = connexion.FlaskApp(__name__)
flask_app.add_api('swagger.yml')


@pytest.fixture(scope='module')
def client():
with flask_app.app.test_client() as c:
yield c


def test_health(client):
response = client.get('/health')
assert response.status_code == 200

swagger.yml

swagger: '2.0'
info:
title: My API
version: '1.0'
consumes:
- application/json
produces:
- application/json
schemes:
- https
paths:
/health:
get:
tags: [Health]
operationId: api.health
summary: Health Check
responses:
'200':
description: Status message from server describing current health

api.py

def health():
return {'msg': 'ok'}, 200

使用 Swagger 测试器

另一种使用 swagger-tester 的解决方案:

test_api.py

from swagger_tester import swagger_test

authorize_error = {
'get': {
'/health': [200],
}
}

def test_swagger():
swagger_test('swagger.yml', authorize_error=authorize_error)

这个库很酷的一点是您可以使用规范中提供的示例。但我不认为它与 connexion.RestyResolver 开箱即用:您必须在每个端点指定 OperationId。

关于python - 如何测试 Connexion/Flask 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42934525/

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