【问题标题】:Retrieve string for unit test检索字符串以进行单元测试
【发布时间】:2015-05-11 07:50:43
【问题描述】:

考虑这段代码:

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"))

【问题讨论】:

  • 我不确定您所说的“以某种方式引用”是什么意思,您能解释一下吗?另外,下划线有什么作用(是在别处定义的函数)?
  • 我稍微编辑了这个问题。 "_" 是标记要翻译的字符串的 babel 方式:babel.pocoo.org/docs/messages

标签: python unit-testing python-babel


【解决方案1】:

如果您使用的是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')

我们知道_here 调用ugettext,如果我们在前面删除import ipdb; ipdb.set_trace() 行,我们可以跳入python shell,调用get_some_text,然后使用this answer 来查找ugettext的导入路径,原来是gettext.ugettext

如果你只使用 babel,并且你知道你的翻译目录的路径,你也许可以 make your own translations 只是为了测试:

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')

【讨论】:

  • 自编写以来,_ 已被修改并调用flask_babel.gettext。现在你应该改用@mock.patch("flask_babel.gettext")
猜你喜欢
  • 1970-01-01
  • 2016-11-17
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
相关资源
最近更新 更多