Python -- 文档测试
2024-09-19 04:43:03
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会在非测试环境下执行。
最新文章
- 课程设计 --- 黑白棋中的 AI
- 关于数组的map、reduce、filter
- Python 之作用域和名字空间
- asp.net core csrf
- WebLogic 的一些基本概念
- Caching Tutorial
- PHP Predefined Interfaces 预定义接口(转)
- 来自GitHub的Android UI开源项目
- F - The Circumference of the Circle
- cloneNode和replaceChild
- Python中使用MongoEngine2
- P1177 【模板】快速排序(学完归并和堆排之后的二更)
- HTTP POST请求
- 分考场(无向图着色问题)(dfs回溯)
- pyCharm的第一个项目
- asp.net core2.1 bundleconfig.json合并压缩资源文件
- 《DISTRIBUTED SYSTEMS Concepts and Design》读书笔记 一
- Openstack单元测试工具简单说明
- 20155321 《网络攻防》 Exp3 免杀原理与实践
- 使用jupyterthemes插件定制jupyter notebook界面
热门文章
- UISlider 滑竿控件
- ios 中Category类别(扩展类)小结
- setting up a IPSEC/L2TP vpn on CentOS 6 or Red Hat Enterprise Linux 6 or Scientific Linux
- slam相关知识
- POJ 1696 Space Ant 极角排序(叉积的应用)
- Sublime 3 and Python
- C# 网上收集的一些所谓的开源项目
- Chapter 2 Open Book——17
- LeetCode OJ 189. Rotate Array
- OpenCV ——双线性插值(Bilinear interpolation)