| 1 | # this is a hack to monkey patch pytest so it handles tests inside namespace packages without __init__.py properly |
| 2 | # without it, pytest can't discover the package root for some reason |
| 3 | # also see https://github.com/karlicoss/pytest_namespace_pkgs for more |
| 4 | |
| 5 | import os |
| 6 | import pathlib |
| 7 | from typing import Optional |
| 8 | |
| 9 | import _pytest.main |
| 10 | import _pytest.pathlib |
| 11 | |
| 12 | # we consider all dirs in repo/ to be namespace packages |
| 13 | root_dir = pathlib.Path(__file__).absolute().parent.resolve() / 'src' |
| 14 | assert root_dir.exists(), root_dir |
| 15 | |
| 16 | # TODO assert it contains package name?? maybe get it via setuptools.. |
| 17 | |
| 18 | namespace_pkg_dirs = [str(d) for d in root_dir.iterdir() if d.is_dir()] |
| 19 | |
| 20 | # resolve_package_path is called from _pytest.pathlib.import_path |
| 21 | # takes a full abs path to the test file and needs to return the path to the 'root' package on the filesystem |
| 22 | resolve_pkg_path_orig = _pytest.pathlib.resolve_package_path |
| 23 | |
| 24 | |
| 25 | def resolve_package_path(path: pathlib.Path) -> Optional[pathlib.Path]: |
| 26 | result = path # search from the test file upwards |
| 27 | for parent in result.parents: |
| 28 | if str(parent) in namespace_pkg_dirs: |
| 29 | return parent |
| 30 | if os.name == 'nt': |
| 31 | # ??? for some reason on windows it is trying to call this against conftest? but not on linux/osx |
| 32 | if path.name == 'conftest.py': |
| 33 | return resolve_pkg_path_orig(path) |
| 34 | raise RuntimeError("Couldn't determine path for ", path) |
| 35 | |
| 36 | |
| 37 | # NOTE: seems like it's not necessary anymore? |
| 38 | # keeping it for now just in case |
| 39 | # after https://github.com/pytest-dev/pytest/pull/13426 we should be able to remove the whole conftest |
| 40 | # _pytest.pathlib.resolve_package_path = resolve_package_path |
| 41 | |
| 42 | |
| 43 | # without patching, the orig function returns just a package name for some reason |
| 44 | # (I think it's used as a sort of fallback) |
| 45 | # so we need to point it at the absolute path properly |
| 46 | # not sure what are the consequences.. maybe it wouldn't be able to run against installed packages? not sure.. |
| 47 | search_pypath_orig = _pytest.main.search_pypath |
| 48 | |
| 49 | |
| 50 | def search_pypath(module_name: str) -> str: |
| 51 | mpath = root_dir / module_name.replace('.', os.sep) |
| 52 | if not mpath.is_dir(): |
| 53 | mpath = mpath.with_suffix('.py') |
| 54 | assert mpath.exists(), mpath # just in case |
| 55 | return str(mpath) |
| 56 | |
| 57 | |
| 58 | _pytest.main.search_pypath = search_pypath # ty: ignore[invalid-assignment] |