为什么我的Flask应用返回测试状态码为308的响应?
问题描述:
我正在对我的Flask应用进行单元测试.被测试的代码如下:
I'm unit testing my Flask app. The code under test is as follows:
@app.route("/my_endpoint/", methods=["GET"])
def say_hello():
"""
Greets the user.
"""
name = request.args.get("name")
return f"Hello {name}"
测试如下:
class TestFlaskApp:
def test_my_endpoint(self):
"""
Tests that my endpoint returns the result as plain text.
:return:
"""
client = app.test_client()
response = client.get("/my_endpoint?name=Peter")
assert response.status_code == status.HTTP_200_OK
assert response.data.decode() == "Hello Peter"
错误是:
预期:200实际:308
Expected :200 Actual :308
因此,而不是确定";(200)我收到了永久重定向"消息,(308)
So instead of "OK" (200) I'm getting a "Permanent Redirect" (308)
答
如果 @ app.route
以斜杠结尾,则还必须在测试中使用斜杠:代替
If the @app.route
ends with a slash you must also use the slash in the test:
Instead of
response = client.get("/my_endpoint?name=Peter")
使用
response = client.get("/my_endpoint/?name=Peter")
在单元测试中.
这很有意义,但是我花了很长时间才找到.
It makes sense yet took me too long time to find out.