简单的chain stub,简单chainstub,常用doctest,但是


常用doctest,但是有时候还是需要点stub的辅助,所以写了个可以chain的stub,满足我当前的需求。

#encoding:utf8class Stub(object):    """    >>> s = Stub()    >>> s.foo = 1    >>> s.foo    1    >>> s = Stub()    >>> s.foo.bar=2    >>> s.foo.bar    2    >>> s = Stub()    >>> s.foo = lambda :3    >>> s.foo()    3    >>> s = Stub()    >>> s.foo().bar=4    >>> s.foo().bar    4    >>> s = Stub()    >>> s.foo().gee(123).bar=5    >>> s.foo().gee(123).bar    5    >>> s = Stub()    >>> s.foo.gee = lambda : 6    >>> s.foo.gee()    6    >>> s = Stub()    >>> s.foo.gee().bar = 7    >>> s.foo.gee().bar    7    >>> s = Stub()    >>> s._called_count    0    >>> t = s()    >>> s._called_count     1    """    _called_count = 0    def __getattr__(self, name):        if not self.__dict__.has_key(name):            self.__dict__[name] = Stub()        return self.__dict__[name]    def __setattr__(self, name, value):        self.__dict__[name] = value        return self    def __call__(self, *args, **options):        self._called_count += 1        return self.__call#该片段来自于http://byrx.net

评论关闭