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 was introduced in Python 2.6 for defining abstract base classes (ABCs). Use isinstance() and issubclass() to check whether an instance or a class implements a specific abstract base class. With this, the collections.abc module defines a set of useful abstract base classes such as Iterable, Container, and MutableMapping.
The collections module has some classes derived from ABCs. The collections.abc submodule has some ABCs that can be used to test whether a class or instance provides a specific interface.
The rewards of interface can be attained by a suitable specifications test discipline in Python −
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.
Even modules which use complex external interfaces can often be tested in isolation using trivial “stub” emulations of the external interface.
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.
The doctest module searches for text snippets that look like interactive Python sessions and then executes these sessions to verify that they are exactly as shown.
The unittest module supports test automation, shares setup and shutdown code for tests, aggregates tests into collections, and makes tests independent of the reporting framework.
A suitable testing discipline can help build large complex applications in Python as well as having interface specifications would.
Writing test suites is very helpful, and you may want to design your code so that it can be easily tested. An increasingly popular technique, test-driven development, requires you to first write portions of a test suite before writing the actual code.
The above is the detailed content of How to specify and enforce interface specifications in Python?. For more information, please follow other related articles on the PHP Chinese website!