繁体   English   中英

使用python mock来计算方法调用的数量

[英]Using python mock to count number of method calls

我刚刚开始使用python mocking框架。 我想计算方法被调用的次数,而不去除实际调用方法的影响。

例如,在这个简单的反例,我想增加计数器和跟踪,它被称为:

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在注册调用后调用mock方法,或者只是表示我想保留mock函数的效果?

只需使用包装:

c = Counter()
with mock.patch.object(Counter, 'increment', wraps=c.increment) as fake_increment:

如果稍后初始化c ,可能会出现一些绑定问题,因为传递给wraps的函数不会知道self

我在模拟1中没有超级经验,但是我通过使用函数包装器而不是默认的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需要一个实例方法。

1事实上,我刚开始学习 - 考虑自己警告;-)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM