我想测试一个资源.其响应取决于会话中的参数(已记录)
为了测试这个资源,我写了这些测试:
为了测试这个资源,我写了这些测试:
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",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上找到任何解决方案.
解决方法
如果没有设置自定义的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获取有关如何生成良好密钥的提示.
没有密钥,默认session implementation无法创建会话.