Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用补丁作为方法调用?_Python_Python 3.x_Unit Testing_Python Unittest - Fatal编程技术网

Python 如何使用补丁作为方法调用?

Python 如何使用补丁作为方法调用?,python,python-3.x,unit-testing,python-unittest,Python,Python 3.x,Unit Testing,Python Unittest,unittest文档说明: patch()充当函数修饰符、类修饰符或上下文 经理 我发现以下方法也允许通过方法调用进行修补。然后可以通过调用此方法修补某些内容。例如,这有助于修补设置方法中的某些内容: class MyTestCase(TestCase): def patch(self, target, new): p = patch(target, new) p.start() self.addCleanup(p.stop)

unittest
文档说明:

patch()
充当函数修饰符、类修饰符或上下文 经理

我发现以下方法也允许通过方法调用进行修补。然后可以通过调用此方法修补某些内容。例如,这有助于修补设置方法中的某些内容:

class MyTestCase(TestCase):

    def patch(self, target, new):
        p = patch(target, new)
        p.start()
        self.addCleanup(p.stop)

    # ...

    def setUp(self):
        self.a = Mock()
        self.patch("whatever.I.want.to.patch", self.a)

    def test(self):
        ...
        self.a.assert_called_once()

有没有更干净的方法?不提供这种开箱即用功能的原因是什么?

self提到了测试用例。在上面的示例中,我将一个mock设置为对象属性,然后使用该属性修补某些东西。模拟可以在测试用例/类中的任何地方使用)哦,对不起,是的,我错了。编辑,感谢您选择:)我想一个更好的标题可能是“为什么
patch
还不是
TestCase
上的方法?”因为您似乎知道当前标题的答案。但现实地说,这只能由少数人来回答(也许只有“我们没有想到它”)。