修补程序 - 修补类引入了一个额外的参数?

时间:2013-04-17 04:21:30

标签: python unit-testing mocking patch typeerror

第一次使用补丁。我试图修补我的一个类进行测试。没有试图运行的补丁超过了测试函数定义,但是使用补丁时,测试函数定义显然需要另一个参数,我得到了一个

TypeError: testAddChannelWithNamePutsChannel() takes exactly 1 argument (2 given)

错误。测试代码如下:

import unittest
import mock
from notification.models import Channel, addChannelWithName, deleteChannelWithName

class TestChannel(unittest.TestCase):
    @mock.patch('notification.models.Channel')
    def testAddChannelWithNamePutsChannel(self):
        addChannelWithName('channel1')
        Channel.put.assert_called_with()

为什么需要补丁的额外参数以及该参数应该是什么?非常感谢!

2 个答案:

答案 0 :(得分:38)

Patch将修补对象的实例传递给您的测试方法(如果您在类级别进行修补,则传递给每个测试方法)。这很方便,因为它可以让您设置返回值和副作用,或检查所做的调用

from unittest.mock import patch

@patch('some_module.sys.stdout')
def test_something_with_a_patch(self, mock_sys_stdout):
    mock_sys_stdout.return_value = 'My return value from stdout'

    my_function_under_test()

    self.assertTrue(mock_sys_stdout.called)
    self.assertEqual(output, mock_sys_stdout.return_value)

如果您只是想要修改某些内容以忽略它,那么您可以使用以下调用调用补丁

from unittest.mock import patch, Mock

@patch('some_module.sys.stdout', Mock())
def test_something_with_a_patch(self):

sys.stdout替换some_module中的Mock并且不将其传递给方法。

答案 1 :(得分:6)

patch将修补后的对象传递给测试函数。记录在案here

  

补丁作为函数装饰器,为您创建模拟并传递它   进入装饰功能:

>>>
>>> @patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
...     print(mock_class is SomeClass)
...
>>> function(None)
True
相关问题