Python-测试抽象基类

Python-测试抽象基类,第1张

Python-测试抽象基类

正如lunaryon所说,这是不可能的。包含抽象方法的ABC的真正目的是,它们不能像声明的那样实例化。

但是,可以创建一个对ABC进行内省的实用函数,并动态创建一个虚拟的非抽象类。可以在测试方法/函数内部直接调用此函数,而不必为了测试几种方法而在测试文件中写入样板代码。

def concreter(abclass):    """    >>> import abc    >>> class Abstract(metaclass=abc.ABCmeta):    ...     @abc.abstractmethod    ...     def bar(self):    ...        return None    >>> c = concreter(Abstract)    >>> c.__name__    'dummy_concrete_Abstract'    >>> c().bar() # doctest: +ELLIPSIS    (<abc_utils.Abstract object at 0x...>, (), {})    """    if not "__abstractmethods__" in abclass.__dict__:        return abclass    new_dict = abclass.__dict__.copy()    for abstractmethod in abclass.__abstractmethods__:        #replace each abc method or property with an identity function:        new_dict[abstractmethod] = lambda x, *args, **kw: (x, args, kw)    #creates a new class, with the overriden ABCs:    return type("dummy_concrete_%s" % abclass.__name__, (abclass,), new_dict)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5647078.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存