Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing webapp2 RequestHandler that requires sessions

On some of my RequestHandler views, I get information from a session to make sure the user is currently logged in (custom auth)

I am having trouble mocking this for unit tests.

helper method in my RequestHandler class:

@webapp2.cached_property
def get_account(self):
    user_session = self.session.get('user-id')
    if user_session:
        user_account = helpers.get_username_data_from_session(self.session.get('user-id'))
        return user_account

In an implemented (what I want to test) view a get method could look like this (example):

def get(self):
    account = self.get_account
    if not account:
        self.error(302)

I have not been able to find a way to mock this for testing get/post methods for a RequestHandler class.

Any help would be awesome!

like image 605
Richard Avatar asked Feb 20 '26 17:02

Richard


1 Answers

Snippet as from http://www.recursion.org/2011/10/12/testing-webapp2-sessions-with-webtest

import webtest
import webapp2 as webapp
from webapp2_extras import sessions
from webapp2_extras.securecookie import SecureCookieSerializer

SUPER_SECRET = 'my-super-secret'

app = webapp.WSGIApplication(config={
    'webapp2_extras.sessions': {
        'secret_key': SUPER_SECRET
    },
})

class SomeTestCase(unittest.TestCase):

    def setUp(self):

        self.app = webtest.TestApp(app)
        self.testbed = testbed.Testbed()
        self.testbed.activate()

    def tearDown(self):
        self.testbed.deactivate()

    def test_get_index(self):
        session = {'key': 'value'}
        secure_cookie_serializer = SecureCookieSerializer(
            SUPER_SECRET
        )
        serialized = secure_cookie_serializer.serialize(
            'session', session
        )
        headers = {'Cookie': 'session=%s' % serialized}

        response = self.app.get('/', headers=headers)

        assert response.status_int == 200
like image 56
Mitchel Kelonye Avatar answered Feb 22 '26 05:02

Mitchel Kelonye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!