codecamp

doctest 检查文本文件中的示例

doctest的另一个简单应用是在文本文件中测试交互式示例。这可以通过以下testfile()功能完成:

import doctest
doctest.testfile("example.txt")

该短脚本执行并验证文件中包含的任何交互式Python示例example.txt。文件内容被视为一个巨大的文档字符串; 该文件不需要包含Python程序!例如,也许example.txt包含这个:

The ``example`` module
======================

Using ``factorial``
-------------------

This is an example text file in reStructuredText format.  First import
``factorial`` from the ``example`` module:

    >>> from example import factorial

Now use it:

    >>> factorial(6)
    120

运行doctest.testfile("example.txt")然后在这个文档中找到错误:

File "./example.txt", line 14, in example.txt
Failed example:
    factorial(6)
Expected:
    120
Got:
    720

与testmod()一样,testfile()除非例子失败,否则不会显示任何内容。如果一个例子失败了,那么失败的例子和失败的原因将被打印到标准输出中,格式为testmod()。

默认情况下,testfile()查找调用模块目录中的文件。有关可用于指示其在其他位置查找文件的可选参数的说明,请参见Basic API一节。

就像testmod(),testfile()可以通过-v命令行开关或可选的关键字参数verbose来设置详细程度。

自Python 2.6以来,还有一个用于运行的命令行快捷方式testfile()。您可以指示Python解释器直接从标准库运行doctest模块,并在命令行上传递文件名:

python -m doctest -v example.txt

因为文件名并不以此结束.py,因此doctest推断它必须与其一起运行testfile(),而不是testmod()。

有关更多信息testfile(),请参阅基本API一节。


doctest 检查Docstrings中的示例
doctest 工作原理
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }