为我忙于编写的API编写一些单元测试,尝试在单元测试中设置会话以模拟已经登录的用户。 由于某种原因,它看起来不像会话通过client.get传递到api端点。任何人都知道我做错了什么?
client = app.test_client()
with client.session_transaction() as sess:
sess['username'] = 'bob@example.com'
response = client.get('/users/')
# Looks good
# <SecureCookieSession {'username': 'bob@example.com'}>
print sess
# Nothing in the cookie...
print response.data
# self.assertEquals(
# json.loads(response.data),
# json.loads('{"users": "all"}'))
答案 0 :(得分:2)
您需要移动client.get()
上下文管理器的with
:
with app.test_client() as client:
with client.session_transaction() as sess:
sess['username'] = 'bob@example.com'
response = client.get('/users/')
会话仅在with
块结束时“提交”。