Unit test a Flask session - cannot reproduce failure with session_transaction Unit test a Flask session - cannot reproduce failure with session_transaction flask flask

Unit test a Flask session - cannot reproduce failure with session_transaction


In my case, I was restricting cookies to a specific domain automatically by loading a configuration file. By updating the configuration on-the-fly, I was able to get cookies to work while unit testing. Setting the SESSION_COOKIE_DOMAIN property to None, all domains (namely localhost) were able to set sessions.

app.config.update(                                                         SESSION_COOKIE_DOMAIN = None                                                )

You may want to fiddle around with the configuration settings described under Configuration Handling in the docs.


I hate to resurrect an old question, but I believe that I figured out the solution to this issue. For testing, try setting your server name to localhost:

app.config['SERVER_NAME'] = 'localhost'

I was originally using Brian's hack, but this solved the problem for me.


Without a testcase that actually fails it's hard to say much anything. All I can think of is that the TestClient instance you're using the make the request is different from the one you use to set up the session. E.g. you could make the gist fail as expected with this:

with self.app.test_client() as c:    with c.session_transaction() as sess:        sess['d'] = 1    self.client.post()

But as this isn't the case here or the gist, go figure.