Simple function test of session value failing

43 views Asked by At

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.

1

There are 1 answers

2
chepner On

Your test tries to access session[CURR_USER_KEY] twice: once in do_login, and once in the call to self.assertEqual. If the key doesn't exist, then do_login is raising the exception.

If that's the expected behavior, you should use self.assertRaises to execute the function so that you can test that KeyError really is raised.

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:
                with self.assertRaises(KeyError):
                    do_login(self.testuser)

If that's not the expected behavior, and do_login is supposed to add an entry to the session so that

self.assertEqual(session[CURR_USER_KEY], self.testuser.id)

will succeed, then you have discovered a bug in do_login that needs to be fixed.