I am testing a Flask application (Flask 0.9), and in particular I have a session fixture that I would like to run in the documented-way, being something like this (as I understand it):
from flask import Flask, session
app = Flask(__name__)
@app.route('/', methods=['POST'])
def m():
logging.error(session) # expect {'x': 1}
return ""
with app.test_request_context() as trc:
with app.test_client() as c:
with c.session_transaction() as sess:
sess['x'] = 1
c.post()
This works as expected, with the output being something like this:
ERROR:root:<SecureCookieSession {'x': 1}>
Unfortunately I am encountering an unexpected result where the session data is not set in the endpoint function, i.e. the output is something like this:
ERROR:root:<SecureCookieSession {}>
This issue exhibits only when run from my unit testing framework. As it stands, I am unable to reproduce this problem with a degenerate case, though I have made a fairly substantial effort with a gist of some of this effort here. The salient points being that I have included itsdangerous
and Google App Engine testbed
, expecting maybe one of them to have been the cause.
On my own system I have gone further than the gist, and almost completely replicated my unit test framework trying to isolate this. Likewise, I have removed ever-increasing amounts of relevant code from my testing framework. To the point, I am unable to think of differences between the degenerate case and my stripped-down framework that could influence the outcome. I have traversed the c.post()
call in pdb to try eek out the cause of this malignity, but have yet to glean any useful insight.
Which is all to say, I would be grateful for a little direction or suggestion as to where the issue may lie. What could possibly be influencing the Werkzeug context in such a way that the session_transaction
is not being honoured?
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.
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