我想在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是否会是更好的框架?
doctest.testmod()
在__main__
模块中运行doctest,这取决于您实际运行的脚本。
您可以使用m
参数解决此问题,但仍然会被迫在每个具有doctest的模块中添加样板代码。试试这个:
doctest.testfile("some_module.py")