2011-11-17 71 views

回答

1

我没有用它自己,但它是我的理解,它扩展的doctest功能。例如,它添加了testsetuptestcleanup指令,您可以将其设置和拆卸逻辑放入其中。使Sphinx可以在文档中排除该指令。

1

下面是一个简单的例子(从the doctest module):

""" 
This is the "example" module. 

The example module supplies one function, factorial(). For example, 

>>> factorial(5) 
120 
""" 

def factorial(n): 
    """Return the factorial of n, an exact integer >= 0. 

    If the result is small enough to fit in an int, return an int. 
    Else return a long. 

    >>> [factorial(n) for n in range(6)] 
    [1, 1, 2, 6, 24, 120] 
    >>> [factorial(long(n)) for n in range(6)] 
    [1, 1, 2, 6, 24, 120] 
    >>> factorial(30) 
    265252859812191058636308480000000L 
    >>> factorial(30L) 
    265252859812191058636308480000000L 
    >>> factorial(-1) 
    Traceback (most recent call last): 
     ... 
    ValueError: n must be >= 0 

    Factorials of floats are OK, but the float must be an exact integer: 
    >>> factorial(30.1) 
    Traceback (most recent call last): 
     ... 
    ValueError: n must be exact integer 
    >>> factorial(30.0) 
    265252859812191058636308480000000L 

    It must also not be ridiculously large: 
    >>> factorial(1e100) 
    Traceback (most recent call last): 
     ... 
    OverflowError: n too large 
    """ 

    import math 
    if not n >= 0: 
     raise ValueError("n must be >= 0") 
    if math.floor(n) != n: 
     raise ValueError("n must be exact integer") 
    if n+1 == n: # catch a value like 1e300 
     raise OverflowError("n too large") 
    result = 1 
    factor = 2 
    while factor <= n: 
     result *= factor 
     factor += 1 
    return result 


if __name__ == "__main__": 
    import doctest 
    doctest.testmod() 
+0

我不想要这个例子。我想了解它的真实世界用法 –

3

Sphinx的doctest测试文档本身。换句话说,它允许自动验证文档的示例代码。虽然它也可能验证Python代码是否按预期工作,但Sphinx不仅仅是用于此目的(您可以更轻松地使用标准库的doctest模块)。因此,一个真实世界的场景(我经常遇到这种场景)就像这样:一个新功能即将完成,因此我编写了一些文档来介绍这个新功能。新文档包含一个或多个代码示例。在发布文档之前,我在我的Sphinx文档目录中运行make doctest,以验证我为受众撰写的代码示例是否真的有效。