0

我正在使用带有 mongoengine 和登录管理器的烧瓶进行会话维护。我想为经过身份验证的视图编写测试用例。任何人都可以对此提供帮助/建议。

4

1 回答 1

1

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

flask-pytest带有一个开箱即用的client夹具,根据文档,它指的是Flask.test_client

您想要做的是模拟一个有效的会话(例如,您的应用程序正在验证用户是否“登录”)

以下是在没有任何支持库的情况下如何做到这一点:

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 文档中进行了讨论。

于 2018-04-10T13:17:37.180 回答