diff --git a/changelog/3396.improvement.rst b/changelog/3396.improvement.rst new file mode 100644 index 00000000000..aa3f278c2a6 --- /dev/null +++ b/changelog/3396.improvement.rst @@ -0,0 +1 @@ +Doctests now respect the ``--import-mode`` flag. diff --git a/src/_pytest/doctest.py b/src/_pytest/doctest.py index ac5a29bb923..ed072fcd628 100644 --- a/src/_pytest/doctest.py +++ b/src/_pytest/doctest.py @@ -542,7 +542,11 @@ def _find( ) else: try: - module = import_path(self.path, root=self.config.rootpath) + module = import_path( + self.path, + root=self.config.rootpath, + mode=self.config.getoption("importmode"), + ) except ImportError: if self.config.getvalue("doctest_ignore_import_errors"): pytest.skip("unable to import module %r" % self.path) diff --git a/testing/test_doctest.py b/testing/test_doctest.py index 1b4809240c0..828253d3223 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -113,6 +113,28 @@ def test_simple_doctestfile(self, pytester: Pytester): reprec = pytester.inline_run(p) reprec.assertoutcome(failed=1) + def test_importmode(self, pytester: Pytester): + p = pytester.makepyfile( + **{ + "namespacepkg/innerpkg/__init__.py": "", + "namespacepkg/innerpkg/a.py": """ + def some_func(): + return 42 + """, + "namespacepkg/innerpkg/b.py": """ + from namespacepkg.innerpkg.a import some_func + def my_func(): + ''' + >>> my_func() + 42 + ''' + return some_func() + """, + } + ) + reprec = pytester.inline_run(p, "--doctest-modules", "--import-mode=importlib") + reprec.assertoutcome(passed=1) + def test_new_pattern(self, pytester: Pytester): p = pytester.maketxtfile( xdoc="""