Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test session in flask resource

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.

like image 210
allevo Avatar asked Jan 31 '14 17:01

allevo


1 Answers

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.

like image 119
Martijn Pieters Avatar answered Sep 18 '22 14:09

Martijn Pieters