[英]pytest is failed: can't find the requested URL
I have this Flask
app: 我有这个Flask
应用程序:
myapp.py : 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"
I want to write some pytest tests so I created two files: 我想编写一些pytest测试,所以我创建了两个文件:
conftest.py: 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 test_endpoints.py
import pytest
from flask import *
def test_hello(client):
response = client.get("/")
assert response.data == b'Hello everyone'
When I run pytest, I get this error: 当我运行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>
Why pytest
can't find the endpoint ? 为什么pytest
找不到端点? What can I add here to let it work ? 我可以在这里添加些什么使其起作用?
You're not adding any routes to the app
you get from create_app()
in your fixture. 您不会在设备中添加任何从create_app()
获取的app
路由。
If you consider your code 如果您考虑您的代码
def create_app():
app = Flask(__name__)
return app
app = create_app()
# ...
@app.route("/")
def hello():
return "Hello everyone"
, that hello
route is only added to that global app
instance, not the one you acquire from the fixture. ,则该hello
路由仅添加到该全局app
实例,而不是您从固定装置获取的路由。
The Flask tutorial, which covers testing , uses blueprints to mount paths in the create_app
function . 涵盖测试的Flask教程使用蓝图在create_app
函数中安装路径 。 You might want to do that too; 您可能也想这样做。 something like this. 这样的事情。
bp = Blueprint('greetings', __name__)
@bp.route("/")
def hello():
return "Hello everyone"
def create_app():
app = Flask(__name__)
app.register_blueprint(bp)
return app
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.