首页 > 解决方案 > Doc-tests 从模块和命令行运行,而不是从 pre-commit 钩子运行

问题描述

我想运行 Python 脚本的 doc-tests 作为 Python 中预提交挂钩的一部分。

在文件set_prefix.py中,我在函数前面有 doc-tests,我在运行之前对其进行了测试:

import doctest
import sys

EXTENSIONS = tuple([".%s" % ending for ending in ["jpg", "heic", "nrw"]])

def is_target_for_renaming(filepath):
    """Returns true if this filepath should be renamed.

    >>> is_target_for_renaming("/Users/username/Pictures/document.other_jpg")
    True
    """

    return filepath.lower().endswith(EXTENSIONS)


def get_failed_tests():
    r = doctest.testmod()
    return r.failed


def main():
    pass


if "__main__" == __name__:

    args = sys.argv
    test_only = 2 <= len(sys.argv) and "test" == sys.argv[1]
    test_failures = get_failed_tests()
    print(test_failures)
    assert 0 == test_failures

    if not test_only:
        main()

当我运行时python3 set_prefix.py test,我得到了我预期的错误。

然而,当我导入模块并调用函数时:

import set_prefix

if "__main__" == __name__:

    test_failures = set_prefix.get_failed_tests()
    print(test_failures)

我得到0次失败:

$ python3 temp.py
0

我要导入模块的原因是在类似于添加的预提交挂钩中运行测试flake8

#!/usr/local/opt/python/bin/python3.7
import sys

from flake8.main import git

if __name__ == '__main__':
    sys.exit(
        git.hook(
            strict=git.config_for('strict'),
            lazy=git.config_for('lazy'),
        )
    )

为什么从命令行和脚本调用文档测试而不是在导入脚本时运行文档测试?会unittest是一个更好的框架,正如这个线程中描述的那样?

标签: pythongitmoduledoctestpre-commit

解决方案


doctest.testmod()

在模块中运行 doctests,__main__这取决于您实际运行的脚本。

您可以使用参数解决此问题m,但您仍将被迫在每个具有 doctest 的模块中添加样板代码。尝试这个:

doctest.testfile("some_module.py")

推荐阅读