gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:47:02 24 4
gpt4 key购买 nike

首先我知道flask-testing带有 LiveServerTestCase 类的库,但它自 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 line multiprocessing.set_start_method("fork") 不是必需的(据我在 v.3.8 中的理解,他们重构了 multiprocessing 模块,所以没有这条线你在 Windows 和 Mac 上会出现 pickle Error)。

一个简单的测试看起来像

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 测试。

关于python - Flask 保持实时服务器用于测试(Selenium),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68638915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com