Google App Engine: Webtest simulating logged in us

2019-04-09 17:00发布

from the webtest documentation I learn that:

The best way to simulate authentication is if your application looks in environ['REMOTE_USER'] to see if someone is authenticated. Then you can simply set that value, like:

app.get('/secret', extra_environ=dict(REMOTE_USER='bob'))

I am trying to do the same thing but in a Google App engine environment. I would like to simulate a logged in user and a user that's an administrator.

If possible which dictionary values do I have to set in extra_environ to accomplish this?

1条回答
冷血范
2楼-- · 2019-04-09 17:44

Set User:

os.environ['USER_EMAIL'] = 'info@example.com'

Set Admin:

os.environ['USER_IS_ADMIN'] = '1'

This is how my whole test looks like. My example uses webtest, nose, nosegae and gaetestbed.

class TestingRoutes(WebTestCase, unittest.TestCase):

    APPLICATION = application()

    def tearDown(self):
        os.environ['USER_EMAIL'] = ''
        os.environ['USER_IS_ADMIN'] = ''

    #AdminIndex .....
    def test_adminindex_no_user(self):
        #No user: redirect to login form
        response = app.get( url_map['adminindex'] )
        self.assertRedirects(response)

    def test_adminindex_user(self):      
        os.environ['USER_EMAIL'] = 'info@example.com'
        response = app.get( url_map['adminindex'] )
        self.assertForbidden(response)

    def test_adminindex_admin(self):
        os.environ['USER_EMAIL'] = 'info@example.com'
        os.environ['USER_IS_ADMIN'] = '1'
        response = app.get( url_map['adminindex'] )
        self.assertOK(response)

Hope it helps.

查看更多
登录 后发表回答