Didn't put in enough information the first time. Trying this again. I have the following function:
def do_login(user):
"""Log in user."""
session["curr_user"] = user.id
It, along with this function,
@app.before_request
def add_user_to_g():
"""If we're logged in, add curr user to Flask global."""
if "curr_user" in session:
# updating to more current syntax
g.user = db.session.query(User).get(session["curr_user"])
else:
g.user = None
is the method I'm using to keep users logged in in my flask app. It puts the users ID number in the browser session from which it can be added to flask's global object. I know the functions work because uses can perform tasks requiring authentication on the front end. It's definitely functioning correctly.
However,the following test:
class UserViewTestCase(TestCase):
"""Test views for users."""
def setUp(self):
"""Create test client, add sample data."""
User.query.delete()
Message.query.delete()
self.client = app.test_client()
self.testuser = User.signup(username="testuser",
email="[email protected]",
password="testuser",
image_url=None,
header_image_url=None,
bio=None,
location=None)
self.testuser2 = User.signup(username='testuser2',
email='[email protected]',
password='testuser',
image_url=None,
header_image_url=None,
bio=None,
location=None)
db.session.commit()
self.msg1 = Message(text="testing 1", user_id = self.testuser.id)
self.msg2 = Message(text="testing 2", user_id = self.testuser2.id)
db.session.add_all([self.msg1, self.msg2])
db.session.commit()
self.testuser.following.append(self.testuser2)
db.session.add(self.testuser)
db.session.commit()
def test_do_login(self):
"""Does do_login function work?"""
with app.test_request_context():
with self.client as c:
with c.session_transaction() as session:
do_login(self.testuser)
self.assertEqual(session["curr_user"], self.testuser.id)
is throwing a KeyError failure. I know that that means there is no value for curr_user in the browser session, but I don't understand why the test isn't working when the actual site works fine. I assume I've done something wrong in my test having to do with the session, but I can't figure out what.
Your test tries to access
session[CURR_USER_KEY]twice: once indo_login, and once in the call toself.assertEqual. If the key doesn't exist, thendo_loginis raising the exception.If that's the expected behavior, you should use
self.assertRaisesto execute the function so that you can test thatKeyErrorreally is raised.If that's not the expected behavior, and
do_loginis supposed to add an entry to the session so thatwill succeed, then you have discovered a bug in
do_loginthat needs to be fixed.