gpt4 book ai didi

python - pytest失败: can't find the requested URL

转载 作者:行者123 更新时间:2023-12-01 01:43:56 25 4
gpt4 key购买 nike

我有这个Flask应用程序:

myapp.py:

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

app = create_app()
session = session_factory()


def connect_db():
engine = get_engine()
return engine.connect()

@app.route("/")
def hello():
return "Hello everyone"

我想编写一些 pytest 测试,所以我创建了两个文件:

conftest.py:

import pytest
from app.myapp import create_app

@pytest.fixture
def app():
app = create_app()
return app

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

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

test_endpoints.py

import pytest
from flask import *

def test_hello(client):
response = client.get("/")
assert response.data == b'Hello everyone'

当我运行 pytest 时,出现此错误:

>       assert response.data == b'Hello everyone'
E assert '<!DOCTYPE HT... again.</p>\n' == 'Hello everyone'
E + Hello everyone
E - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
E - <title>404 Not Found</title>
E - <h1>Not Found</h1>
E - <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>

为什么pytest找不到端点?我可以在此处添加什么以使其正常工作?

最佳答案

您没有向您的装置中通过 create_app() 获得的 app 添加任何路由。

如果你考虑你的代码

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

app = create_app()

# ...

@app.route("/")
def hello():
return "Hello everyone"

,该 hello 路由仅添加到该全局 app 实例,而不是您从固定装置获取的实例。

Flask 教程,covers testing , uses blueprints to mount paths in the create_app function 。您可能也想这样做;像这样的东西。

bp = Blueprint('greetings', __name__)

@bp.route("/")
def hello():
return "Hello everyone"

def create_app():
app = Flask(__name__)
app.register_blueprint(bp)
return app

关于python - pytest失败: can't find the requested URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51591906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com