diff --git a/Lib/doctest.py b/Lib/doctest.py index a8f08868cf4957..ca919ef1d808a4 100644 --- a/Lib/doctest.py +++ b/Lib/doctest.py @@ -1379,7 +1379,7 @@ def _failure_header(self, test, example): # DocTest Running #///////////////////////////////////////////////////////////////// - def __run(self, test, compileflags, out): + def __run(self, test, compileflags, out, original_optionflags): """ Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the @@ -1390,10 +1390,6 @@ def __run(self, test, compileflags, out): # Keep track of the number of failed, attempted, skipped examples. failures = attempted = skips = 0 - # Save the option flags (since option directives can be used - # to modify them). - original_optionflags = self.optionflags - SUCCESS, FAILURE, BOOM = range(3) # `outcome` state check = self._checker.check_output @@ -1515,9 +1511,6 @@ def __run(self, test, compileflags, out): if failures and self.optionflags & FAIL_FAST: break - # Restore the option flags (in case they were modified) - self.optionflags = original_optionflags - # Record and return the number of failures and attempted. self.__record_outcome(test, failures, attempted, skips) return TestResults(failures, attempted, skipped=skips) @@ -1601,7 +1594,11 @@ def run(self, test, compileflags=None, out=None, clear_globs=True): for key in color_variables: color_variables[key] = os.environ.pop(key, None) try: - return self.__run(test, compileflags, out) + original_optionflags = self.optionflags + try: + return self.__run(test, compileflags, out, original_optionflags) + finally: + self.optionflags = original_optionflags finally: sys.stdout = save_stdout pdb.set_trace = save_set_trace diff --git a/Lib/test/test_doctest/test_doctest.py b/Lib/test/test_doctest/test_doctest.py index 776ad83ee6d6ce..f58c79ddd4b2b0 100644 --- a/Lib/test/test_doctest/test_doctest.py +++ b/Lib/test/test_doctest/test_doctest.py @@ -774,6 +774,15 @@ def non_Python_modules(): r""" class TestDocTest(unittest.TestCase): + def test_debug_runner_restores_directives(self): + runner = doctest.DebugRunner(verbose=False) + parser = doctest.DocTestParser() + for source in (">>> print('actual') # doctest: +ELLIPSIS\nwrong", + ">>> print('actual')\na..."): + test = parser.get_doctest(source, {}, "example", None, 0) + with self.assertRaises(doctest.DocTestFailure): + runner.run(test) + def test_run(self): test = ''' >>> 1 + 1 diff --git a/Misc/NEWS.d/next/Library/2026-11-25-19-49-00.gh-issue-163094.Dm8sR5.rst b/Misc/NEWS.d/next/Library/2026-11-25-19-49-00.gh-issue-163094.Dm8sR5.rst new file mode 100644 index 00000000000000..81a19b03b0260e --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-25-19-49-00.gh-issue-163094.Dm8sR5.rst @@ -0,0 +1,2 @@ +Restore :mod:`doctest` option flags after a :class:`~doctest.DebugRunner` +stops on a failure.