在 pytest 下运行完整的 Flask 服务器来处理给定端口上的 HTTP 请求

问题描述 投票:0回答:1

通常,在测试端点时,Flask 文档建议执行以下操作:

import pytest
from my_project import create_app

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

    yield app


@pytest.fixture()
def client(app):
    return app.test_client()

然后在测试中使用

client
夹具,如下所示:

def test_ping(client):
    response = client.get("/foobar")
    assert response.status_code == 200

但是,在某些非常特殊的情况下,处理

/foobar
端点的代码可能需要对 Flask 服务器进行 HTTP 回调(想象一下它导入了一个设计不佳的库,该库需要从端点获取一些数据,并且它不允许您注入自定义提取器,因此您所能做的就是指定自定义 URL)。如何在后台线程中运行整个 Flask 服务器?

python flask pytest werkzeug
1个回答
0
投票

为此目的,过去可以“利用”werkzeug.server.shutdown机制。不幸的是,这已被弃用并

删除
但是,这种机制并不是绝对必要的。如果您只需要服务器在运行测试之前启动一次(在

session

级别),那么您可以将其作为

daemon
后台线程运行,并且可以跳过
thread.join()
,因为当测试完成时,它将是唯一剩下运行的线程,当只剩下
daemon
线程时,Python 进程就会退出。详细信息
这里
。如果服务器在测试执行之前没有机会启动,则可能会出现竞争条件,但这可以通过一些睡眠来“修复”...... 这是我的

conftest.py

中最终的代码:

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

    thread = Thread(target=app.run, daemon=True, kwargs=dict(host='localhost', port=5000))
    thread.start()

    yield app


@pytest.fixture(scope='module')
def client(app):
    return app.test_client()

所有需要这个成熟的 Flask 服务器启动并运行的测试都必须使用 
client

夹具,它依赖于

app
夹具。
    

© www.soinside.com 2019 - 2024. All rights reserved.