- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
<分区>
我正在尝试在单元测试中修补现有类中的单个方法。要修补的类是:
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
有副作用的函数吗?
让我们写一个简单的类在我的脑海中解释: class SomeClass { var happyToUsed = 10 } 并创建一个对象 let someObject = SomeClass(
采用 self 的方法与采用 &self 甚至 &mut self 的方法有什么区别? 例如 impl SomeStruct { fn example1(self) { } fn ex
请观察以下代码(Win10上的python 3.6,PyCharm),函数thread0(self)作为线程成功启动,但是 thread1(self)似乎与thread0(self)不同已设置。 se
backbone.js 开始于: //Establish the root object, `window` (`self`) in the browser, or `global` on the s
做的事: self = self.init; return self; 在 Objective-C 中具有相同的效果: self.init() 快速? 例如,在这种情况下: else if([form
我查看了关于堆栈溢出的一些关于使用[weak self]和[unowned self]的问题的评论。我需要确保我理解正确。 我正在使用最新的 Xcode - Xcode 13.4,最新的 macOS
我面临在以下模型类代码中的 self.init 调用或分配给 self 之前使用 self 的错误tableview单元格项目,它发生在我尝试获取表格单元格项目的文档ID之后。 应该做什么?请推荐。
晚上好。 我对在 Swift 中转义(异步)闭包有疑问,我想知道哪种方法是解决它的最佳方法。 有一个示例函数。 func exampleFunction() { functionWithEsca
我需要在内心深处保持坚强的自我。 我知道声明[weak self]就够了外封闭仅一次。 但是guard let self = self else { return }呢? ,是否也足以为外部闭包声明一
代码 use std::{ fs::self, io::self, }; fn rmdir(path: impl AsRef) -> io::Result { fs::remo
我检查了共享相同主题的问题,但没有一个解决我遇到的这种奇怪行为: 说我有一个简单的老学校struct : struct Person { var name: String var age:
我应该解释为什么我的问题不是重复的:TypeError: can only concatenate list (not “str”) to list ...所以它不是重复的,因为该帖子处理代码中出现的
我有一个 trait,它接受一个类型参数,我想说实现这个 trait 的对象也会符合这个类型参数(使用泛型,为了 Java 的兼容性) 以下代码: trait HandleOwner[SELF
这个问题在这里已经有了答案: Why would a JavaScript variable start with a dollar sign? [duplicate] (16 个答案) 关闭 8
我总是找到一些类似的代码newPromise.promiseDispatch.apply(newPromise, message),我不明白为什么不使用newPromise.promiseDispat
我看到类似的模式 def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... 非
mysql查询示例: SELECT a1.* FROM agreement a1 LEFT JOIN agreement a2 on a1.agreementType = a2.agreementTy
self.delegate = self; 这样做有什么问题吗?正确的做法是什么? 谢谢,尼尔。 代码: (UITextField*)initWith:(id)sender:(float)X:(flo
为什么要声明self在类中需要的结构中不需要?我不知道是否还有其他例子说明了这种情况,但在转义闭包的情况下,确实如此。如果闭包是非可选的(因此是非转义的),则不需要声明 self在两者中的任何一个。
这个问题已经有答案了: What does the ampersand (&) before `self` mean in Rust? (1 个回答) 已关闭去年。 我不清楚 self 之间有什么区别
我是一名优秀的程序员,十分优秀!