python - 在 Python 中测试抽象类

标签 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

最佳答案

您可以创建抽象类的子类并测试该子类。此外,您可以在调用抽象方法时引发 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/

相关文章:

unit-testing - 编写 Substrate Runtime Test 时快进时间

python - 用另一个文件的行替换文件的行

python - 将参数作为字符串传递给 zip(),避免使用 exec()

AngularJS - 在使用 moment.js 的 Controller 上进行单元测试

python - “python setup.py notests”报告包的 __init__.py 未被测试覆盖

python - 使用 Python unittest : how to improve granularity? 进行集成测试

python - 带有命令行参数的 Nose 测试脚本

python - 填充列表与字典时的性能注意事项

python - Try-except 未知功能?

c# - Visual Studio 2010 单元测试