2

考虑这段代码:

def get_some_text():
    return _(u"We need this text here")

编写单元测试以确保函数返回 this - 由 Babel 引用和翻译 - 字符串的最佳方法是什么?

这个幼稚的代码不会包含引用——所以这实际上是一个不同的“Babel 字符串”:

def test_get_some_text(self):
    self.assertEqual(get_some_text(), _(u"We need this text here"))
4

1 回答 1

2

如果您使用的是flask-babel,请不要介意使用模拟,并且您只是在测试_返回的内容(即get_some_text不对 的结果进行任何额外的转换),那么您可以模拟并测试_返回值_你得到你所期望的:

import mock


@mock.patch('gettext.ugettext')
def test_get_some_text(self, mock_ugettext):
  mock_ugettext.return_value = u'Hello World'

  self.assertEqual(get_some_text(), u'Hello World')

我们知道从这里_调用,如果我们在之前删除一行,我们可以跳到一个 python shell,调用,并使用这个答案找到 的导入路径,结果是。ugettextimport ipdb; ipdb.set_trace()get_some_textugettextgettext.ugettext

如果你只使用 babel,并且你知道你的翻译目录的路径,你也许可以制作你自己的翻译只是为了测试:

import os
import shutil

import polib    


os_locale = ''
translations_directory = '/absolute/path/to/your/translations'
# choose a locale that isn't already in translations_directory
test_locale = 'en_GB'

def setUp(self):
    mo_file_path = os.path.join(
        translations_directory,
        test_locale,
        'LC_MESSAGES',
        'messages.mo'
    )
    mo = polib.MOFile()
    entry = polib.MOEntry(
        msgid=u'We need this text here',
        msgstr='My favourite colour is grey'
    )
    mo.append(entry)
    mo.save(mo_file_path)

    # modify our locale for the duration of this test
    os_locale = os.environ.pop('LANG', 'en')
    os.environ['LANG'] = test_locale

def tearDown(self):
    # restore our locale
    os.environ['LANG'] = os_locale
    shutil.rmtree(os.path.join(translations_directory, test_locale))

def test_get_some_text(self):
    self.assertEqual(get_some_text(), u'My favourite colour is grey')
于 2015-08-01T21:05:07.327 回答