I want to run doc-tests of a Python script as part of a pre-commit hook in Python.
In the file set_prefix.py
, I have doc-tests in front of functions, which I test before running with:
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()
When I run python3 set_prefix.py test
, I get the error I expected.
Yet, when I import the module and call the function:
import set_prefix
if "__main__" == __name__:
test_failures = set_prefix.get_failed_tests()
print(test_failures)
I get 0 failures:
$ python3 temp.py 0
The reason I want to import the module is to run the tests in a pre-commit hook similar to that added by 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'),
)
)
Why do the doc-tests run when called from the command-line and the script and not when the script is imported? Would unittest
be a better framework, as described in this thread?