为什么我的 Flask 应用程序在测试时返回状态代码为 308 的响应?

kon*_*tin 3 pytest flask

我正在对我的 Flask 应用程序进行单元测试。测试的代码如下:

@app.route("/my_endpoint/", methods=["GET"])
def say_hello():
    """
    Greets the user.
    """
    name = request.args.get("name")
    return f"Hello {name}"

Run Code Online (Sandbox Code Playgroud)

测试看起来像这样:

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"
Run Code Online (Sandbox Code Playgroud)

错误是:

预计:200 实际:308

因此,我得到的不是“确定”(200),而是“永久重定向”(308)

kon*_*tin 6

如果@app.route以斜杠结尾,您还必须在测试中使用斜杠:而不是

response = client.get("/my_endpoint?name=Peter")
Run Code Online (Sandbox Code Playgroud)

使用

response = client.get("/my_endpoint/?name=Peter")
Run Code Online (Sandbox Code Playgroud)

在你的单元测试中。

这是有道理的,但我花了很长时间才发现。