卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16333本站已运行3317

如何在Python中指定和强制执行接口规范?

如何在Python中指定和强制执行接口规范?

Let us first see what is an interface spec. The interface spec is an interface specification for a module provided by programming languages such as C++ and Java. It describes the prototypes for the methods and functions of the module.

The abc module

在Python 2.6中引入了abc模块,用于定义抽象基类(ABCs)。使用isinstance()和issubclass()来检查一个实例或一个类是否实现了特定的抽象基类。通过这个,collections.abc模块定义了一组有用的抽象基类,如Iterable、Container和MutableMapping。

collections模块有一些从ABCs派生的类。collections.abc子模块有一些ABCs,可以用来测试一个类或实例是否提供特定的接口。

The rewards of interface specifications can be attained by a suitable test discipline in Python −

Test Suite

A good test suite for a module can both provide a regression test and serve as a module interface specification and a set of examples. Many Python modules can be run as a script to provide a simple self test.

Stub Emulations

可以翻译为:

存根仿真

Even modules which use complex external interfaces can often be tested in isolation using trivial “stub” emulations of the external interface.

使用doctest和unittest模块创建测试套件

The doctest and unittest modules or third-party test frameworks can be used to construct exhaustive test suites that exercise every line of code in a module.

doctest模块搜索看起来像是交互式Python会话的文本片段,然后执行这些会话以验证它们是否与显示的完全一致。

unittest模块支持测试自动化,共享测试的设置和关闭代码,将测试聚合到集合中,并使测试与报告框架独立。

构建大型复杂应用程序

A suitable testing discipline can help build large complex applications in Python as well as having interface specifications would.

测试驱动开发

编写测试套件非常有帮助,您可能希望设计您的代码以便轻松进行测试。一种越来越流行的技术,即测试驱动开发,要求您首先编写测试套件的部分内容,然后再编写实际的代码。

卓越飞翔博客
上一篇: 如何使用C++语言实现嵌入式系统的各个关键功能
下一篇: Python中列表、元组、集合和字典的区别和应用
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏