使用 python mock 计算方法调用次数 [英] Using python mock to count number of method calls
问题描述
我刚刚开始使用 python 模拟框架.我只想计算一个方法被调用的次数,而不消除实际调用该方法的影响.
I'm just starting out using the python mocking framework. I'd like to just count the number of times a method gets called, without removing the effects of actually calling the method.
例如,在这个简单的计数器示例中,我想两者递增计数器并跟踪它被调用的情况:
For example, in this simple counter example, I would like to both increment the counter and track that it was called:
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
调用被模拟的方法,或者只是表示我想保留被模拟函数的效果?
Is it possible to force mock
to call the mocked method after it registered the call, or just signify that I want to keep the effects of the mocked function?
推荐答案
只需使用包装:
c = Counter()
with mock.patch.object(Counter, 'increment', wraps=c.increment) as fake_increment:
如果稍后初始化 c
,可能会出现一些绑定问题,因为传递给 wraps
的函数不会知道 self
.
There can be some binding problems if you initialize c
later, as the function passed to wraps
won't know about self
.
这篇关于使用 python mock 计算方法调用次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!