在行为步骤中访问 Flask 会话

Access Flask session in behave steps

我正在使用 Flask 和 behave,遵循说明 here

我正在使用 Flask 测试客户端访问页面(而不是通过类似 Selenium 的浏览器)。例如,在测试客户端调用get得到响应。

我想在我的步骤中访问 Flask 会话数据。 Testing Flask Applications 页面上记录了各种关于访问上下文和会话的技术,但我看不出其中任何一种是我在使用 behave 时所需要的,特别是因为我将同时访问该页面步骤,然后想在另一个中检索会话。

我的 environment.py 看起来像这样:

from my_app import app


def before_scenario(context, scenario):
    app.testing = True
    # load the test config to ensure e.g. right database used
    app.config.from_object('parameters.test')
    context.client = app.test_client()


def after_scenario(context, scenario):
    pass

最接近我需要的 Flask 测试技术是 this one:

with app.test_client() as c:
    rv = c.get('/')
    assert flask.session['foo'] == 42

我遇到的问题是我需要在一个步骤中发出 get 请求,稍后在另一个步骤中检查会话 - 即代码在不同的函数中,所以不能全部包装在 with 块中。

读书会

with statement 本质上是类似于 try/finally 的模式的语法糖(参见 link),所以我可以稍微分解一下,给出以下 environment.py:

from my_app import app


def before_scenario(context, scenario):
    # all the code I had before still here
    # ...
    # and this new line:
    context.client.__enter__()


def after_scenario(context, scenario):
    # the exit code doesn't actually use its parameters, so providing None is fine
    context.client.__exit__(None, None, None)

在我的步骤中,我现在可以像在我的正常应用程序中一样执行 from flask import session 和访问 session。您可以用同样的方式访问request

写作课

正如 Flask 测试页面所说,这种方法 "does not make it possible to also modify the session or to access the session before a request was fired."

如果需要这样做,则需要稍微进一步扩展模式。首先(在 before_scenario 中),将 __enter__() 中的 return 值分配给一个您稍后可以访问的变量:

context.session = context.client.__enter__()

那么,在你的步骤中,你可以这样做:

with context.session.session_transaction() as sess:
    sess['key here'] = some_value

这是我回答开头 link 部分描述的第二种模式。唯一的修改是您需要存储 __enter__() 中的 return 值,因为您没有使用 with 语句。