deffibonacci(max): ''' calculate fibonacci series >>> fib = fibonacci(100) >>> for i in fib: ... print(i, end=",") 0,1,1,2,3,5,8,13,21,34,55,89, >>> fib = fibonacci(-1) >>> next(fib) Traceback (most recent call last): ... StopIteration >>> next(fib) Traceback (most recent call last): ... StopIteration ''' a, b = 0, 1 while a < max: yield a a, b = b, a + b
if __name__ == "__main__": import doctest doctest.testmod()
末尾处的
1 2 3
if __name__ == "__main__": import doctest doctest.testmod()
Trying: fib = fibonacci(100) Expecting nothing ok Trying: for i in fib: print(i, end=",") Expecting: 0,1,1,2,3,5,8,13,21,34,55,89, ok Trying: fib = fibonacci(-1) Expecting nothing ok Trying: next(fib) Expecting: Traceback (most recent call last): ... StopIteration ok Trying: next(fib) Expecting: Traceback (most recent call last): ... StopIteration ok 1 items had no tests: __main__ 1 items passed all tests: 5 tests in __main__.fibonacci 5 tests in 2 items. 5 passed and 0 failed. Test passed.
unittest
unittest 已经被后面所要提到的 nose 所取代。这里不做详细介绍。如果想了解,可以参考文末提供的几个链接。
nose
nose 是一个比 unittest 更加先进的测试框架。其优势在于:
不用动不动就写个类,而只是写测试函数;
自动查找和搜集测试,不需要自己手动搭建测试集;
支持插件,可以搭配其他非常实用的标准化插件(coverage, output capture, drop into debugger on errors, doctests support, profiler)
为测试打标签,并且可以根据标签非常灵活的选择测试集;
并行测试;
更好的支持fixtures;
产生器测试。
缺点:不是在标准库自带的,需要自行安装。
示例
使用 nosetest 要求先建立好工程目录。这里假设你已经按照 打包 一节建立好了工程目录,并写好了 setup.py 文件。现在可以工程目录下建立 test 目录,然后在里头编写测试脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/bin/python # fibonacci_test.py
from nose.tools import * from fib.fibonacci import fibonacci
deftest_fib(): myfib = fibonacci(100) series = [] test_case = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] for i in myfib: series.append(i) assert_equal(series, test_case)
说明:
注意将该脚本命名为带“test”字符串的文件,例如 “fibonacci_test.py”,否则 nose 将不会直接执行这段测试代码。