如何在 Flask 中为经过身份验证的 URL 编写测试用例

how to write test cases for authenticated urls in flask

我正在使用带有 mongoengine 和登录管理器的 flask 来维护会话。我想为经过身份验证的视图编写测试用例。任何人都可以 help/suggestions 关于这个。

首先,我建议使用 pytest, and the flask-pytest 库,它包含一些非常方便的功能,可以让这一切变得更容易。

flask-pytest 开箱即用 client fixture,根据文档,它指的是 Flask.test_client

你想要做的是模仿一个有效的会话(例如,但是你的应用正在验证用户是"logged in")

以下是在没有任何支持库的情况下执行此操作的方法:

import app
from flask import url_for

def test_authenticated_route():
    app.testing = True
    client = app.test_client()

    with client.session_transaction() as sess:
        # here you can assign whatever you need to
        # emulate a "logged in" user...
        sess["user"] = {"email": "test_user@example.com"}

    # now, you can access "authenticated" endpoints
    response = client.get(url_for(".protected_route"))
    assert response.status_code == 200

这也在 Flask docs 中讨论。