python doctest模块

doctest查找和执行交互式Python会话,检验其符合预期,常用场景如下:

  • 检验模块的文档字符串是最新的。
  • 衰退测试。
  • 书写教程。

Doctest比unittest简单,没有API。不过doctest没有fixture,不适合复杂的场景

Getting Started

需要注意的是,“>>>”后面必须跟个空格,否则会报错

def my_function(a, b):
    """
    >>> my_function(2, 3)
    6
    >>> my_function('a', 3)
    'aaa'
    """
    return a * b
    

To run the tests, use doctest as the main program via the-m option to the interpreter. Usually no output is produced while the tests are running, 

-v表示显示详细执行过程。测试用例以空行或者下个解释器提示符表示结束。


$ python -m doctest -v doctest_simple.py

Trying:
    my_function(2, 3)
Expecting:
    6
ok
Trying:
    my_function('a', 3)
Expecting:
    'aaa'
ok
1 items had no tests:
    doctest_simple
1 items passed all tests:
   2 tests in doctest_simple.my_function
2 tests in 2 items.
2 passed and 0 failed.
Test passed.

Examples cannot usually stand on their own as explanations of a function, so doctest also lets you keep the surrounding text you would normally include in the documentation. It looks for lines beginning with the interpreter prompt,>>>, to find the beginning of a test case. The case is ended by a blank line, or by the next interpreter prompt. Intervening text is ignored, and can have any format as long as it does not look like a test case.

def my_function(a, b):
    """Returns a * b.

    Works with numbers:
    
    >>> my_function(2, 3)
    6

    and strings:
    
    >>> my_function('a', 3)
    'aaa'
    """
    return a * b
    

 

 

The surrounding text in the updated docstring makes it more useful to a human reader, and is ignored bydoctest, and the results are the same.

$ python -m doctest -v doctest_simple_with_docs.py

Trying:
    my_function(2, 3)
Expecting:
    6
ok
Trying:
    my_function('a', 3)
Expecting:
    'aaa'
ok
1 items had no tests:
    doctest_simple_with_docs
1 items passed all tests:
   2 tests in doctest_simple_with_docs.my_function
2 tests in 2 items.
2 passed and 0 failed.
Test passed.

 

另外的例子

#!/usr/bin/env python3.2
def is_between(v, lower, higher):
    '''demo of doctest
    >>> is_between(5,1,9)    
    True
    >>> is_between(3,3,9)
    False
    '''
    return lower<v<higher


if __name__=='__main__':
    import doctest
    doctest.testmod(verbose=True)


 

 

需要注意的是,“>>>”后面必须跟个空格,否则会报错
ValueError: line 2 of the docstring for __main__.is_between lacks blank after >>>: '    >>>is_between(5,1,9)    '


python thefile.py -v
显示doctest详细信息

 

 

 

转自:http://blog.sina.com.cn/s/blog_630c58cb0100u20d.html

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值