xuol001 发表于 2015-4-28 10:00:26

【python测试】--doctest简单点的

  1)unitest:通用测试框架
  2)doctest:简单一点的模块,用于检查文档的,对于编写的单元测试也很在行。
1 doctest

  


view plaincopy to clipboardprint?
[*]#my_math.py
[*]
[*]def square(x):
[*]    '''''
[*]    Squares a number and returns the results.
[*]    >>> square(2)
[*]    4
[*]    >>> square(3)
[*]    9
[*]    '''
[*]    return x*x
[*]      
[*]if __name__ == '__main__':
[*]    import doctest, my_math
[*]    doctest.testmod(my_math)
#my_math.pydef square(x):'''Squares a number and returns the results.>>> square(2)4>>> square(3)9'''return x*xif __name__ == '__main__':import doctest, my_mathdoctest.testmod(my_math)   

  


view plaincopy to clipboardprint?
[*]# python my_math.py -v
[*]Trying:
[*]    square(2)
[*]Expecting:
[*]    4
[*]ok
[*]Trying:
[*]    square(3)
[*]Expecting:
[*]    9
[*]ok
[*]1 items had no tests:
[*]    my_math
[*]1 items passed all tests:
[*]   2 tests in my_math.square
[*]2 tests in 2 items.
[*]2 passed and 0 failed.
[*]Test passed.
# python my_math.py -vTrying:square(2)Expecting:4okTrying:square(3)Expecting:9ok1 items had no tests:my_math1 items passed all tests:2 tests in my_math.square2 tests in 2 items.2 passed and 0 failed.Test passed.   
  把x*x改成x**x,得到以下输出:

  


view plaincopy to clipboardprint?
[*]# python my_math.py -v
[*]Trying:
[*]    square(2)
[*]Expecting:
[*]    4
[*]ok
[*]Trying:
[*]    square(3)
[*]Expecting:
[*]    9
[*]**********************************************************************
[*]File "/home/liqing/PythonStudy/my_math.py", line 8, in my_math.square
[*]Failed example:
[*]    square(3)
[*]Expected:
[*]    9
[*]Got:
[*]    27
[*]1 items had no tests:
[*]    my_math
[*]**********************************************************************
[*]1 items had failures:
[*]   1 of   2 in my_math.square
[*]2 tests in 2 items.
[*]1 passed and 1 failed.
[*]***Test Failed*** 1 failures.
# python my_math.py -vTrying:square(2)Expecting:4okTrying:square(3)Expecting:9**********************************************************************File "/home/liqing/PythonStudy/my_math.py", line 8, in my_math.squareFailed example:square(3)Expected:9Got:271 items had no tests:my_math**********************************************************************1 items had failures:1 of   2 in my_math.square2 tests in 2 items.1 passed and 1 failed.***Test Failed*** 1 failures.   
  错误被扑捉到了!
页: [1]
查看完整版本: 【python测试】--doctest简单点的