是否有一个基于python的实用程序来测试注释中的示例

2024-09-27 23:26:17 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有基于python的实用程序来测试函数注释中的示例?例如,给定orwell_1984.py中的以下代码:

def two_plus_two():
    """Returns 2 + 2 according to Orwell's 1984"""
    # EX: two_plus_two() => 5
    return 5

该实用程序将执行以下等效操作:

import orwell_1984
verify_test(orwell_1984.two_plus_two, (), 5)

其中verify\u test使用指定的参数调用传入的函数,然后确保等于预期值

不久前,我用perl写了一些东西来实现这一点;见http://www.cs.nmsu.edu/~tomohara/useful-scripts/test-perl-examples.perl。在尝试移植之前,我希望找到一个基于python的实用程序,它可以做类似的事情


Tags: to代码pytest实用程序示例defplus
1条回答
网友
1楼 · 发布于 2024-09-27 23:26:17

在Python中称为docstring,例如:

def two_plus_two():
    """Returns 2 + 2 according to Orwell's 1984.

    >>> two_plus_two()
    5
    """
    return 5

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

检查有关^{} module的信息

相关问题 更多 >

    热门问题