[英]Test a abstract class in Python
我使用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
您可以作為抽象類的子類並測試該子類。 另外,代替pass
,可以在調用抽象方法時引發NotImplementedError
:
@abstractproperty
def a(self):
raise NotImplementedError("Not implemented")
@abstractmethod
def do(self, obj):
raise NotImplementedError("Not implemented")
如Python異常文檔所述 :
異常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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.