Skip to content
This repository has been archived by the owner on Jun 26, 2020. It is now read-only.

Commit

Permalink
Add a gettextutils.install() helper function
Browse files Browse the repository at this point in the history
Part of fixing bug #995287

Every top-level script in every project needs to call gettext.install()
so that a _() builtin function is installed and strings are translated
using the correct translation domain.

However, translations are always installed in the default localedir
(which is commonly '/usr/share/locale') and, in cases like devstack, may
be found in a project-specific localedir. To support such a use case we
should have project-specific environment variables for overriding the
default value of localedir - e.g. NOVA_LOCALEDIR.

Add a new gettextutils.install() helper method to make this as easy as
possible for projects to get right.

Change-Id: I6c8549c8ff00797c96f2dd4b0b5266d18d77aa19
  • Loading branch information
markmc committed Apr 3, 2013
1 parent 05219b8 commit d8b66c7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
17 changes: 17 additions & 0 deletions openstack/common/gettextutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,27 @@
"""

import gettext
import os


t = gettext.translation('oslo', 'locale', fallback=True)


def _(msg):
return t.ugettext(msg)


def install(domain):
"""Install a _() function using the given translation domain.
Given a translation domain, install a _() function using gettext's
install() function.
The main difference from gettext.install() is that we allow
overriding the default localedir (e.g. /usr/share/locale) using
a translation-domain-specific environment variable (e.g.
NOVA_LOCALEDIR).
"""
gettext.install(domain,
localedir=os.environ.get(domain.upper() + '_LOCALEDIR'),
unicode=True)
18 changes: 16 additions & 2 deletions tests/unit/test_gettext.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

import logging

from openstack.common.gettextutils import _
import mock

from openstack.common import gettextutils
from tests import utils


Expand All @@ -27,4 +29,16 @@
class GettextTest(utils.BaseTestCase):

def test_gettext_does_not_blow_up(self):
LOG.info(_('test'))
LOG.info(gettextutils._('test'))

def test_gettext_install_looks_up_localedir(self):
with mock.patch('os.environ.get') as environ_get:
with mock.patch('gettext.install') as gettext_install:
environ_get.return_value = '/foo/bar'

gettextutils.install('blaa')

environ_get.assert_called_once_with('BLAA_LOCALEDIR')
gettext_install.assert_called_once_with('blaa',
localedir='/foo/bar',
unicode=True)

0 comments on commit d8b66c7

Please sign in to comment.