Search code examples
unit-testinggoogle-app-engineinternationalizationwebapp2

Using webapp2 i18n in unit tests


I'm using webapp2 with webapp2_extras.i18n for a Google App Engine app.

I have a unit test script as described on the bottom here: https://developers.google.com/appengine/docs/python/tools/localunittesting

The test script imports the models and does not include webapp2 handlers, because the target of the test is the business logic code, not the requests and responses. However, some of my models will call i18n functions like format_currency or gettext which will result in an error:

AssertionError: Request global variable is not set.

How can I initialize the i18n module without instantiating a webapp2 app and request?


Solution

  • Try to mock your functions.

    Example: I have a script called users that import i18n like this:

    from webapp2_extras.i18n import gettext as _
    

    So on my tests i mock the function like this:

    from pswdless.model import PswdUserEmail, EmailUserArc
    from pswdless.users import FindOrCreateUser
    from pswdless import users
    
    # mocking i18n
    users._ = lambda s: s
    
    #your tests bellow
    

    You can use same trick with another functions.

    I hope it helps you.