gpt4 book ai didi

python - 关闭单元测试的翻译

转载 作者:太空宇宙 更新时间:2023-11-04 05:50:29 25 4
gpt4 key购买 nike

我有一些 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com