pytest-flask - 无法从测试客户端函数访问应用程序的端点

时间:2017-12-06 17:41:58

标签: python flask

编辑:

在移动内容并重命名之后,我正在修改此帖子以反映我当前的问题。

我无法访问views文件夹内的文件中的端点。我想在test_example.py中明确导入它们,或者已经在__init__.py中导入它们就可以了。

运行pytest时出现错误:

    rv = self._partial_build(endpoint, values, method, append_unknown)
    if rv is None:
>       raise BuildError(endpoint, values, method, self)
E       werkzeug.routing.BuildError: Could not build url for endpoint '/api/create_booth'. Did you mean 'static' instead? 

另外,我尝试用url_for('some_endpoint')替换url_for('some_endpoint', _external=True) - 没有效果。

这是我的目录结构和相关文件的简化内容:

目录结构

server/
    my_app/
        __init__.py
        views/
            __init__.py
            some_views.py
    test/
        __init__.py
        conftest.py
        test_example.py

__ INIT __ PY:

from flask import Flask

def create_app():
    app = Flask(__name__)
    return app

app = create_app()
from views.some_view import *    

if __name__ == '__main__':
    app.run(debug=True)

conftest.py

import pytest
from my_app import create_app

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

test_example.py

from flask import url_for
from my_app.views.some_views import some_endpoint

def test_some_endpoint(client):
    assert client.post(url_for('some_endpoint'),
           data=json.dumps(dict(some_attr='some_value')),
           content_type='application/json').status_code == 200

some_views.py

from my_app import app

@app.route('/api/some_endpoint/', methods=['POST'])
def some_endpoint():
    return "success"

我正在运行pytest-flask-0.10.0Python 3.4.3Flask 0.12.2

1 个答案:

答案 0 :(得分:2)

我认为您应该考虑重新组织您的应用结构。您的方式将导致循环导入,这可能是您创建应用程序后导入视图的原因。我建议将您的app工厂移动到自己的文件中,因为您将在测试中重复使用它。

程序my_app / factory.py

def create_app():
    # init extensions
    # init blueprints
    return app

然后,当您的应用很小时,只需将视图保留在app.py中,当您的应用变得更大时,请考虑实施blueprint设计模式 - > docs

程序my_app / app.py

from factory import create_app

app = create_app()

@app.route('/')
def index():
    return 'hello'

if __name__ == '__main__':
    app.run()

在你的测试中

test_example.py

from factory import create_app

@py.fixture
def client():
    return create_app().test_client()

def test_route(client):
    response = client.get('/')
    assert response.json() == 'hello', 'Route should return "hello"'

Miguel Grinberg在Flask上有一个非常棒的blog他是Flask Web Development的作者,这是一个很好的资源。看起来他正在重写他关于烧瓶的教程。

蓝图示例

程序my_app / factory.py

def create_app():
    app = Flask(__name__)
    from main import main
    app.register_blueprint(main)

    return app

程序my_app / main.py

from flask import Blueprint

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return "hello"

程序my_app / app.py

from factory import create_app

app = create_app()

if __name__ == '__main__':
    app.run()

希望有所帮助