访问 Flask 测试响应中的所有 cookie

Accessing all cookies in the Flask test response

我用 Flask 测试客户端发出请求后,想访问服务器设置的 cookie。如果我遍历 response.headers,我会看到多个 Set-Cookie header,但如果我这样做 response.headers["Set-Cookie"],我只会得到一个值。此外,header 是难以测试的未解析字符串。

response = client.get("/")
print(response.headers['Set-Cookie'])
'mycookie=value; Expires=Thu, 27-Jun-2019 13:42:19 GMT; Max-Age=1800; Path=/'

for item in response.headers:
    print(item)

('Content-Type', 'application/javascript')
('Content-Length', '215')
('Set-Cookie', 'mycookie=value; Expires=Thu, 27-Jun-2019 13:42:19 GMT; Max-Age=1800; Path=/')
('Set-Cookie', 'mycookie2=another; Domain=.client.com; Expires=Sun, 04-Apr-2021 13:42:19 GMT; Max-Age=62208000; Path=/')
('Set-Cookie', 'mycookie3=something; Domain=.client.com; Expires=Thu, 04-Apr-2019 14:12:19 GMT; Max-Age=1800; Path=/')

为什么访问 Set-Cookie header 只给我一个 header?我如何访问 cookie 及其属性以进行测试?

response.headers 是一种 MultiDict, which provides the getlist 方法,用于获取给定键的所有值。

response.headers.getlist('Set-Cookie')

检查客户端拥有的 cookie 可能比检查响应返回的特定原始 Set-Cookie headers 更有用。 client.cookie_jarCookieJar instance, iterating over it yields Cookie 个实例。例如,获取名称为 "user_id":

的 cookie 的值
client.post("/login")
cookie = next(
    (cookie for cookie in client.cookie_jar if cookie.name == "user_id"),
    None
)
assert cookie is not None
assert cookie.value == "4"

根据您要对 cookie 执行的操作,之前的回答引导我使用稍微不同的版本。

我尝试使用 client.cookie_jar,但我正在测试一些“non-standard”属性,例如 HttpOnlySameSite。来自 client.cookie_jar 的 cookie return 没有 return 它们,所以我改为检查 Set-Cookie header:

from werkzeug.http import parse_cookie

cookies = response.headers.getlist('Set-Cookie')
cookie = next(
    (cookie for cookie in cookies if expected_cookie_name in cookie),
    None
)

assert cookie is not None
cookie_attrs = parse_cookie(cookie)

assert cookie_attrs[expected_cookie_name] == expected_cookie_value
assert 'Secure' in cookie_attrs
assert 'HttpOnly' in cookie_attrs
assert cookie_attrs['SameSite'] == 'Lax'