Search code examples
pythonunit-testingtestingdecoratorpython-decorators

Python: decorator for mocking gettext during testing


I'm writing a Django app, and I wanted to write a decorator that will mock the _() function during testing, just adding '_translated' after the string to translate

I basically have my decorator to replace the following instruction within my test:

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

Solution

  • I didn't find anything similar on the web, so I'm sharing it:

    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