简体   繁体   English

测试路由时 Flask pytest 失败

[英]Flask pytest fails when testing a route

I don't know why my pytest fails when they shouldn't.我不知道为什么我的 pytest 不应该失败。

I have a REST API flask server, with the following folder structure:我有一个 REST API Flask 服务器,文件夹结构如下:

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

My tests are:我的测试是:

tests/conftest.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()

tests/test_routes.py:测试/test_routes.py:

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

Now, I tried running python3 -m pytest in the .现在,我试图运行python3 -m pytest. folder both with flask server running and not running and not, but the test always fails and I get 404 status_code instead of 200. I know for sure that the route is perfectly working, but I can't get why the test fails. Flask 服务器运行和未运行的文件夹,但测试总是失败,我得到 404 status_code 而不是 200。我确信该路由运行良好,但我不明白为什么测试失败。

This is the first time I use pytest (or any Unit Test framework) so I'm sure I'm missing something, any help would be much appreciated.这是我第一次使用 pytest(或任何单元测试框架),所以我确定我遗漏了一些东西,任何帮助将不胜感激。

Solved.解决了。 It was a configuration error.这是一个配置错误。

Indeed, I was making a mistake in the create_app() factory.事实上,我在 create_app() 工厂中犯了一个错误。

As I learned also, it is much better to define the create_app in the init .py file in the parent directory of your server (I was defining the function in main.py).我还了解到,最好在服务器父目录的init .py 文件中定义 create_app(我在 main.py 中定义函数)。

To be clear I moved the create_app factory definition here (*):为了清楚起见,我将 create_app 工厂定义移至此处 (*):

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

New tests/conftest.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()

Finally, I call python3 -m pytest in the uppermost folder ( . ) to run the tests.最后,我在最上面的文件夹 ( . ) 中调用python3 -m pytest来运行测试。

Now tests are working and I'm also able to create different configurations for testing and other use cases.现在测试正在运行,我还能够为测试和其他用例创建不同的配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM