【问题标题】:Python: decorator for mocking gettext during testingPython:在测试期间模拟 gettext 的装饰器
【发布时间】:2022-06-14 14:48:23
【问题描述】:

我正在编写一个 Django 应用程序,我想编写一个装饰器,在测试期间模拟 _() 函数,只需在要翻译的字符串后添加“_translated”

我基本上让我的装饰器在我的测试中替换以下指令:

with mock.patch('module_which_is_being_tested._', lambda s: s+'_translated'):

【问题讨论】:

    标签: python unit-testing testing decorator python-decorators


    【解决方案1】:

    我没有在网上找到类似的东西,所以我分享它:

    from unittest import mock
    import functools
    
    def mock_translation(tested_object):
        """
        A decorator that mock the '_()' function during testing
        just adds '_translated' after the string to translate
    
        the class/function being tested needs to be passed as parameter
    
        Use: 
        from my_module.sub_module import my_function_to_be_tested
    
        @mock_translation(my_function_to_be_tested)
        def test_my_function_to_be_tested():
            pass
        """
     
        def actual_decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                module_name = tested_object.__module__
                tested_obj = tested_object
                breakpoint()
                import_path = module_name + '._'
                # with mock.patch('battletech.models._', lambda s: s+'_translated'):
                with mock.patch(import_path, lambda s: s+'_translated'):
                    value = func(*args, **kwargs)
                    return value
            return wrapper
        return actual_decorator
    

    【讨论】:

      猜你喜欢
      • 2012-11-01
      • 2016-08-20
      • 1970-01-01
      • 2013-03-19
      • 2021-06-04
      • 2011-02-13
      • 2017-08-20
      • 2021-12-23
      • 2018-06-05
      相关资源
      最近更新 更多