Flask pytest和application factory的简单烧瓶示例不起作用

Flask pytest和application factory的简单烧瓶示例不起作用,flask,pytest,Flask,Pytest,我对烧瓶还不熟悉,我已经建立了一个简单的烧瓶示例和两个使用pytest的测试(请参阅)。当我只运行一个测试时,它可以工作,但如果我同时运行两个测试,它就不能工作。 有人知道为什么吗?我想我在这里遗漏了烧瓶工作原理的一些基本知识 代码结构: app/\uuuuu init\uuuuuuu.py app/views.py tests/conftest.py tests/test\u app.py 问题在于,当您在当前应用程序中将路由注册为app时,您在app/views.py中注册路

我对烧瓶还不熟悉,我已经建立了一个简单的烧瓶示例和两个使用pytest的测试(请参阅)。当我只运行一个测试时,它可以工作,但如果我同时运行两个测试,它就不能工作。
有人知道为什么吗?我想我在这里遗漏了烧瓶工作原理的一些基本知识

代码结构:

  • app/\uuuuu init\uuuuuuu.py
  • app/views.py
  • tests/conftest.py
  • tests/test\u app.py

问题在于,当您在
当前应用程序中将路由注册为app
时,您在
app/views.py
中注册路由。我不确定在不使用蓝图的情况下如何应用应用程序工厂模式,因为文档中的说明意味着它们对于模式是必需的:

如果您已经在为应用程序使用软件包和蓝图[…]

因此,我调整了您的代码以使用蓝图:

app/main/\uuuuuu init\uuuuuuu.py

from flask import Blueprint

bp = Blueprint('main', __name__)

from app.main import views
from app.main import bp


@bp.route('/')
def index():
    return 'Index Page'


@bp.route('/hello')
def hello():
    return 'Hello World!'
from flask import Flask


def create_app():
    app = Flask(__name__)

    # register routes with app instead of current_app:
    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    return app
app/views.py
->
app/main/views.py

from flask import Blueprint

bp = Blueprint('main', __name__)

from app.main import views
from app.main import bp


@bp.route('/')
def index():
    return 'Index Page'


@bp.route('/hello')
def hello():
    return 'Hello World!'
from flask import Flask


def create_app():
    app = Flask(__name__)

    # register routes with app instead of current_app:
    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    return app
app/\uuuuu init\uuuuuuuuuuuuupy

from flask import Blueprint

bp = Blueprint('main', __name__)

from app.main import views
from app.main import bp


@bp.route('/')
def index():
    return 'Index Page'


@bp.route('/hello')
def hello():
    return 'Hello World!'
from flask import Flask


def create_app():
    app = Flask(__name__)

    # register routes with app instead of current_app:
    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    return app
然后您的测试按预期工作:

$ python -m pytest tests
============================== test session starts ==============================
platform darwin -- Python 3.6.5, pytest-6.1.0, py-1.9.0, pluggy-0.13.1
rootdir: /Users/oschlueter/github/simple-flask-example-with-pytest
collected 2 items                                                               

tests/test_app.py ..                                                      [100%]

=============================== 2 passed in 0.02s ===============================

对我来说,我不需要移动文件夹或更改代码,但我只是使用了你的建议,即
python-m pytest tests
,而不是
pytest
,它通过了测试。