views:

49

answers:

1

Hello,

I have a Google App Engine application and my request hadnler has a decorator that does authentication. With WebTest I found out yesterday how you can set a logged in user and administrator.

Now today my authentication decorator got a little more complex. It's also checking if a user has a profile in the database and if he doesn't he'll get redirected to the 'new user' page.

def authenticated(method):
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return

        profile = Profile.get_by_key_name(str(user.user_id))
        if not profile:
            self.redirect( '/newuser' )

        return method(self, *args, **kwargs)

    return wrapper

Now adding the profile part breaks my unit test that checks if a user is logged in and gets a status code 200(assertOK).

def user_ok(self):
    os.environ['USER_EMAIL'] = '[email protected]'
    os.environ['USER_IS_ADMIN'] = ''
    response = self.get( '/appindex' )
    self.assertOK(response)

So now I need to be able to somehow inject the profile functionality into the decorator so I can set it in my tests. Does anybody got an idea how to do this I've been trying to think of a way but I keep getting stuck.

+2  A: 

You should create a profile during the test, to be used by the decorator:

def user_ok(self):
    key_name = '[email protected]'
    new_user = Profile(key_name=key_name)
    new_user.put()

    os.environ['USER_EMAIL'] = key_name
    os.environ['USER_ID'] = key_name
    os.environ['USER_IS_ADMIN'] = ''
    response = self.get( '/appindex' )
    self.assertOK(response)

    # Now let's reset it to check that the user will be redirected.
    new_user.delete()
    response = self.get( '/appindex' )
    self.assertEqual(response.headers['Location'], 'http://localhost/newuser')
moraes
Seems I am over thinking it a little. I am mostly used to Asp.net Mvc and there you decouple everything so it can be tested. But I notice in GAE the tests are mostly integration tests.
Pickels