Flask 保持实时服务器用于测试(Selenium)

Flask keep live server working for tests (Selenium)

首先,我知道 flask-testing 库带有 LiveServerTestCase class,但它自 2017 年以来就没有更新过,而且 GitHub 充满了无法正常工作的问题在 Windows 或 MacOs 上都没有,我还没有找到任何其他解决方案。

我正在尝试使用 selenium 为 Flask 应用程序编写一些测试,以验证此应用程序中的 FlaskForms。

像这样的简单测试:

def test_start(app):
    driver.get("http://127.0.0.1:5000/endpoint")
    authenticate(driver)

属于 selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_CONNECTION_REFUSED 错误。 (据我所知,在我的案例中,应用程序在 @pytest.fixtures 中创建并立即关闭,我需要找到一种方法在整个测试期间保持它 运行)

我的问题是:是否可以在每个测试中创建一些将继续工作的实时服务器,以便我可以通过 selenium 调用 API 端点?

简单的装置如果有帮助的话:

@pytest.fixture
def app():
    app = create_app()
    ...
    with app.context():
        # creating db
        ...
    yield app

还有:

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

终于全部搞定了。我的 conftest.py

import multiprocessing
import pytest

from app import create_app


@pytest.fixture(scope="session")
def app():
    app = create_app()
    multiprocessing.set_start_method("fork")
    return app


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

重要的是,使用 python <3.8 行 multiprocessing.set_start_method("fork") 是没有必要的(据我在 v.3.8 中的理解,他们重构了多处理模块,所以如果没有这条线,你会得到 pickle Error windows 和 Mac).

一个简单的测试看起来像

def test_add_endpoint_to_live_server(live_server):
    @live_server.app.route('/tests-endpoint')
    def test_endpoint():
        return 'got it', 200

    live_server.start()

    res = urlopen(url_for('.te', _external=True))# ".te is a method path I am calling"
    assert  url_for('.te', _external=True) == "some url"
    assert res.code == 200
    assert b'got it' in res.read()

我也在用url_for。重点是每次实时服务器在随机端口上启动并且 url_for 函数在内部生成具有正确端口的 url。所以现在实时服务器是 运行 并且可以实施 selenium 测试。