How to improve readabilty and maintainability of @patch and MagicMock statements (avoid long names and String identification)?

huangapple go评论63阅读模式
英文:

How to improve readabilty and maintainability of @patch and MagicMock statements (avoid long names and String identification)?

问题

以下是翻译好的部分:

在我的测试代码中,我有很多样板表达式 "Magic"、"return_"。我还有长字符串用于标识要模拟的函数路径。在重构过程中,这些字符串不会自动替换,我更喜欢直接使用导入的函数。

示例代码:

from mock import patch, MagicMock
from pytest import raises

@patch(
    'foo.baa.qux.long_module_name.calculation.energy_intensity.intensity_table',
    MagicMock(return_value='mocked_result_table'),
)

而我更希望:

from better_test_module import patch, Mock, raises
from foo.baa.qux.long_module_name.calculation import energy_intensity

@patch(
    energy_intensity.intensity_table,
    Mock('mocked_result_table'),
)

或者

@patch(
    energy_intensity.intensity_table,
    'mocked_result_table',
)

如果您有其他建议,请告诉我。我想知道为什么建议的解决方案不是默认选项。我不想重复发明轮子。因此,如果已经存在可以使用的库,请告诉我。

相关链接:

https://stackoverflow.com/questions/17181687/mock-vs-magicmock

https://stackoverflow.com/questions/67580353/how-to-override-getitem-on-a-magicmock-subclass

英文:

In my test code I have a lot of boilerplate expressions "Magic", "return_". I also have lengthy strings to identify the paths of the functions to mock.
The strings are not automatically replaced during refactoring and I would prefer to directly use the imported functions.

Example code:

from mock import patch, MagicMock
from pytest import raises

@patch(
    'foo.baa.qux.long_module_name.calculation.energy_intensity.intensity_table',
    MagicMock(return_value='mocked_result_table'),
)

Instead I would prefer:

from better_test_module import patch, Mock, raises
from foo.baa.qux.long_module_name.calculation import energy_intensity

@patch(
    energy_intensity.intensity_table,
    Mock('mocked_result_table'),
)

or

@patch(
    energy_intensity.intensity_table,
    'mocked_result_table',
)

I post my corresponding custom implementation as an answer below.

If you have other suggestions, please let me know. I am wondering why the proposed solution is not the default. I do not want to reinvent the wheel.
Therefore, if there is an already existing library I could use, please let me know.

Related:

https://stackoverflow.com/questions/17181687/mock-vs-magicmock

https://stackoverflow.com/questions/67580353/how-to-override-getitem-on-a-magicmock-subclass

答案1

得分: 0

创建一个包装模块,允许使用更短的名称并直接传递函数。(如果类似的东西已经存在作为一个pip包,请告诉我;不想重复造轮子。)

用法:

from my_test_utils.mock import patch, Mock, raises    
from foo.baa.qux.long_module_name.calculation import energy_intensity

@patch(
    energy_intensity.intensity_table,
    Mock('mocked_result_table'),  
)

my_test_utils/mock.py 中的第一个草案代码:

from mock import MagicMock, DEFAULT
from mock import patch as original_patch
from pytest import raises as original_raises


class Mock(MagicMock):
    # 这个类用作MagicMock的包装器,允许使用更短的语法

    def __new__(cls, *args, **kwargs):
        if len(args) > 0:
            first_argument = args[0]
            mock = MagicMock(return_value=first_argument, *args[1:], **kwargs)
        else:
            mock = MagicMock(**kwargs)
        return mock

    def assert_called_once(self, *args, **kwargs):  # pylint: disable = useless-parent-delegation
        # pylint没有找到这个方法,除非定义为代理
        super().assert_called_once(*args, **kwargs)

    def assert_not_called(self, *args, **kwargs):  # pylint: disable = useless-parent-delegation
        # pylint没有找到这个方法,除非定义为代理
        super().assert_not_called(*args, **kwargs)


def patch(item_to_patch, *args, **kwargs):
    if isinstance(item_to_patch, str):
        raise KeyError('请直接导入并使用项目,而不是传递字符串路径!')

    module_path = item_to_patch.__module__
    if hasattr(item_to_patch, '__qualname__'):
        item_path = module_path + '.' + item_to_patch.__qualname__
    else:
        name = _try_to_get_object_name(item_to_patch, module_path)
        item_path = module_path + '.' + name

    item_path = item_path.lstrip('_')

    return original_patch(item_path, *args, **kwargs)


def _try_to_get_object_name(object_to_patch, module_path):
    module = __import__(module_path)
    name = None
    for attribute_name in dir(module):
        attribute = getattr(module, attribute_name)
        if attribute == object_to_patch:
            if name is None:
                name = attribute_name
            else:
                # 对象在其父对象内不是唯一的,但被使用了两次
                message = (
                    '无法识别要打补丁的项目,因为对象不是唯一的。'
                    + ' 请使用唯一的字符串路径。'
                )
                raise KeyError(message)
    if name is None:
        raise KeyError('无法识别要打补丁的对象。')
    return name


def raises(*args):
    # 这个函数用作raises的包装器,以便能够从与其他函数相同的模块导入它
    return original_raises(*args)

请注意:以上是您提供的代码的翻译。如果有任何其他问题或需要进一步的帮助,请随时告诉我。

英文:

Create a wrapper module allowing for shorter names and passing functions directly. (If something like this already exists as a pip package, please let me know; don't want to reinvent the wheel.)

Usage:

from my_test_utils.mock import patch, Mock, raises    
from foo.baa.qux.long_module_name.calculation import energy_intensity
@patch(
energy_intensity.intensity_table,
Mock('mocked_result_table'),  
)

First draft for my wrapping code in my_test_utils/mock.py:

from mock import MagicMock, DEFAULT
from mock import patch as original_patch
from pytest import raises as original_raises
class Mock(MagicMock):
# This class serves as a wrapper for MagicMock to allow for shorter syntax
def __new__(cls, *args, **kwargs):
if len(args) > 0:
first_argument = args[0]
mock = MagicMock(return_value=first_argument, *args[1:], **kwargs)
else:
mock = MagicMock(**kwargs)
return mock
def assert_called_once(self, *args, **kwargs):  # pylint: disable = useless-parent-delegation
# pylint did not find this method without defining it as a proxy
super().assert_called_once(*args, **kwargs)
def assert_not_called(self, *args, **kwargs):  # pylint: disable = useless-parent-delegation
# pylint did not find this method without defining it as a proxy
super().assert_not_called(*args, **kwargs)
def patch(item_to_patch, *args, **kwargs):
if isinstance(item_to_patch, str):
raise KeyError('Please import and use items directly instead of passing string paths!')
module_path = item_to_patch.__module__
if hasattr(item_to_patch, '__qualname__'):
item_path = module_path + '.' + item_to_patch.__qualname__
else:
name = _try_to_get_object_name(item_to_patch, module_path)
item_path = module_path + '.' + name
item_path = item_path.lstrip('_')
return original_patch(item_path, *args, **kwargs)
def _try_to_get_object_name(object_to_patch, module_path):
module = __import__(module_path)
name = None
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if attribute == object_to_patch:
if name is None:
name = attribute_name
else:
# object is not unique within its parent but used twice
message = (
'Could not identify item to patch because object is not unique.'
+ ' Please use a unique string path.'
)
raise KeyError(message)
if name is None:
raise KeyError('Could not identify object to patch.')
return name
def raises(*args):
# This function serves as a wrapper for raises to be able to import it from the same module as the other functions
return original_raises(*args)

huangapple
  • 本文由 发表于 2023年6月27日 20:27:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定