开发者

WebTest: Testing with decorators + datastore calls

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开发者_JS百科):
        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'] = 'info@example.com'
    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.


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

def user_ok(self):
    key_name = 'info@example.com'
    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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜