使用 test_client (Flask) 时出错 - raise ValueError("unknown url type: %r" % self.full_url)
Error when using test_client (Flask) - raise ValueError("unknown url type: %r" % self.full_url)
烧瓶应用代码:
# main.py
from flask import Flask, Response
app = Flask(__name__)
@app.route("/", methods=["POST"])
def post_example():
return Response("aaa")
这是我的测试代码:
# e2e.py
from main import app
test_client = app.test_client()
def test_flask_api_call():
response = test_client.post("/", {"a": "b"})
pass
我不断收到:
raise ValueError("unknown url type: %r" % self.full_url)
ValueError: unknown url type: '://%7B%27a%27:%20%27b%27%7D/'
问题出在 post
方法调用上。您必须将您的 数据 参数命名为 client.post("/", data={"a": "b"})
,如果不是这样,则将其视为 URL.
的一部分
urllib.parse.quote("/" + str({"a": "b"}))
# '/%7B%27a%27%3A%20%27b%27%7D'
这里是重写的测试代码,为客户端初始化定义了一个fixture
。有关 official doc.
上测试烧瓶应用程序的更多信息
import pytest
from main import app
@pytest.fixture(scope="module")
def client():
with app.test_client() as client:
yield client
def test_flask_api_call(client):
response = client.post("/", data={"a": "b"})
assert response.status_code == 200, f"Got bad status code {response.status_code}"
烧瓶应用代码:
# main.py
from flask import Flask, Response
app = Flask(__name__)
@app.route("/", methods=["POST"])
def post_example():
return Response("aaa")
这是我的测试代码:
# e2e.py
from main import app
test_client = app.test_client()
def test_flask_api_call():
response = test_client.post("/", {"a": "b"})
pass
我不断收到:
raise ValueError("unknown url type: %r" % self.full_url)
ValueError: unknown url type: '://%7B%27a%27:%20%27b%27%7D/'
问题出在 post
方法调用上。您必须将您的 数据 参数命名为 client.post("/", data={"a": "b"})
,如果不是这样,则将其视为 URL.
urllib.parse.quote("/" + str({"a": "b"}))
# '/%7B%27a%27%3A%20%27b%27%7D'
这里是重写的测试代码,为客户端初始化定义了一个fixture
。有关 official doc.
import pytest
from main import app
@pytest.fixture(scope="module")
def client():
with app.test_client() as client:
yield client
def test_flask_api_call(client):
response = client.post("/", data={"a": "b"})
assert response.status_code == 200, f"Got bad status code {response.status_code}"