Python 3.x 启动本地flask服务器,以便使用pytest进行测试

Python 3.x 启动本地flask服务器,以便使用pytest进行测试,python-3.x,flask,subprocess,pytest,Python 3.x,Flask,Subprocess,Pytest,我有以下问题 在部署到生产环境之前,我希望在本地flask服务器上运行测试。我用pytest来做这个。我的conftest.py目前看起来是这样的: import pytest from toolbox import Toolbox import subprocess def pytest_addoption(parser): """Add option to pass --testenv=local to pytest cli command""" parser.addop

我有以下问题

在部署到生产环境之前,我希望在本地flask服务器上运行测试。我用pytest来做这个。我的conftest.py目前看起来是这样的:

import pytest
from toolbox import Toolbox
import subprocess


def pytest_addoption(parser):
    """Add option to pass --testenv=local to pytest cli command"""
    parser.addoption(
        "--testenv", action="store", default="exodemo", help="my option: type1 or type2"
    )


@pytest.fixture(scope="module")
def testenv(request):
    return request.config.getoption("--testenv")


@pytest.fixture(scope="module")
def testurl(testenv):
        if testenv == 'local':
            return 'http://localhost:5000/'
        else:
            return 'https://api.domain.com/'
这允许我通过键入命令
pytest
来测试生产api,并通过键入
pytest--testenv=local
来测试本地flask服务器

这段代码工作完美无瑕

我的问题是,每次我想进行本地测试时,都必须从终端手动实例化本地flask服务器,如下所示:

source ../pypyenv/bin/activate
python ../app.py
def test_can_login(client):
    response = client.post('/login', data={username='username', password='password'})
    assert response.status_code == 200
现在我想添加一个装置,在测试开始时在后台启动终端,并在完成测试后关闭服务器。经过大量的研究和测试,我仍然无法让它工作。这是我添加到conftest.py的行:

@pytest.fixture(scope="module", autouse=True)
def spinup(testenv):
    if testenv == 'local':
        cmd = ['../pypyenv/bin/python', '../app.py']
        p = subprocess.Popen(cmd, shell=True)
        yield
        p.terminate()
    else:
        pass
我收到的错误来自请求包,该包表示没有连接/被拒绝

E requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost',port=5000):超过最大重试次数 使用url:/login(由以下原因引起) NewConnectionError(':未能建立新连接: [Errno 111]连接被拒绝',))

/usr/lib/python3/dist包/请求/适配器。py:437: 连接者


这对我来说意味着app.py下的flask服务器不在线。有什么建议吗?我愿意接受更优雅的替代方案

用于本地测试。烧瓶
测试客户机
是一个更优雅的解决方案。请参阅上的文档。您可以为
test\u客户端创建一个fixture
,并使用该fixture创建测试请求:

@pytest.fixture
def app():
    app = create_app()
    yield app
    # teardown here

@pytest.fixture
def client(app):
    return app.test_client()
然后像这样使用它:

source ../pypyenv/bin/activate
python ../app.py
def test_can_login(client):
    response = client.post('/login', data={username='username', password='password'})
    assert response.status_code == 200

如果唯一的问题是手动步骤,也许考虑一个BASH脚本,为你做手动设置,然后执行<代码> PyTest。< /P> < P>用BASH脚本(谢谢)Ekuulela)我现在终于成功了。 我添加了一个fixture,在新的终端窗口中调用bashscript

spinserver.sh
。这在ubuntu中工作,命令在不同的环境中是不同的(请参阅了解其他环境)

这里是非常简单的bash脚本

#!/bin/bash
cd ..
source pypyenv/bin/activate
python app.py
  • sleep命令是必需的,因为服务器需要一些时间来执行 初始化
  • 别忘了让bash脚本可执行(chmod) u+x spinserver.sh)
  • 我试着在
    yield
    之后进行拆卸,但p.kill实际上没有 关上窗户。这对我来说是可以接受的,因为这无关紧要 如果我必须手动关闭终端窗口&我甚至可以看到 必要时进行调试

为此,我使用以下方法,以便测试配置也保留在测试服务器中

@pytest.fixture(scope="session")
def app():
    db_fd, db_path = tempfile.mkstemp()

    app = create_app({
        'TESTING': True,
        'DATABASE': db_path
    })

    yield app

    os.close(db_fd)
    os.unlink(db_path)

from flask import request
def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@pytest.fixture
def server(app):
    @app.route('/shutdown',methods=('POST',))
    def shutdown():
        shutdown_server()
        return 'Shutting down server ...'

    import threading    
    t = threading.Thread(target=app.run)
    yield t.start()

    import requests
    requests.post('http://localhost:5000/shutdown')

参考资料


谢谢!问题仍然是我不能用这个激活并运行virtualenv。我已经阅读了flask文档,但它没有显示如何激活virtualenv。问题的另一个目标是在在线api测试和本地flask服务器测试之间切换。如果我必须在所有测试函数中使用“client”作为参数,那么它们一般也不能用于针对在线api进行测试。我认为尝试从python应用程序中激活virtual env没有意义,但您可以编写一个bash脚本,来完成您现在手动执行的任何操作。