python-3.x - 启动本地烧瓶服务器以使用 pytest 进行测试
问题描述
我有以下问题。
我想在部署到生产之前在本地烧瓶服务器上运行测试。我为此使用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/'
这使我可以通过键入命令来测试生产 api,pytest
并通过键入来测试本地烧瓶服务器pytest --testenv=local
这段代码完美无缺。
我的问题是,每次我想像这样在本地进行测试时,我都必须从终端手动实例化本地烧瓶服务器:
source ../pypyenv/bin/activate
python ../app.py
现在我想添加一个夹具,在测试开始时在后台启动一个终端,并在完成测试后关闭服务器。经过大量的研究和测试,我仍然无法让它工作。这是我添加到 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): Max retries exceeded with url: /login (Caused by NewConnectionError(': 无法建立新连接: [Errno 111] Connection denied', ))
/usr/lib/python3/dist-packages/requests/adapters.py:437: ConnectionError
这对我来说意味着 app.py 下的烧瓶服务器不在线。有什么建议么?我对更优雅的选择持开放态度
解决方案
对于本地测试,Flasktest_client
是一个更优雅的解决方案。请参阅有关测试的文档。您可以创建一个夹具test_client
并使用它创建测试请求:
@pytest.fixture
def app():
app = create_app()
yield app
# teardown here
@pytest.fixture
def client(app):
return app.test_client()
并像这样使用它:
def test_can_login(client):
response = client.post('/login', data={username='username', password='password'})
assert response.status_code == 200
如果唯一的问题是手动步骤,则可以考虑使用 bash 脚本为您进行手动设置,然后执行pytest
.
推荐阅读
- php - WooCommerce 更改产品标题?
- openssl - X509_REQ_sign 使用引擎
- javascript - 无论如何动态使用jquery的toggle()?
- python - 如何将元素附加到一对坐标以制作多维列表?
- android - 在 Android Studion 中为两个 URL 使用 AsyncTask 时出现问题
- r - ggplot2:geom_bar 和 position_dodge:不以 x 轴为中心(因子)
- python-3.x - Python firebase_admin.credentials 没有属性 Certificate
- ruby-on-rails - 如何在不出现“我们很抱歉,但出了点问题”的情况下推送到 Heroku
- r - 如何根据列值在行上循环操作?R
- c - 如何在 C 中以适当的间距生成随机数?