Debian Codegraph @

src/pytest_cython/plugin.py

raw
1 """Discover and run doctests in Cython extension modules."""
2
3 from __future__ import annotations
4
5 import os
6 import pathlib
7 import re
8 from typing import Any, Iterable
9
10 import pytest
11 from _pytest.doctest import DoctestItem, DoctestModule
12 from _pytest.pathlib import ImportMode, resolve_package_path
13
14 CYTHON_SUFFIXES = [".pyx"]
15
16 IGNORE_IMPORTMISMATCH_KEY = "PY_IGNORE_IMPORTMISMATCH"
17 IGNORE_IMPORTMISMATCH = os.environ.get(IGNORE_IMPORTMISMATCH_KEY, "")
18
19
20 def pytest_addoption(parser: pytest.Parser):
21 group = parser.getgroup("cython")
22
23 group.addoption(
24 "--doctest-cython",
25 action="store_true",
26 default=False,
27 help="run doctests in all .so and .pyd modules",
28 dest="doctest_cython",
29 )
30
31
32 def pytest_collect_file(
33 file_path: pathlib.Path, parent: pytest.Collector
34 ) -> pytest.Module:
35 config = parent.config
36 if file_path.suffix not in CYTHON_SUFFIXES or not config.getoption(
37 "--doctest-cython"
38 ):
39 return
40
41 # only run test if matching .so and .pyx files exist
42 return _PatchedDoctestModule.from_parent(parent, path=file_path)
43
44
45 class _PatchedDoctestModule(DoctestModule):
46 def collect(self) -> Iterable[DoctestItem]:
47 mode = ImportMode(self.config.getoption("importmode"))
48
49 if mode is not ImportMode.importlib and IGNORE_IMPORTMISMATCH != "1":
50 # we know we will get an import file mismatch error so ignore it for now,
51 # we will double check the import paths after import.
52 os.environ[IGNORE_IMPORTMISMATCH_KEY] = "1"
53
54 try:
55 items = list(super().collect()) # import the module and collect tests
56 finally:
57 # set ignore variable back to its original value
58 os.environ[IGNORE_IMPORTMISMATCH_KEY] = IGNORE_IMPORTMISMATCH
59
60 module = self.obj # module already imported
61 return _add_line_numbers(module, items)
62
63
64 def _without_suffixes(path: str | pathlib.Path) -> pathlib.Path:
65 path = pathlib.Path(path)
66 return path.with_name(path.name.split(".")[0]).with_suffix("")
67
68
69 def _get_module_name(path: pathlib.Path) -> str:
70 pkg_path = resolve_package_path(path)
71 if pkg_path is not None:
72 pkg_root = pkg_path.parent
73 names = list(path.with_suffix("").relative_to(pkg_root).parts)
74 if names[-1] == "__init__":
75 names.pop()
76 module_name = ".".join(names)
77 else:
78 pkg_root = path.parent
79 module_name = path.stem
80
81 return module_name
82
83
84 def _add_line_numbers(
85 module: Any, items: Iterable[DoctestItem]
86 ) -> Iterable[DoctestItem]:
87 # handle tests from Cython's internal __test__ dict generated by
88 # the autotestdict directive; we exclude the tests from __test__,
89 # though they do give us a little bonus if they exist: we can extract
90 # the line number of the test
91 lineno_re = re.compile(r"\(line (\d+)\)")
92 test_dict = module.__name__ + ".__test__"
93 test_items = {x.name: x for x in items}
94
95 for test_name in list(test_items.keys()):
96 if not test_name.startswith(test_dict + "."):
97 continue
98
99 match = lineno_re.search(test_name)
100 lineno = int(match.group(1)) if match else None
101
102 # If somehow the equivalent test does not already exist, we
103 # keep the __test__ test (maybe it is something else not
104 # generated by autotestdict)
105 equiv_test_name = test_name.split()[0].replace(test_dict, module.__name__)
106
107 if (
108 equiv_test_name not in test_items
109 or not test_items[equiv_test_name].dtest.examples
110 ):
111 # for some reason the equivalent test was not found (e.g.
112 # the module was compiled with docstrings stripped) so keep
113 # the __test__ test but hide the fact that it came from the
114 # __test__ dict
115 test_items[test_name].name = equiv_test_name
116 # set lineno on the __test__ test as well, since normally
117 # it is not set by doctest
118 test_items[test_name].dtest.lineno = lineno
119 continue
120
121 # Delete the __test__ test, but try to update the lineno of the
122 # equivalent test
123 del test_items[test_name]
124 test_items[equiv_test_name].dtest.lineno = lineno
125
126 yield from sorted(test_items.values(), key=lambda x: x.name)