python - 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
是一个更好的框架,正如这个线程中描述的那样?
解决方案
doctest.testmod()
在模块中运行 doctests,__main__
这取决于您实际运行的脚本。
您可以使用参数解决此问题m
,但您仍将被迫在每个具有 doctest 的模块中添加样板代码。尝试这个:
doctest.testfile("some_module.py")
推荐阅读
- c++ - 找出在我的程序中放置 [I] 的位置
- javascript - TypeError:comments.map 不是函数
- python - 如何通过yahoo用pandas导入多个股票价格?
- javascript - 替换nodejs模板文件中两行之间的行
- algorithm - “WKS”虚拟内存压缩算法源码或详解?
- swiftui - SwiftUI Alert 如何让它在一个简单的 if 语句中工作?
- python - 嵌套 for 循环将每个唯一值的数据附加到列表中
- swift - 如何用 Swift 填充 UIBezierPath 的内部?
- c++ - 为什么编译器给出未定义的引用错误
- c++ - 用不同的数字替换每个正则表达式匹配