Python pytest失败:can';找不到请求的URL
我有一个Python pytest失败:can';找不到请求的URL,python,flask,pytest,Python,Flask,Pytest,我有一个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 "He
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()
测试端点.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>
>assert response.data==b'Hello everyone'
E断言“您没有向从夹具中的create_app()
获得的app
添加任何路由
如果你考虑你的代码
def create_app():
app = Flask(__name__)
return app
app = create_app()
# ...
@app.route("/")
def hello():
return "Hello everyone"
,该hello
路线仅添加到该全局app
实例中,而不是从夹具中获取的实例
烧瓶教程,其中。你可能也想这么做;像这样的
bp = Blueprint('greetings', __name__)
@bp.route("/")
def hello():
return "Hello everyone"
def create_app():
app = Flask(__name__)
app.register_blueprint(bp)
return app
所以,事实上,我不打算直接调用应用程序端点,但我需要创建“假”端点并对其进行测试?不,不。您只需要使用蓝图进行路由映射,以便在生产应用程序和测试实例之间重用它们。