pytest `AssertionError: View function mapping is overwriting an existing endpoint function:` flask-restful while registring blueprint

pytest `AssertionError: View function mapping is overwriting an existing endpoint function:` flask-restful while registring blueprint

问题如下,我创建了一个虚拟示例。文件夹结构是:

.
├── api_bp
│   └── __init__.py
├── app.py
├── pytest.ini
└── tests
    ├── conftest.py
    ├── __init__.py
    ├── test_todo1.py
    └── test_todo2.py

文件夹api_bp里面的代码__init__.py:

# __init__.py

from flask import Blueprint

api_bp = Blueprint('api', __name__)

Flask 应用程序:

# app.py

from flask import Flask, Blueprint
from flask_restful import Api, Resource


class TodoItem(Resource):
    def get(self, id):
        return {'task': 'Say "Hello, World!"'}


def create_app():
    """Initialize the app. """
    app = Flask(__name__)
    from api_bp import api_bp
    # api_bp = Blueprint('api', __name__)
    api = Api(api_bp)

    api.add_resource(TodoItem, '/todos/<int:id>')
    app.register_blueprint(api_bp, url_prefix='/api')

    return app


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

出于测试目的,我有客户端 fixture 和两个针对不同待办事项的测试(我有意将其放入单独的模块):

# conftest.py

import pytest

from app_factory import create_app

@pytest.fixture(scope='module')
def client():
    flask_app = create_app()

    testing_client = flask_app.test_client()

    context = flask_app.app_context()
    context.push()

    yield testing_client

    context.pop()
# test_todo1.py

import pytest

def test_todo2(client):
    """Test"""
    response = client.get('/api/todos/1')
    print(response)
    assert response.status_code == 200
# test_todo2.py

import pytest

def test_todo2(client):
    """Test"""
    response = client.get('/api/todos/2')
    print(response)
    assert response.status_code == 200

所以当我 运行 $ pytest -v 测试它时,我得到了以下错误:

AssertionError: View function mapping is overwriting an existing endpoint function: api.todoitem

发生这种情况是因为注册了蓝图。我想了解在 flask (flask-restful) 与 pytest 结合的情况下发生的魔法。因为如果我像这样定义我的 app.py 模块,它会成功通过测试:

# app.py

from flask import Flask, Blueprint
from flask_restful import Api, Resource


class TodoItem(Resource):
    def get(self, id):
        return {'task': 'Say "Hello, World!"'}


def create_app():
    """Initialize the app. """
    app = Flask(__name__)
    # note: I commented the line below and defined the blueprint in-place
    # from api_bp import api_bp  
    api_bp = Blueprint('api', __name__)
    api = Api(api_bp)

    api.add_resource(TodoItem, '/todos/<int:id>')
    app.register_blueprint(api_bp, url_prefix='/api')

    return app


if __name__ == '__main__':
    app = create_app()
    app.run(debug=True)
$ pytest -v
tests/test_api1.py::test_todo2 PASSED    [ 50%]
tests/test_api2.py::test_todo2 PASSED    [100%]

或者,如果我不使用应用程序工厂,它也可以正常工作:

# app.py

from flask import Flask, Blueprint
from flask_restful import Api, Resource

app = Flask(__name__)
api_bp = Blueprint('api', __name__)
api = Api(api_bp)


class TodoItem(Resource):
    def get(self, id):
        return {'task': 'Say "Hello, World!"'}


api.add_resource(TodoItem, '/todos/<int:id>')
app.register_blueprint(api_bp, url_prefix='/api')

如果我将所有测试放在一个模块中,或者如果我先注册蓝图然后添加资源,也可以解决这个问题:

# app.py

...

def create_app():
    """Initialize the app. """
    app = Flask(__name__)

    from api_bp import api_bp

    api = Api(api_bp)

    app.register_blueprint(api_bp, url_prefix='/api')
    api.add_resource(TodoItem, '/todos/<int:id>')


    return app

...

谁知道这里发生了什么,可以解释一下magic?提前致谢。

所以问题的解释是,当 pytest 设置并在测试中使用客户端时,它会运行 create_app() 并在未在 app.py 中定义蓝图时尝试重用蓝图:

tests/test_api1.py::test_todo2 <flask.blueprints.Blueprint object at 0x7f04a8c9c610>

    SETUP    M client
        tests/test_api1.py::test_todo2 (fixtures used: client)<Response streamed [200 OK]>
PASSED
    TEARDOWN M client
tests/test_api2.py::test_todo2 <flask.blueprints.Blueprint object at 0x7f04a8c9c610>

    SETUP    M clientERROR
    TEARDOWN M client

可以通过以下方式解决:

# api_bp/__init__.py

from flask import Blueprint


get_blueprint = lambda: Blueprint('api', __name__)

并使用:

def create_app():
    """Initialize the app. """
    app = Flask(__name__)
    from api_bp import get_blueprint

    api_bp = get_blueprint()
    api = Api(api_bp)

    api.add_resource(TodoItem, '/todos/<int:id>')
    app.register_blueprint(api_bp, url_prefix='/api')

    return app

因此,解决此类问题的最简单方法是使用适当的 pytest 作用域(而不是 'module'):

@pytest.fixture(scope='session')
def client():
...

更新:

此方法不适用于定义如下管理命令:

class Test(Command):
    def run(self):
        """Runs the tests."""
        pytest.main(['-s', '-v', './tests'])


manager.add_command('test', Test)  # run the tests

使用 python app.py test 你会得到与前面示例相同的错误。有关详细信息,请阅读以下 link 中的 'Note:' 部分:https://docs.pytest.org/en/latest/usage.html#calling-pytest-from-python-code