python - 使用 pytest-flask + pytest-selenium (docker) 测试 Flask 应用程序

标签 python selenium docker flask pytest-selenium

我正在尝试在 docker 容器中测试 Flask 网络应用程序,这对我来说是新的。我的堆栈如下:

  • 火狐
  • Selenium
  • pytest-selenium
  • pytest flask

这是我的 Flask 应用程序文件:

from flask import Flask

def create_app():
    app = Flask(__name__)
    return app

app = create_app()

@app.route('/')
def index():
    return render_template('index.html')

现在,我的测试文件验证了我的索引页面的标题:

import pytest
from app import create_app

# from https://github.com/pytest-dev/pytest-selenium/issues/135
@pytest.fixture
def firefox_options(request, firefox_options):
    firefox_options.add_argument('--headless')
    return firefox_options

# from https://pytest-flask.readthedocs.io/en/latest/tutorial.html#step-2-configure
@pytest.fixture
def app():
    app = create_app()
    return app

# from https://pytest-flask.readthedocs.io/en/latest/features.html#start-live-server-start-live-server-automatically-default
@pytest.mark.usefixtures('live_server')
class TestLiveServer:

    def test_homepage(self, selenium):
        selenium.get('http://0.0.0.0:5000')
        h1 = selenium.find_element_by_tag_name('h1')
        assert h1 == 'title'

当我运行我的测试时:

pytest --driver Firefox --driver-path /usr/local/bin/firefox test_app.py

我收到以下错误(这似乎是由于 firefox 未处于 headless 模式)。

selenium.common.exceptions.WebDriverException: Message: Service /usr/local/bin/firefox unexpectedly exited. Status code was: 1
Error: no DISPLAY environment variable specified

我可以运行 firefox --headless 但我的 pytest fixture 似乎无法完成设置。有更好的方法吗?

现在,如果我将 selenium.get() 替换为 urlopen 只是为了尝试正确初始化应用程序及其连接:

def test_homepage(self):
    res = urlopen('http://0.0.0.0:5000')
    assert b'OK' in res.read()
    assert res.code == 200

我得到错误:

urllib.error.URLError:

我需要以不同方式启动实时服务器吗?或者我应该在某处更改我的主机 + 端口配置?

最佳答案

关于直接调用urllib的问题:

Pytest 的实时服务器默认使用随机端口。您可以将此参数添加到 pytest 调用:

--live-server-port 5000

或者如果没有这个参数,你可以像这样直接调用实时服务器:

import pytest
import requests

from flask import url_for


@pytest.mark.usefixtures('live_server')
def test_something():
    r = requests.get(url_for('index', _external=True))
    assert r.status_code == 200

我想您有一个名为 index 的 View 函数。它会自动添加正确的端口号。

但是这个和docker没有任何关系,怎么运行呢?

关于 Selenium 本身的问题 - 我可以想象与 docker 网络相关的问题。你如何使用它?你有例如。 docker-compose 配置?可以分享吗?

关于python - 使用 pytest-flask + pytest-selenium (docker) 测试 Flask 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52153076/

相关文章:

java - 即使两个字符串完全相同,使用 xpath 的 selenium 中的字符串比较也会失败

python - IDLE 不会在 python 3.0 中启动

java - 单击 webTable 中特定记录的特定按钮

Java Selenium 和 Appium 不起作用无法启动 REST http 接口(interface)监听器

docker - 使用 Travis 时,已安装的 Docker 卷具有不同的所有权

java - 如何在gitlab-ci build中跳过先前的Maven目标?

docker - 部署 nginx 的最佳实践

python - 根据 pandas 中的其他数据帧过滤一个数据帧

python - 在对象列表中创建一个 float

python - 我如何重新使用经过训练的 fastai 模型?