gpt4 book ai didi

python - 模拟类方法并将 self 参数传递给 Mock 的副作用

转载 作者:行者123 更新时间:2023-12-04 15:24:57 25 4
gpt4 key购买 nike

<分区>

我正在尝试在单元测试中修补现有类中的单个方法。要修补的类是:

class Example:
def __init__(self: "Example", id: int) -> None:
self.id : int = id
self._loaded : bool = False
self._data : typing.Union[str,None] = None

def data(self: "Example") -> str:
if not self._loaded:
self.load()
return self._data

def load(self: "Example") -> None:
self._loaded = True
# some expensive computations
self._data = f"real_data{self.id}"

因此,不是调用 self.load(),而是使用 mocked_load 函数调用 unittest.mock.Mock(如下)作为副作用:

def mocked_load(self: "Example") -> None:
# mock the side effects of load without the expensive computation.
self._loaded = True
self._data = f"test_data{self.id}"

第一次尝试是:

@unittest.mock.patch.object(Example, "load", new = mocked_load)
def test_data__patch_new(
self: "TestExample",
) -> None:
example1 = Example(id=1)
example2 = Example(id=2)

data1_1 = example1.data()
self.assertEqual(data1_1, "test_data1")

data2_1 = example2.data()
self.assertEqual(data2_1, "test_data2")

data1_2 = example1.data()
self.assertEqual(data1_2, "test_data1")

data2_2 = example2.data()
self.assertEqual(data2_2, "test_data2")

这行得通,但只是将 Example.load 函数替换为 mocked_load 函数,而不是将其包装在 Mock 中;因此,尽管它确实通过了,但您无法扩展测试来断言修补后的 Example.load 方法被调用了多少次。这不是我正在寻找的解决方案。

第二次尝试是:

@unittest.mock.patch.object(Example, "load")
def test_data__patch_side_effect(
self: "TestExample",
patched_load: unittest.mock.Mock
) -> None:
patched_load.side_effect = mocked_load

example1 = Example(id=1)
example2 = Example(id=2)

self.assertEqual(patched_load.call_count, 0)

data1_1 = example1.data()
self.assertEqual(data1_1, "test_data1")
self.assertEqual(patched_load.call_count, 1)

data2_1 = example2.data()
self.assertEqual(data2_1, "test_data2")
self.assertEqual(patched_load.call_count, 2)

data1_2 = example1.data()
self.assertEqual(data1_2, "test_data1")
self.assertEqual(patched_load.call_count, 2)

data2_2 = example2.data()
self.assertEqual(data2_2, "test_data2")
self.assertEqual(patched_load.call_count, 2)

失败,异常:

Traceback (most recent call last):
File "/usr/lib/python3.8/unittest/mock.py", line 1325, in patched
return func(*newargs, **newkeywargs)
File "my_file.py", line 65, in test_data__patch_side_effect
data1_1 = example1.data()
File "my_file.py", line 13, in data
self.load()
File "/usr/lib/python3.8/unittest/mock.py", line 1081, in __call__
return self._mock_call(*args, **kwargs)
File "/usr/lib/python3.8/unittest/mock.py", line 1085, in _mock_call
return self._execute_mock_call(*args, **kwargs)
File "/usr/lib/python3.8/unittest/mock.py", line 1146, in _execute_mock_call
result = effect(*args, **kwargs)
TypeError: mocked_load() missing 1 required positional argument: 'self'

最后的尝试是:

@unittest.mock.patch.object(Example, "load")
def test_data__patch_multiple_side_effect(
self: "TestExample",
patched_load: unittest.mock.Mock
) -> None:
example1 = Example(id=1)
example2 = Example(id=2)

side_effect1 = lambda: mocked_load( example1 )
side_effect2 = lambda: mocked_load( example2 )

patched_load.side_effect = side_effect1

self.assertEqual(patched_load.call_count, 0)

data1_1 = example1.data()
self.assertEqual(data1_1, "test_data1")
self.assertEqual(patched_load.call_count, 1)

patched_load.side_effect = side_effect2

data2_1 = example2.data()
self.assertEqual(data2_1, "test_data2")
self.assertEqual(patched_load.call_count, 2)

patched_load.side_effect = side_effect1

data1_2 = example1.data()
self.assertEqual(data1_2, "test_data1")
self.assertEqual(patched_load.call_count, 2)

patched_load.side_effect = side_effect2

data2_2 = example2.data()
self.assertEqual(data2_2, "test_data2")
self.assertEqual(patched_load.call_count, 2)

这“有效”,但它非常脆弱,因为 self 参数被硬编码到 lambda 函数中,并且需要交换 mock 的 side_effect匹配每个调用。

完整的最小代表性示例是:

import typing
import unittest
import unittest.mock

class Example:
def __init__(self: "Example", id: int) -> None:
self.id : int = id
self._loaded : bool = False
self._data : typing.Union[str,None] = None

def data(self: "Example") -> str:
if not self._loaded:
self.load()
return self._data

def load(self: "Example") -> None:
self._loaded = True
# some expensive computations
self._data = f"real_data{self.id}"

def mocked_load(self: "Example") -> None:
# mock the side effects of load without the expensive computation.
self._loaded = True
self._data = f"test_data{self.id}"

class TestExample( unittest.TestCase ):
@unittest.mock.patch.object(Example, "load", new = mocked_load)
def test_data__patch_new(
self: "TestExample",
) -> None:
# This works but just replaces the Example.load function with another
# rather than wrapping it in a Mock; so you cannot assert how many
# times the patched method was called.

example1 = Example(id=1)
example2 = Example(id=2)

data1_1 = example1.data()
self.assertEqual(data1_1, "test_data1")

data2_1 = example2.data()
self.assertEqual(data2_1, "test_data2")

data1_2 = example1.data()
self.assertEqual(data1_2, "test_data1")

data2_2 = example2.data()
self.assertEqual(data2_2, "test_data2")

@unittest.mock.patch.object(Example, "load")
def test_data__patch_side_effect(
self: "TestExample",
patched_load: unittest.mock.Mock
) -> None:
# This fails as the self argument is not passed to the side_effect
# function.

patched_load.side_effect = mocked_load

example1 = Example(id=1)
example2 = Example(id=2)

self.assertEqual(patched_load.call_count, 0)

data1_1 = example1.data()
self.assertEqual(data1_1, "test_data1")
self.assertEqual(patched_load.call_count, 1)

data2_1 = example2.data()
self.assertEqual(data2_1, "test_data2")
self.assertEqual(patched_load.call_count, 2)

data1_2 = example1.data()
self.assertEqual(data1_2, "test_data1")
self.assertEqual(patched_load.call_count, 2)

data2_2 = example2.data()
self.assertEqual(data2_2, "test_data2")
self.assertEqual(patched_load.call_count, 2)

@unittest.mock.patch.object(Example, "load")
def test_data__patch_multiple_side_effect(
self: "TestExample",
patched_load: unittest.mock.Mock
) -> None:
# This passes but feels (very) wrong as you have to have change the
# side_effect each time you call the function and relies on hardcoding
# the class instances being passed as "self".

example1 = Example(id=1)
example2 = Example(id=2)

side_effect1 = lambda: mocked_load( example1 )
side_effect2 = lambda: mocked_load( example2 )

patched_load.side_effect = side_effect1

self.assertEqual(patched_load.call_count, 0)

data1_1 = example1.data()
self.assertEqual(data1_1, "test_data1")
self.assertEqual(patched_load.call_count, 1)

patched_load.side_effect = side_effect2

data2_1 = example2.data()
self.assertEqual(data2_1, "test_data2")
self.assertEqual(patched_load.call_count, 2)

patched_load.side_effect = side_effect1

data1_2 = example1.data()
self.assertEqual(data1_2, "test_data1")
self.assertEqual(patched_load.call_count, 2)

patched_load.side_effect = side_effect2

data2_2 = example2.data()
self.assertEqual(data2_2, "test_data2")
self.assertEqual(patched_load.call_count, 2)


if __name__ == '__main__':
unittest.main()

我如何“修复”我的第二次尝试(或提供替代方法)以使用 Mock 修补 Example.load 函数,以便 side_effect 可以调用对 self 有副作用的函数吗?

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