Skip to content

Commit c2aa548

Browse files
committed
Compatibility fix with pytest < 8
tests/test_eager_preimports.py::create_doctest_wrapper() - Fixed compatibility error (`_pytest.doctest.get_optionflags()` expecting a `pytest.Config` in v8+ but an object having it at `.config` below) - Future-proofed against `pytest` API changes by falling back to the vanilla `doctest` implementation with a warning if setting up the test item fails
1 parent 6dc5f9f commit c2aa548

1 file changed

Lines changed: 28 additions & 9 deletions

File tree

tests/test_eager_preimports.py

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
import functools
1212
import importlib
1313
import pathlib
14+
import warnings
15+
import traceback
1416
from types import ModuleType
1517
from typing import Any, Callable, Dict, Type, Union
1618

@@ -75,15 +77,32 @@ def create_doctest_wrapper(
7577
use_pytest_doctest = False
7678

7779
def wrapper_pytest(request: pytest.FixtureRequest) -> None:
78-
if globs is not None:
79-
test.globs = globs.copy()
80-
module = module_from_parent(parent=request.session, path=fname)
81-
runner = PytestDoctestRunner(
82-
checker=checker,
83-
optionflags=get_doctest_option_flags(request.config),
84-
continue_on_failure=False)
85-
item = item_from_parent(module, name=name, runner=runner, dtest=test)
86-
item.setup()
80+
try:
81+
if globs is not None:
82+
test.globs = globs.copy()
83+
module = module_from_parent(parent=request.session, path=fname)
84+
try:
85+
option_flags = get_doctest_option_flags(request.config)
86+
except AttributeError:
87+
# `pytest < 8` expects an object having the `.config` to
88+
# be passed, instead of the `pytest.Config` itself
89+
option_flags = get_doctest_option_flags(request)
90+
runner = PytestDoctestRunner(checker=checker,
91+
optionflags=option_flags,
92+
continue_on_failure=False)
93+
item = item_from_parent(module,
94+
name=name, runner=runner, dtest=test)
95+
item.setup()
96+
except Exception as e:
97+
# If setting up the test item fails (e.g. due to `pytest`
98+
# refactoring), fall back to the vanilla implementation with
99+
# a warning
100+
msg = ('failed to convert `doctest.DocTest` into '
101+
'`pytest.Item`:\n\n'
102+
f'{"".join(traceback.format_exception(e))}\n'
103+
'falling back to vanilla `doctest`')
104+
warnings.warn(msg)
105+
return wrapper_vanilla()
87106
try:
88107
item.runtest()
89108
except doctest.UnexpectedException as e:

0 commit comments

Comments
 (0)