如何在flask资源中测试会话

时间:2014-01-31 17:32:02

标签: python unit-testing session flask

我想测试资源。响应取决于会话中的参数(已记录) 为了测试这个资源,我写了这些测试:

import app
import unittest

class Test(unittest.TestCase):
    def setUp(self):
        self.app = app.app.test_client()

    def test_without_session(self):
        resp = self.app.get('/')
        self.assertEqual('without session', resp.data)

    def test_with_session(self):
        with self.app as c:
            with c.session_transaction() as sess:
                sess['logged'] = True
            resp = c.get('/')
        self.assertEqual('with session', resp.data)


if __name__ == '__main__':
    unittest.main()

我的app.py是这样的:

from flask import Flask, session


app = Flask(__name__)


@app.route('/')
def home():
    if 'logged' in session:
        return 'with session'
    return 'without session'


if __name__ == '__main__':
    app.run(debug=True)

当我运行测试时,我有这个错误:

ERROR: test_pippo_with_session (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_pippo.py", line 17, in test_pippo_with_session
    with c.session_transaction() as sess:
  File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/home/tommaso/repos/prova-flask/local/lib/python2.7/site-packages/flask/testing.py", line 74, in session_transaction
    raise RuntimeError('Session backend did not open a session. '
RuntimeError: Session backend did not open a session. Check the configuration

我在google上找不到任何解决方案。

1 个答案:

答案 0 :(得分:15)

如果您未设置自定义app.session_interface,则忘记设置secret key

def setUp(self):
    app.config['SECRET_KEY'] = 'sekrit!'
    self.app = app.app.test_client()

这只是为测试设置了一个模拟密钥,但是要使你的应用程序工作,你需要生成一个生产密钥,请参阅sessions section in the Quickstart documentation以获取有关如何生成一个好密钥的提示。 / p>

如果没有密钥,默认session implementation将无法创建会话。