python - 关闭单元测试的翻译

标签 python pylons python-unittest

我有一些 python 代码,比如

from pylons.i18n.translation import _

def get_message():
     message = _(u"Translated message")
     # interesting code to test
     # [...]
     return 'result'

我想像这样进行单元测试:

class MyTest(TestCase):
    def test_get_message(self):
        assertTrue(get_message(), 'result')

现在在 nosetests 中运行这个测试给我:

TypeError: No object (name: translator) has been registered for this thread

有没有办法在单元测试时停用与翻译相关的任何内容?

最佳答案

假设您的生产代码在 my_module.py 中:

from unittest import TestCase
from mock import patch
from my_module import get_message


class MyTest(TestCase):
    def test_get_message(self):
        with patch("my_module._"):
            result = get_message()
            self.assertEqual("result", result)

使用补丁,您的测试将_() 函数更改为MagicMock() 对象。文档 here .

注意 mock 是 Python 3.3 及更高版本标准库的一部分。否则,您应该首先使用 pip install mock 安装它。

关于python - 关闭单元测试的翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30507695/

相关文章:

python - 在Python中向图像添加对齐文本

python - 如何将此代理切换为使用代理身份验证?

python - 如何在 matplotlib 中将散点大小转换为数据坐标?

python - 我可以将什么附加到 Pylons 中的 pylons.request 上?

python - 在 Pylons : app_globals? 线程安全中设置 MySQLdb 连接的正确位置?

python - numpy 测试断言数组不等于

python - 以不同顺序对多个列上的结构化 Numpy 数组进行排序

error-handling - 处理 Pylons 中的非致命异常

python-2.7 - Python 模拟 Autospec 与 Spec

python - 使unittest.mock.Mock()返回字典列表