【问题标题】:How can I set&get cookie via testing Flask application with pytest?如何通过使用 pytest 测试 Flask 应用程序来设置和获取 cookie?
【发布时间】:2020-06-14 20:32:37
【问题描述】:

我无法获取之前通过flask.test_client 设置的cookie。 看看吧

我的灯具:

    @pytest.fixture(scope='module')
    def client():
        app.config['TESTING'] = True
        settings = Settings()
        ctx = app.app_context()
        ctx.push()
        with app.test_client() as client:
            yield client
        ctx.pop()
        os.system("rm -rf logs json")

还有测试:

    def test_test(client):
        # order cookie is set to url_encoded '{}' by default
        to_set = {"1": 2}
        client.set_cookie('order', json.dumps(to_set))
        print(request.cookies.get('order'))  # prints url-encoded '{}'

我做错了什么?我需要获取我之前为测试设置的 cookie。我该怎么做?

【问题讨论】:

    标签: python python-3.x flask pytest


    【解决方案1】:

    我想你忘记了一个论点。
    Client.set_cookie(server_name, key, value)

    我也知道 set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None) .
    这指的是 Flask 应用程序对象本身在您的应用程序中设置 cookie。它不是为了测试。

    我找不到这方面的原始文档,但查看了here

    您从app.test_client () 收到的FlaskClient flask.testing.FlaskClient 派生自werkzeug.testing.Client

    werkzeug.testing.Client 的源代码中有以下内容。

    def set_cookie (
             self,
             server_name,
             key,
             value = "",
             max_age = None,
             expires = None,
             path = "/",
             domain = None,
             secure = None,
             httponly = false,
             samesite = None,
             charset = "utf-8",
         )
    

    (源代码文件:“lib/python3.8/site-packages/werkzeug/test.py”、“lib/python3.8/site-packages/flask/testing.py”)。

    我的项目中有类似的问题。在同一主题上还有其他关于 SO 的问题 hereherehere

    【讨论】:

    • 来自文档:Response.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)
    • 我已经更新了我的答案。也许这将使我们更接近解决方案。我还想检查在基于令牌的身份验证中,cookie 中是否存在相应的令牌。
    • 非常感谢!这决定了我的问题。所以,对我来说正确的 set_cookie 请求是client.set_cookie('/', 'order', json.dumps(to_set))
    猜你喜欢
    • 2019-02-08
    • 2013-01-30
    • 2011-06-28
    • 2013-01-31
    • 2023-04-01
    • 2022-01-12
    • 2020-03-15
    • 2014-12-11
    • 1970-01-01
    相关资源
    最近更新 更多