I'd like to test a resource. The response of that depends on a parameter in session (logged) To test this resource, I've wrote those tests:
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()
My app.py is this:
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)
When i run the tests I have this error:
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
I haven't found any solution on google.
If you did not set a custom app.session_interface, then you forgot to set a secret key:
def setUp(self):
    app.config['SECRET_KEY'] = 'sekrit!'
    self.app = app.app.test_client()
This just sets a mock secret key for the tests, but for your application to work you'll need to generate a production secret key, see the sessions section in the Quickstart documentation for tips on how to produce a good secret key.
Without a secret key, the default session implementation fails to create a session.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With