Doc-tests从模块和命令行运行,而不是从预提交钩子运行

问题描述 投票:0回答:1

我想在Python的预提交钩子中运行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.py0

我要导入模块的原因是要在类似于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'),
        )
    )

为什么从命令行和脚本中调用而不是在导入脚本时运行doc-test?如unittest中所述,this thread是否会是更好的框架?

python git module doctest pre-commit
1个回答
0
投票
doctest.testmod()

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

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

doctest.testfile("some_module.py")
© www.soinside.com 2019 - 2024. All rights reserved.