test_circular_imports.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. """Tests for circular imports in all local packages and modules.
  2. This ensures all internal packages can be imported right away without
  3. any need to import some other module before doing so.
  4. This module is based on the idea that pytest uses for self-testing:
  5. * https://github.com/sanitizers/octomachinery/blob/be18b54/tests/circular_imports_test.py # noqa: E501
  6. * https://github.com/pytest-dev/pytest/blob/d18c75b/testing/test_meta.py
  7. * https://twitter.com/codewithanthony/status/1229445110510735361
  8. """
  9. from __future__ import annotations
  10. import os
  11. import pkgutil
  12. import subprocess
  13. import sys
  14. from itertools import chain
  15. from pathlib import Path
  16. from types import ModuleType
  17. from typing import Generator
  18. import pytest
  19. import multidict
  20. def _find_all_importables(pkg: ModuleType) -> list[str]:
  21. """Find all importables in the project.
  22. Return them in order.
  23. """
  24. return sorted(
  25. set(
  26. chain.from_iterable(
  27. _discover_path_importables(Path(p), pkg.__name__) for p in pkg.__path__
  28. ),
  29. ),
  30. )
  31. def _discover_path_importables(
  32. pkg_pth: Path,
  33. pkg_name: str,
  34. ) -> Generator[str, None, None]:
  35. """Yield all importables under a given path and package."""
  36. yield pkg_name
  37. for dir_path, _d, file_names in os.walk(pkg_pth):
  38. pkg_dir_path = Path(dir_path)
  39. if pkg_dir_path.parts[-1] == "__pycache__":
  40. continue
  41. if all(Path(_).suffix != ".py" for _ in file_names):
  42. continue
  43. rel_pt = pkg_dir_path.relative_to(pkg_pth)
  44. pkg_pref = ".".join((pkg_name,) + rel_pt.parts)
  45. yield from (
  46. pkg_path
  47. for _, pkg_path, _ in pkgutil.walk_packages(
  48. (str(pkg_dir_path),),
  49. prefix=f"{pkg_pref}.",
  50. )
  51. )
  52. @pytest.fixture(params=_find_all_importables(multidict))
  53. def import_path(request: pytest.FixtureRequest) -> str:
  54. """Return an importable from the multidict package."""
  55. importable_module: str = request.param
  56. if importable_module == "multidict._multidict":
  57. request.applymarker(pytest.mark.c_extension)
  58. return importable_module
  59. def test_no_warnings(import_path: str) -> None:
  60. """Verify that importing modules and packages doesn't explode.
  61. This is seeking for any import errors including ones caused
  62. by circular imports.
  63. """
  64. imp_cmd = (
  65. # fmt: off
  66. sys.executable,
  67. "-I",
  68. "-W", "error",
  69. "-c", f"import {import_path!s}",
  70. # fmt: on
  71. )
  72. subprocess.check_call(imp_cmd)
  73. @pytest.mark.c_extension
  74. def test_c_extension_preferred_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
  75. """Verify that the C-extension is exposed by default."""
  76. monkeypatch.delenv("MULTIDICT_NO_EXTENSIONS", raising=False)
  77. imp_cmd = (
  78. # fmt: off
  79. sys.executable,
  80. "-I",
  81. "-W", "error",
  82. "-c", "import multidict; raise SystemExit(int("
  83. "multidict.istr.__module__ != 'multidict._multidict' "
  84. "or multidict.USE_EXTENSIONS is not True))",
  85. # fmt: on
  86. )
  87. subprocess.check_call(imp_cmd)