13

I'm using the GAE testbed service and when I run users.get_current_user() I get None i.e.

>>> import sys
>>> sys.path.append("/usr/local/google_appengine") # for Mac OS X
>>> from google.appengine.api import users
>>> from google.appengine.ext import testbed
>>> testbed = testbed.Testbed()
>>> testbed.activate()
>>> testbed.init_user_stub()
>>> users.get_current_user() == None
True

This is the expected result. However, I'd like to log in a fake user when running some of my unit tests.

If it's possible (and I expect it would be), how can one log a user in when running testbed from the command line so that get_current_user() returns an actual user?

Thanks for reading.

Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343

2 Answers2

18

To simulate a sign in of an admin user, you can call anywhere in your test function:

self.testbed.setup_env(
    USER_EMAIL = 'test@example.com',
    USER_ID = '123',
    USER_IS_ADMIN = '1',
    overwrite = True)

Note that you need to use the overwrite=True parameter!

psmith
  • 2,292
  • 1
  • 19
  • 19
3

After some experimentation the following worked for me:

>>> os.environ['USER_EMAIL'] = 'a@b.c'
>>> os.environ['USER_ID'] = '123'
>>> users.get_current_user()
users.User(email='a@b.c',_user_id='123')

I hope this is a good solution, and this answer helps the next person to run into this issue.

EDIT: Related variables

To avoid /google/appengine/api/users.py:115 - AssertionError: assert _auth_domain

>>> os.environ['AUTH_DOMAIN'] = 'testbed'

Per Elliot de Vries comment, for an administrative user:

>>> os.environ['USER_IS_ADMIN'] = '1'
Community
  • 1
  • 1
Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343
  • 2
    Another useful one: os.environ['USER_IS_ADMIN'] = '1' –  Jun 03 '11 at 16:44
  • 2
    Thanks for this. Do you have any recommendations for examples of unit tests? I find the docs at: http://code.google.com/appengine/docs/python/tools/localunittesting.html a bit lacking – pheelicks Jun 05 '11 at 04:25
  • 5
    this is basically the right idea. except that you want to use [`testbed.setup_env()`](http://code.google.com/appengine/docs/python/tools/localunittesting.html#Changing_the_Default_Environment_Variables) instead of `os.environ` directly. – ryan Jul 26 '11 at 15:28