我使用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
最佳答案
您可以创建抽象类的子类并测试该子类。此外,您可以在调用抽象方法时引发 NotImplementedError
,而不是 pass
:
@abstractproperty
def a(self):
raise NotImplementedError("Not implemented")
@abstractmethod
def do(self, obj):
raise NotImplementedError("Not implemented")
如 Python exceptions documentation 中所述:
exception NotImplementedError
This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.
然后你实现一个子类:
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)
关于python - 在 Python 中测试抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28299191/