How to initialize session data in automated test? (python 2.7, webpy, nosetests)

久未见 提交于 2019-12-07 01:16:32

You don't need to initialise session in your test, since when you make app.request() call, your app will auto init session for you. The issue here is you don't maintain session id in your test ( your test is like a client as any browser ).

The solution is that when you make first app.request(), record the session id in the response headers. Then supply with the session id when you make subsequent app.request()

Here is my code:

First I make a helper function in tests/tools.py to extract the session id from response header:

def get_session_id(resp):
    cookies_str = resp.headers['Set-Cookie']
    if cookies_str:
        for kv in cookies_str.split(';'):
            if 'webpy_session_id=' in kv:
                return kv

then write test as:

def test_session():
    resp = app.request('/')
    session_id = get_session_id(resp)

    resp1 = app.request('/game', headers={'Cookie':session_id})
    assert_response(resp1, status='200', contains='Central Corridor')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!