【问题标题】:Flask pytest fails when testing a route测试路由时 Flask pytest 失败
【发布时间】:2021-02-06 22:19:35
【问题描述】:

我不知道为什么我的 pytest 不应该失败。

我有一个 REST API 烧瓶服务器,具有以下文件夹结构:

.
├── api
│   ├── conf
│   ├── database
│   ├── error
│   ├── handlers
│   ├── models
│   ├── roles
│   ├── schemas
│   └── test.db
├── main.py
├── tests
│   ├── conftest.py
│   └── test_routes.py

我的测试是:

测试/conftest.py:

import pytest

from main import app as flask_app

@pytest.fixture
def app():
    yield flask_app
    

@pytest.fixture
def client(app):
    return app.test_client()

测试/test_routes.py:

def test_algorithms_get(app, client):
    res = client.get('/algorithms')
    assert res.status_code == 200

现在,我尝试在 . 文件夹中运行 python3 -m pytest,同时使用烧瓶服务器运行和未运行,但测试总是失败,我得到 404 status_code 而不是 200。我确定路线是完美的工作,但我不明白为什么测试失败。

这是我第一次使用 pytest(或任何单元测试框架),所以我确定我遗漏了一些东西,非常感谢任何帮助。

【问题讨论】:

  • 我也是个新手。但是您是否尝试过使用 client.get 中的完整 URL?还可以查看路线的实际代码。
  • @mzndr 感谢您的回复。我解决了。事实上,这是我创建 Flask 应用程序的配置错误。

标签: python flask pytest


【解决方案1】:

解决了。 这是一个配置错误。

确实,我在 create_app() 工厂中犯了一个错误。

据我所知,最好在服务器父目录的 init.py 文件中定义 create_app(我在 main.py 中定义函数)。

为清楚起见,我将 create_app 工厂定义移至此处 (*):

.
├── api
│   ├── __init__.py *
│   ├── conf
│   ├── database
│   ├── error
│   ├── handlers
│   ├── models
│   ├── roles
│   ├── schemas
│   └── test.db
├── main.py
├── tests
│   ├── conftest.py
│   └── test_routes.py

新的测试/conftest.py:

import pytest

from api import create_app


@pytest.fixture
def app():
    flask_app = create_app({'TESTING': True})
    yield flask_app


@pytest.fixture
def client(app):
    return app.test_client()

@pytest.fixture
def runner(app):
    return app.test_cli_runner()

最后,我在最上面的文件夹 (.) 中调用 python3 -m pytest 来运行测试。

现在测试正在运行,我还可以为测试和其他用例创建不同的配置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2016-06-02
    • 1970-01-01
    • 2019-09-14
    • 2018-04-05
    • 1970-01-01
    • 2014-08-02
    相关资源
    最近更新 更多