使用python模拟计算方法调用的数量
我刚刚开始使用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
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