《python本质参考 第4版》笔记 §11 测试、调试、..
时间:2010-10-14 来源:oychw
§11 测试、调试、评测和调优
§11.1 文档字符串
#!/usr/bin/env python
# -*- coding: gbk -*-
import sys
#设定字符编码为GBK
reload(sys)
sys.setdefaultencoding('gbk')
def split(line, types=None, delimiter=None):
"""Splits a line of text and optionally performs type conversion.
For example:
>>> split('GOOG 100 490.50')
['GOOG', '100', '490.50']
>>> split('GOOG 100 490.50',[str, int, float])
['GOOG', 100, 490.5]
>>>
By default, splitting is performed on whitespace, but a different
delimiter can be selected with the delimiter keyword argument:
>>> split('GOOG,100,490.50',delimiter=',')
['GOOG', '100', '490.50']
>>>
"""
fields = line.split(delimiter)
if types:
fields = [ ty(val) for ty,val in zip(types,fields) ]
return fields
if __name__=='__main__':
# test myself
import doctest
doctest.testmod(verbose=True)
作为模块的使用:
# testsplitter.py
import splitter
import doctest
nfail, ntests = doctest.testmod(splitter)
运行结果:
Trying:
split('GOOG 100 490.50')
Expecting:
['GOOG', '100', '490.50']
ok
Trying:
split('GOOG 100 490.50',[str, int, float])
Expecting:
['GOOG', 100, 490.5]
ok
Trying:
split('GOOG,100,490.50',delimiter=',')
Expecting:
['GOOG', '100', '490.50']
ok
1 items had no tests:
splitter
1 items passed all tests:
3 tests in splitter.split
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
如果没有设置verbose=True,仅仅在出错之后才会有输出。
Doctest 不适合做完整的测试,用户看到庞大的边界测试用例等会觉得厌烦。一般要使用unittest。