首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flask为测试保持实时服务器工作(Selenium)

Flask为测试保持实时服务器工作(Selenium)
EN

Stack Overflow用户
提问于 2021-08-03 15:32:41
回答 1查看 59关注 0票数 0

首先,我知道带有LiveServerTestCase类的flask-testing库,但它自2017年以来就没有更新过,GitHub充满了问题,它既不能在Windows或MacOs上运行,我也没有找到任何其他的解决方案。

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

如下所示的简单测试:

代码语言:javascript
复制
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端点?

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

代码语言:javascript
复制
@pytest.fixture
def app():
    app = create_app()
    ...
    with app.context():
        # creating db
        ...
    yield app

另外:

代码语言:javascript
复制
@pytest.fixture
def client(app):
    """Test client"""
    return app.test_client()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-05 11:50:50

终于让一切运转起来了。我的conftest.py

代码语言:javascript
复制
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中,他们重构了多处理模块,因此在没有这行的情况下,你将在windows和Mac上得到pickle Error )。

一个简单的测试看起来像

代码语言:javascript
复制
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测试。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68638915

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档