如何测试Connexion / Flask应用程序? [英] How to test a Connexion/Flask app?

查看:715
本文介绍了如何测试Connexion / Flask应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 Connexion 框架.org /rel =noreferrer> Flask 来构建一个微服务。我想用 py.test 来为我的应用程序编写测试。



pytest-flask doc它表示在 conftest.py 中创建一个夹具来创建应用程序,如下所示:

conftest.py



  import pytest 

from api.main import create_app

$ b $ pytest.fixture
def app():
app = create_app()
返回应用程序

在我的测试中,我使用客户端 $ b

test_api.py



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

但是,当我运行 py.test 时,出现以下错误信息:

  ========================== ==========错误==================================== 
_______________________设置test_api_ping时出错______ __________________

request =< SubRequest'_monkeypatch_response_class'for< Function'test_api_ping'>>
monkeypatch =< _pytest.monkeypatch.MonkeyPatch实例在0x7f9f76b76518>

@ pytest.fixture(autouse = True)
def _monkeypatch_response_class(request,monkeypatch):
在测试套件之前设置自定义响应类并恢复原来的$ b $自定义响应具有`json`属性来轻松测试JSON响应::

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

def test_json(client):
res = client.get(url_for('ping'))
assert res.json == {如果'app'不在request.fixturenames中:
返回

app = request.getfuncargvalue ('app')
monkeypatch.setattr(app,'response_class',
> _make_test_response_class(app.response_class))
E AttributeError:'App'对象没有属性'response_class'

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

main.py



  import connexion 

$ b def create_app():
app = connexion .app(__ name__,port = 8002,)
app.add_api('swagger.yaml')
返回应用程序

$ b if __name__ ==__main__:
create_app()。run()


解决方案

使用灯具



test_api.py
$ b

  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:我的API
版本:'1.0'
消耗:
- application / json
产生:
- application / json
方案:
- https
路径:
/ health:
get:
标签:[Health]
operationId:api.health
summary:健康检查
响应:
'200':
描述:服务器描述当前健康的状态消息

api.py

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



使用Swagger测试器



使用 swagger-tester
$ b

test_api.py

<$来自swagger_tester的p $ p> import swagger_test
$ b authorize_error = {
'get':{
'/ health':[200],
}

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

这个库很酷的地方在于你可以使用你的spec中提供的例子。但是我不认为它可以和 connexion.RestyResolver 一起使用,你必须在每个端点指定OperationId。

I'm using the Connexion framework for Flask to build a microservice. I would like to write tests for my application using py.test.

In the pytest-flask doc it says to create a fixture in conftest.py that creates the app like so:

conftest.py

import pytest

from api.main import create_app


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

In my test I'm using the client fixture like this:

test_api.py

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

However when I run py.test I get the following error message:

==================================== 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'

How can I make py.test work? Here is my create_app function:

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()

解决方案

Using fixtures

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

Using Swagger Tester

Another solution using 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)

Cool thing about this library is that you can use the examples provided in your spec. But I don't think it works out of the box with connexion.RestyResolver: you'll have to specify the OperationId at each endpoint.

这篇关于如何测试Connexion / Flask应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆