Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/67.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_Unit Testing_Mocking - Fatal编程技术网

使用python模拟计算方法调用的数量

使用python模拟计算方法调用的数量,python,unit-testing,mocking,Python,Unit Testing,Mocking,我刚刚开始使用python模拟框架。我只想计算一个方法被调用的次数,而不排除实际调用该方法的影响 例如,在这个简单的计数器示例中,我想同时增加计数器和它被调用的轨迹: import unittest import mock class Counter(object): def __init__(self): self.count = 0 def increment(self): self.count += 1 class CounterT

我刚刚开始使用python模拟框架。我只想计算一个方法被调用的次数,而不排除实际调用该方法的影响

例如,在这个简单的计数器示例中,我想同时增加计数器和它被调用的轨迹:

import unittest
import mock


class Counter(object):
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1


class CounterTest(unittest.TestCase):
    def test_increment(self):
        c = Counter()
        c.increment()
        self.assertEquals(1, c.count)

    def test_call_count(self):

        with mock.patch.object(Counter, 'increment') as fake_increment:
            c = Counter()
            self.assertEquals(0, fake_increment.call_count)
            c.increment()
            self.assertEquals(1, fake_increment.call_count)

            # increment() didn't actually get called.
            self.assertEquals(1, c.count)  # Fails.

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

是否可以在注册调用后强制
mock
调用mocked方法,或者只是表示我想保留mocked函数的效果?

我在mock1方面没有太多经验,但我是通过使用函数包装器而不是默认的
MagicMock
来完成的:

class FuncWrapper(object):
    def __init__(self, func):
        self.call_count = 0
        self.func = func

    def __call__(self, *args, **kwargs):
        self.call_count += 1
        return self.func(*args, **kwargs)

class CounterTest(unittest.TestCase):
    def test_call_count(self):

        c = Counter()
        new_call = FuncWrapper(c.increment)
        with mock.patch.object(c, 'increment', new=new_call) as fake_increment:
            print fake_increment
            self.assertEquals(0, fake_increment.call_count)
            c.increment()
            self.assertEquals(1, fake_increment.call_count)

            self.assertEquals(1, c.count)  # Fails.
当然,这个
FuncWrapper
非常小。它只是对调用进行计数,然后将流控制委托回原始函数。如果需要同时测试其他内容,则需要添加到
FuncWrapper
类中。我还刚刚修补了一个类实例,而不是整个类。主要原因是我需要
FuncWrapper
中的实例方法

事实上,我刚刚开始学习——考虑自己的警告;-)p> 只需使用包装:

c = Counter()
with mock.patch.object(Counter, 'increment', wraps=c.increment) as fake_increment:
如果稍后初始化
c
,可能会出现一些绑定问题,因为传递给
wrapps
的函数不知道
self