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):
        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.

1
задан Community 23 May 2017 в 12:18
поделиться

1 ответ

Вы должны создать профиль во время теста, который будет использоваться декоратором:

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')
2
ответ дан 2 September 2019 в 21:44
поделиться
Другие вопросы по тегам:

Похожие вопросы: