我使用Python(2.7)中的抽象类创建了一个类,现在我想通过Nose测试这个类。如何在技术上实现它?
这里我给出一个示例代码:
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod, abstractproperty
class A(object):
__metaclass__ = ABCMeta
@abstractproperty
def a(self):
pass
@abstractmethod
def do(self, obj):
pass
答案 0 :(得分:2)
您可以创建抽象类的子类并测试子类。另外,在调用抽象方法时,您可以提出pass
而不是NotImplementedError
:
@abstractproperty
def a(self):
raise NotImplementedError("Not implemented")
@abstractmethod
def do(self, obj):
raise NotImplementedError("Not implemented")
如Python exceptions documentation中所述:
异常NotImplementedError
此异常派生自RuntimeError。在用户定义的基类中,抽象方法在需要派生类覆盖方法时应引发此异常。
然后实现一个子类:
class B(A):
def a(self):
super(B, self).a()
def do(self, obj):
super(B, self).do(obj)
你测试的就像这样:
@raises(NotImplementedError)
def abstractPropertyAShouldNotRun():
B().a()
@raises(NotImplementedError)
def abstractMethodDoShouldNotRun():
obj = []
B().do(obj)