在 Python 中测试抽象类

Oct*_*ian 5 python unit-testing nose

我使用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
Run Code Online (Sandbox Code Playgroud)

And*_*ira 5

您可以创建抽象类的子类并测试该子类。另外,pass您可以NotImplementedError在调用抽象方法时引发 a 来代替 :

@abstractproperty
def a(self):
    raise NotImplementedError("Not implemented")

@abstractmethod
def do(self, obj):
    raise NotImplementedError("Not implemented")
Run Code Online (Sandbox Code Playgroud)

正如Python 异常文档中所述:

异常未实现错误

该异常源自 RuntimeError。在用户定义的基类中,抽象方法在需要派生类重写该方法时应引发此异常。

然后你实现一个子类:

class B(A):
    def a(self):
        super(B, self).a()
    
    def do(self, obj):
        super(B, self).do(obj)
Run Code Online (Sandbox Code Playgroud)

你可以这样测试:

@raises(NotImplementedError)
def abstractPropertyAShouldNotRun():
    B().a()

@raises(NotImplementedError)
def abstractMethodDoShouldNotRun():
    obj = []
    B().do(obj)
Run Code Online (Sandbox Code Playgroud)

  • @GonzaloGarcia,它来自鼻子(https://nose.readthedocs.io/en/latest/testing_tools.html)。我认为 pytest 有 `pytest.raises` (https://docs.pytest.org/en/latest/assert.html#assertions-about-expected-exceptions)来检查是否引发异常,但它不是注释。 (2认同)