在 Python 中测试摘要 class

Test a abstract class in Python

我使用 Python(2.7) 中的摘要 class 创建了一个 class,现在我想通过 Nose 测试这个 class。技术上如何实现?

这里我举个例子代码:

# -*- 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

您可以制作摘要 class 的子class 并测试子class。此外,在调用抽象方法时,您可以引发 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.

然后你实现一个subclass:

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)