Python内置的“文档测试”(doctest)模块可以直接提取注释中的代码并执行测试。

例子:

# mydict2.py
class Dict(dict):
'''
Simple dict but also support access as x.y style. >>> d1 = Dict()
>>> d1['x'] = 100
>>> d1.x
100
>>> d1.y = 200
>>> d1['y']
200
>>> d2 = Dict(a=1, b=2, c='3')
>>> d2.c
'3'
>>> d2['empty']
Traceback (most recent call last):
...
KeyError: 'empty'
>>> d2.empty
Traceback (most recent call last):
...
AttributeError: 'Dict' object has no attribute 'empty'
'''
def __init__(self, **kw):
super(Dict, self).__init__(**kw) def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key) def __setattr__(self, key, value):
self[key] = value if __name__=='__main__':
import doctest
doctest.testmod()

如果程序没有错误,则没有输出

如果程序有问题,比如把__getattr__()方法注释掉,再运行就会报错:

>>>
**********************************************************************
File "C:\Users\SQD\Desktop\Git\Python\doctest\mydict2.py", line 12, in __main__.Dict
Failed example:
d1['y']
Exception raised:
Traceback (most recent call last):
File "C:\Python34\lib\doctest.py", line 1324, in __run
compileflags, 1), test.globs)
File "<doctest __main__.Dict[4]>", line 1, in <module>
d1['y']
KeyError: 'y'
**********************************************************************
1 items had failures:
1 of 9 in __main__.Dict
***Test Failed*** 1 failures.

注意到最后3行代码。当模块正常导入时,doctest不会被执行。只有在命令行直接运行时,才执行doctest。所以,不必担心doctest会在非测试环境下执行。

最新文章

  1. 课程设计 --- 黑白棋中的 AI
  2. 关于数组的map、reduce、filter
  3. Python 之作用域和名字空间
  4. asp.net core csrf
  5. WebLogic 的一些基本概念
  6. Caching Tutorial
  7. PHP Predefined Interfaces 预定义接口(转)
  8. 来自GitHub的Android UI开源项目
  9. F - The Circumference of the Circle
  10. cloneNode和replaceChild
  11. Python中使用MongoEngine2
  12. P1177 【模板】快速排序(学完归并和堆排之后的二更)
  13. HTTP POST请求
  14. 分考场(无向图着色问题)(dfs回溯)
  15. pyCharm的第一个项目
  16. asp.net core2.1 bundleconfig.json合并压缩资源文件
  17. 《DISTRIBUTED SYSTEMS Concepts and Design》读书笔记 一
  18. Openstack单元测试工具简单说明
  19. 20155321 《网络攻防》 Exp3 免杀原理与实践
  20. 使用jupyterthemes插件定制jupyter notebook界面

热门文章

  1. UISlider 滑竿控件
  2. ios 中Category类别(扩展类)小结
  3. setting up a IPSEC/L2TP vpn on CentOS 6 or Red Hat Enterprise Linux 6 or Scientific Linux
  4. slam相关知识
  5. POJ 1696 Space Ant 极角排序(叉积的应用)
  6. Sublime 3 and Python
  7. C# 网上收集的一些所谓的开源项目
  8. Chapter 2 Open Book——17
  9. LeetCode OJ 189. Rotate Array
  10. OpenCV ——双线性插值(Bilinear interpolation)