1# coding: utf-8
2import argparse
3import os
4from doctest import FAIL_FAST, OPTIONFLAGS_BY_NAME, testfile, testmod
5
6from ..loader import Notebook
7
8
9def _test():
10 parser = argparse.ArgumentParser(description="doctest runner")
11 parser.add_argument(
12 "-v",
13 "--verbose",
14 action="store_true",
15 default=False,
16 help="print very verbose output for all tests",
17 )
18 parser.add_argument(
19 "-o",
20 "--option",
21 action="append",
22 choices=OPTIONFLAGS_BY_NAME.keys(),
23 default=[],
24 help=(
25 "specify a doctest option flag to apply"
26 " to the test run; may be specified more"
27 " than once to apply multiple options"
28 ),
29 )
30 parser.add_argument(
31 "-f",
32 "--fail-fast",
33 action="store_true",
34 help=(
35 "stop running tests after first failure (this"
36 " is a shorthand for -o FAIL_FAST, and is"
37 " in addition to any other -o options)"
38 ),
39 )
40 parser.add_argument("file", nargs="+", help="file containing the tests to run")
41 args = parser.parse_args()
42 testfiles = args.file
43 # Verbose used to be handled by the "inspect argv" magic in DocTestRunner,
44 # but since we are using argparse we are passing it manually now.
45 verbose = args.verbose
46 options = 0
47 for option in args.option:
48 options |= OPTIONFLAGS_BY_NAME[option]
49 if args.fail_fast:
50 options |= FAIL_FAST
51 for filename in testfiles:
52 if any(map(filename.endswith, (".py", ".ipynb"))):
53 # It is a module -- insert its dir into sys.path and try to
54 # import it. If it is part of a package, that possibly
55 # won't work because of package imports.
56 failures, _ = testmod(
57 Notebook.load(filename), verbose=verbose, optionflags=options
58 )
59 else:
60 failures, _ = testfile(
61 filename, module_relative=False, verbose=verbose, optionflags=options
62 )
63 if failures:
64 return 1
65 return 0
66
67
68if __name__ == "__main__":
69 _test()
70
71if __name__ == "__main__":
72 from .export import export
73
74 export("nbdoctest.ipynb", "../../utils/nbdoctest.py")