test_editable_install.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. from __future__ import annotations
  2. import os
  3. import platform
  4. import stat
  5. import subprocess
  6. import sys
  7. from copy import deepcopy
  8. from importlib import import_module
  9. from importlib.machinery import EXTENSION_SUFFIXES
  10. from pathlib import Path
  11. from textwrap import dedent
  12. from typing import Any
  13. from unittest.mock import Mock
  14. from uuid import uuid4
  15. import jaraco.envs
  16. import jaraco.path
  17. import pytest
  18. from path import Path as _Path
  19. from setuptools._importlib import resources as importlib_resources
  20. from setuptools.command.editable_wheel import (
  21. _encode_pth,
  22. _find_namespaces,
  23. _find_package_roots,
  24. _find_virtual_namespaces,
  25. _finder_template,
  26. _LinkTree,
  27. _TopLevelFinder,
  28. editable_wheel,
  29. )
  30. from setuptools.dist import Distribution
  31. from setuptools.extension import Extension
  32. from setuptools.warnings import SetuptoolsDeprecationWarning
  33. from . import contexts, namespaces
  34. from distutils.core import run_setup
  35. @pytest.fixture(params=["strict", "lenient"])
  36. def editable_opts(request):
  37. if request.param == "strict":
  38. return ["--config-settings", "editable-mode=strict"]
  39. return []
  40. EXAMPLE = {
  41. 'pyproject.toml': dedent(
  42. """\
  43. [build-system]
  44. requires = ["setuptools"]
  45. build-backend = "setuptools.build_meta"
  46. [project]
  47. name = "mypkg"
  48. version = "3.14159"
  49. license = {text = "MIT"}
  50. description = "This is a Python package"
  51. dynamic = ["readme"]
  52. classifiers = [
  53. "Development Status :: 5 - Production/Stable",
  54. "Intended Audience :: Developers"
  55. ]
  56. urls = {Homepage = "https://github.com"}
  57. [tool.setuptools]
  58. package-dir = {"" = "src"}
  59. packages = {find = {where = ["src"]}}
  60. license-files = ["LICENSE*"]
  61. [tool.setuptools.dynamic]
  62. readme = {file = "README.rst"}
  63. [tool.distutils.egg_info]
  64. tag-build = ".post0"
  65. """
  66. ),
  67. "MANIFEST.in": dedent(
  68. """\
  69. global-include *.py *.txt
  70. global-exclude *.py[cod]
  71. prune dist
  72. prune build
  73. """
  74. ).strip(),
  75. "README.rst": "This is a ``README``",
  76. "LICENSE.txt": "---- placeholder MIT license ----",
  77. "src": {
  78. "mypkg": {
  79. "__init__.py": dedent(
  80. """\
  81. import sys
  82. from importlib.metadata import PackageNotFoundError, version
  83. try:
  84. __version__ = version(__name__)
  85. except PackageNotFoundError:
  86. __version__ = "unknown"
  87. """
  88. ),
  89. "__main__.py": dedent(
  90. """\
  91. from importlib.resources import read_text
  92. from . import __version__, __name__ as parent
  93. from .mod import x
  94. data = read_text(parent, "data.txt")
  95. print(__version__, data, x)
  96. """
  97. ),
  98. "mod.py": "x = ''",
  99. "data.txt": "Hello World",
  100. }
  101. },
  102. }
  103. SETUP_SCRIPT_STUB = "__import__('setuptools').setup()"
  104. @pytest.mark.xfail(sys.platform == "darwin", reason="pypa/setuptools#4328")
  105. @pytest.mark.parametrize(
  106. "files",
  107. [
  108. {**EXAMPLE, "setup.py": SETUP_SCRIPT_STUB},
  109. EXAMPLE, # No setup.py script
  110. ],
  111. )
  112. def test_editable_with_pyproject(tmp_path, venv, files, editable_opts):
  113. project = tmp_path / "mypkg"
  114. project.mkdir()
  115. jaraco.path.build(files, prefix=project)
  116. cmd = [
  117. "python",
  118. "-m",
  119. "pip",
  120. "install",
  121. "--no-build-isolation", # required to force current version of setuptools
  122. "-e",
  123. str(project),
  124. *editable_opts,
  125. ]
  126. print(venv.run(cmd))
  127. cmd = ["python", "-m", "mypkg"]
  128. assert venv.run(cmd).strip() == "3.14159.post0 Hello World"
  129. (project / "src/mypkg/data.txt").write_text("foobar", encoding="utf-8")
  130. (project / "src/mypkg/mod.py").write_text("x = 42", encoding="utf-8")
  131. assert venv.run(cmd).strip() == "3.14159.post0 foobar 42"
  132. def test_editable_with_flat_layout(tmp_path, venv, editable_opts):
  133. files = {
  134. "mypkg": {
  135. "pyproject.toml": dedent(
  136. """\
  137. [build-system]
  138. requires = ["setuptools", "wheel"]
  139. build-backend = "setuptools.build_meta"
  140. [project]
  141. name = "mypkg"
  142. version = "3.14159"
  143. [tool.setuptools]
  144. packages = ["pkg"]
  145. py-modules = ["mod"]
  146. """
  147. ),
  148. "pkg": {"__init__.py": "a = 4"},
  149. "mod.py": "b = 2",
  150. },
  151. }
  152. jaraco.path.build(files, prefix=tmp_path)
  153. project = tmp_path / "mypkg"
  154. cmd = [
  155. "python",
  156. "-m",
  157. "pip",
  158. "install",
  159. "--no-build-isolation", # required to force current version of setuptools
  160. "-e",
  161. str(project),
  162. *editable_opts,
  163. ]
  164. print(venv.run(cmd))
  165. cmd = ["python", "-c", "import pkg, mod; print(pkg.a, mod.b)"]
  166. assert venv.run(cmd).strip() == "4 2"
  167. def test_editable_with_single_module(tmp_path, venv, editable_opts):
  168. files = {
  169. "mypkg": {
  170. "pyproject.toml": dedent(
  171. """\
  172. [build-system]
  173. requires = ["setuptools", "wheel"]
  174. build-backend = "setuptools.build_meta"
  175. [project]
  176. name = "mod"
  177. version = "3.14159"
  178. [tool.setuptools]
  179. py-modules = ["mod"]
  180. """
  181. ),
  182. "mod.py": "b = 2",
  183. },
  184. }
  185. jaraco.path.build(files, prefix=tmp_path)
  186. project = tmp_path / "mypkg"
  187. cmd = [
  188. "python",
  189. "-m",
  190. "pip",
  191. "install",
  192. "--no-build-isolation", # required to force current version of setuptools
  193. "-e",
  194. str(project),
  195. *editable_opts,
  196. ]
  197. print(venv.run(cmd))
  198. cmd = ["python", "-c", "import mod; print(mod.b)"]
  199. assert venv.run(cmd).strip() == "2"
  200. class TestLegacyNamespaces:
  201. # legacy => pkg_resources.declare_namespace(...) + setup(namespace_packages=...)
  202. def test_nspkg_file_is_unique(self, tmp_path, monkeypatch):
  203. deprecation = pytest.warns(
  204. SetuptoolsDeprecationWarning, match=".*namespace_packages parameter.*"
  205. )
  206. installation_dir = tmp_path / ".installation_dir"
  207. installation_dir.mkdir()
  208. examples = (
  209. "myns.pkgA",
  210. "myns.pkgB",
  211. "myns.n.pkgA",
  212. "myns.n.pkgB",
  213. )
  214. for name in examples:
  215. pkg = namespaces.build_namespace_package(tmp_path, name, version="42")
  216. with deprecation, monkeypatch.context() as ctx:
  217. ctx.chdir(pkg)
  218. dist = run_setup("setup.py", stop_after="config")
  219. cmd = editable_wheel(dist)
  220. cmd.finalize_options()
  221. editable_name = cmd.get_finalized_command("dist_info").name
  222. cmd._install_namespaces(installation_dir, editable_name)
  223. files = list(installation_dir.glob("*-nspkg.pth"))
  224. assert len(files) == len(examples)
  225. @pytest.mark.parametrize(
  226. "impl",
  227. (
  228. "pkg_resources",
  229. # "pkgutil", => does not work
  230. ),
  231. )
  232. @pytest.mark.parametrize("ns", ("myns.n",))
  233. def test_namespace_package_importable(
  234. self, venv, tmp_path, ns, impl, editable_opts
  235. ):
  236. """
  237. Installing two packages sharing the same namespace, one installed
  238. naturally using pip or `--single-version-externally-managed`
  239. and the other installed in editable mode should leave the namespace
  240. intact and both packages reachable by import.
  241. (Ported from test_develop).
  242. """
  243. build_system = """\
  244. [build-system]
  245. requires = ["setuptools"]
  246. build-backend = "setuptools.build_meta"
  247. """
  248. pkg_A = namespaces.build_namespace_package(tmp_path, f"{ns}.pkgA", impl=impl)
  249. pkg_B = namespaces.build_namespace_package(tmp_path, f"{ns}.pkgB", impl=impl)
  250. (pkg_A / "pyproject.toml").write_text(build_system, encoding="utf-8")
  251. (pkg_B / "pyproject.toml").write_text(build_system, encoding="utf-8")
  252. # use pip to install to the target directory
  253. opts = editable_opts[:]
  254. opts.append("--no-build-isolation") # force current version of setuptools
  255. venv.run(["python", "-m", "pip", "install", str(pkg_A), *opts])
  256. venv.run(["python", "-m", "pip", "install", "-e", str(pkg_B), *opts])
  257. venv.run(["python", "-c", f"import {ns}.pkgA; import {ns}.pkgB"])
  258. class TestPep420Namespaces:
  259. def test_namespace_package_importable(self, venv, tmp_path, editable_opts):
  260. """
  261. Installing two packages sharing the same namespace, one installed
  262. normally using pip and the other installed in editable mode
  263. should allow importing both packages.
  264. """
  265. pkg_A = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgA')
  266. pkg_B = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgB')
  267. # use pip to install to the target directory
  268. opts = editable_opts[:]
  269. opts.append("--no-build-isolation") # force current version of setuptools
  270. venv.run(["python", "-m", "pip", "install", str(pkg_A), *opts])
  271. venv.run(["python", "-m", "pip", "install", "-e", str(pkg_B), *opts])
  272. venv.run(["python", "-c", "import myns.n.pkgA; import myns.n.pkgB"])
  273. def test_namespace_created_via_package_dir(self, venv, tmp_path, editable_opts):
  274. """Currently users can create a namespace by tweaking `package_dir`"""
  275. files = {
  276. "pkgA": {
  277. "pyproject.toml": dedent(
  278. """\
  279. [build-system]
  280. requires = ["setuptools", "wheel"]
  281. build-backend = "setuptools.build_meta"
  282. [project]
  283. name = "pkgA"
  284. version = "3.14159"
  285. [tool.setuptools]
  286. package-dir = {"myns.n.pkgA" = "src"}
  287. """
  288. ),
  289. "src": {"__init__.py": "a = 1"},
  290. },
  291. }
  292. jaraco.path.build(files, prefix=tmp_path)
  293. pkg_A = tmp_path / "pkgA"
  294. pkg_B = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgB')
  295. pkg_C = namespaces.build_pep420_namespace_package(tmp_path, 'myns.n.pkgC')
  296. # use pip to install to the target directory
  297. opts = editable_opts[:]
  298. opts.append("--no-build-isolation") # force current version of setuptools
  299. venv.run(["python", "-m", "pip", "install", str(pkg_A), *opts])
  300. venv.run(["python", "-m", "pip", "install", "-e", str(pkg_B), *opts])
  301. venv.run(["python", "-m", "pip", "install", "-e", str(pkg_C), *opts])
  302. venv.run(["python", "-c", "from myns.n import pkgA, pkgB, pkgC"])
  303. def test_namespace_accidental_config_in_lenient_mode(self, venv, tmp_path):
  304. """Sometimes users might specify an ``include`` pattern that ignores parent
  305. packages. In a normal installation this would ignore all modules inside the
  306. parent packages, and make them namespaces (reported in issue #3504),
  307. so the editable mode should preserve this behaviour.
  308. """
  309. files = {
  310. "pkgA": {
  311. "pyproject.toml": dedent(
  312. """\
  313. [build-system]
  314. requires = ["setuptools", "wheel"]
  315. build-backend = "setuptools.build_meta"
  316. [project]
  317. name = "pkgA"
  318. version = "3.14159"
  319. [tool.setuptools]
  320. packages.find.include = ["mypkg.*"]
  321. """
  322. ),
  323. "mypkg": {
  324. "__init__.py": "",
  325. "other.py": "b = 1",
  326. "n": {
  327. "__init__.py": "",
  328. "pkgA.py": "a = 1",
  329. },
  330. },
  331. "MANIFEST.in": EXAMPLE["MANIFEST.in"],
  332. },
  333. }
  334. jaraco.path.build(files, prefix=tmp_path)
  335. pkg_A = tmp_path / "pkgA"
  336. # use pip to install to the target directory
  337. opts = ["--no-build-isolation"] # force current version of setuptools
  338. venv.run(["python", "-m", "pip", "-v", "install", "-e", str(pkg_A), *opts])
  339. out = venv.run(["python", "-c", "from mypkg.n import pkgA; print(pkgA.a)"])
  340. assert out.strip() == "1"
  341. cmd = """\
  342. try:
  343. import mypkg.other
  344. except ImportError:
  345. print("mypkg.other not defined")
  346. """
  347. out = venv.run(["python", "-c", dedent(cmd)])
  348. assert "mypkg.other not defined" in out
  349. def test_editable_with_prefix(tmp_path, sample_project, editable_opts):
  350. """
  351. Editable install to a prefix should be discoverable.
  352. """
  353. prefix = tmp_path / 'prefix'
  354. # figure out where pip will likely install the package
  355. site_packages_all = [
  356. prefix / Path(path).relative_to(sys.prefix)
  357. for path in sys.path
  358. if 'site-packages' in path and path.startswith(sys.prefix)
  359. ]
  360. for sp in site_packages_all:
  361. sp.mkdir(parents=True)
  362. # install workaround
  363. _addsitedirs(site_packages_all)
  364. env = dict(os.environ, PYTHONPATH=os.pathsep.join(map(str, site_packages_all)))
  365. cmd = [
  366. sys.executable,
  367. '-m',
  368. 'pip',
  369. 'install',
  370. '--editable',
  371. str(sample_project),
  372. '--prefix',
  373. str(prefix),
  374. '--no-build-isolation',
  375. *editable_opts,
  376. ]
  377. subprocess.check_call(cmd, env=env)
  378. # now run 'sample' with the prefix on the PYTHONPATH
  379. bin = 'Scripts' if platform.system() == 'Windows' else 'bin'
  380. exe = prefix / bin / 'sample'
  381. subprocess.check_call([exe], env=env)
  382. class TestFinderTemplate:
  383. """This test focus in getting a particular implementation detail right.
  384. If at some point in time the implementation is changed for something different,
  385. this test can be modified or even excluded.
  386. """
  387. def install_finder(self, finder):
  388. loc = {}
  389. exec(finder, loc, loc)
  390. loc["install"]()
  391. def test_packages(self, tmp_path):
  392. files = {
  393. "src1": {
  394. "pkg1": {
  395. "__init__.py": "",
  396. "subpkg": {"mod1.py": "a = 42"},
  397. },
  398. },
  399. "src2": {"mod2.py": "a = 43"},
  400. }
  401. jaraco.path.build(files, prefix=tmp_path)
  402. mapping = {
  403. "pkg1": str(tmp_path / "src1/pkg1"),
  404. "mod2": str(tmp_path / "src2/mod2"),
  405. }
  406. template = _finder_template(str(uuid4()), mapping, {})
  407. with contexts.save_paths(), contexts.save_sys_modules():
  408. for mod in ("pkg1", "pkg1.subpkg", "pkg1.subpkg.mod1", "mod2"):
  409. sys.modules.pop(mod, None)
  410. self.install_finder(template)
  411. mod1 = import_module("pkg1.subpkg.mod1")
  412. mod2 = import_module("mod2")
  413. subpkg = import_module("pkg1.subpkg")
  414. assert mod1.a == 42
  415. assert mod2.a == 43
  416. expected = str((tmp_path / "src1/pkg1/subpkg").resolve())
  417. assert_path(subpkg, expected)
  418. def test_namespace(self, tmp_path):
  419. files = {"pkg": {"__init__.py": "a = 13", "text.txt": "abc"}}
  420. jaraco.path.build(files, prefix=tmp_path)
  421. mapping = {"ns.othername": str(tmp_path / "pkg")}
  422. namespaces = {"ns": []}
  423. template = _finder_template(str(uuid4()), mapping, namespaces)
  424. with contexts.save_paths(), contexts.save_sys_modules():
  425. for mod in ("ns", "ns.othername"):
  426. sys.modules.pop(mod, None)
  427. self.install_finder(template)
  428. pkg = import_module("ns.othername")
  429. text = importlib_resources.files(pkg) / "text.txt"
  430. expected = str((tmp_path / "pkg").resolve())
  431. assert_path(pkg, expected)
  432. assert pkg.a == 13
  433. # Make sure resources can also be found
  434. assert text.read_text(encoding="utf-8") == "abc"
  435. def test_combine_namespaces(self, tmp_path):
  436. files = {
  437. "src1": {"ns": {"pkg1": {"__init__.py": "a = 13"}}},
  438. "src2": {"ns": {"mod2.py": "b = 37"}},
  439. }
  440. jaraco.path.build(files, prefix=tmp_path)
  441. mapping = {
  442. "ns.pkgA": str(tmp_path / "src1/ns/pkg1"),
  443. "ns": str(tmp_path / "src2/ns"),
  444. }
  445. namespaces_ = {"ns": [str(tmp_path / "src1"), str(tmp_path / "src2")]}
  446. template = _finder_template(str(uuid4()), mapping, namespaces_)
  447. with contexts.save_paths(), contexts.save_sys_modules():
  448. for mod in ("ns", "ns.pkgA", "ns.mod2"):
  449. sys.modules.pop(mod, None)
  450. self.install_finder(template)
  451. pkgA = import_module("ns.pkgA")
  452. mod2 = import_module("ns.mod2")
  453. expected = str((tmp_path / "src1/ns/pkg1").resolve())
  454. assert_path(pkgA, expected)
  455. assert pkgA.a == 13
  456. assert mod2.b == 37
  457. def test_combine_namespaces_nested(self, tmp_path):
  458. """
  459. Users may attempt to combine namespace packages in a nested way via
  460. ``package_dir`` as shown in pypa/setuptools#4248.
  461. """
  462. files = {
  463. "src": {"my_package": {"my_module.py": "a = 13"}},
  464. "src2": {"my_package2": {"my_module2.py": "b = 37"}},
  465. }
  466. stack = jaraco.path.DirectoryStack()
  467. with stack.context(tmp_path):
  468. jaraco.path.build(files)
  469. attrs = {
  470. "script_name": "%PEP 517%",
  471. "package_dir": {
  472. "different_name": "src/my_package",
  473. "different_name.subpkg": "src2/my_package2",
  474. },
  475. "packages": ["different_name", "different_name.subpkg"],
  476. }
  477. dist = Distribution(attrs)
  478. finder = _TopLevelFinder(dist, str(uuid4()))
  479. code = next(v for k, v in finder.get_implementation() if k.endswith(".py"))
  480. with contexts.save_paths(), contexts.save_sys_modules():
  481. for mod in attrs["packages"]:
  482. sys.modules.pop(mod, None)
  483. self.install_finder(code)
  484. mod1 = import_module("different_name.my_module")
  485. mod2 = import_module("different_name.subpkg.my_module2")
  486. expected = str((tmp_path / "src/my_package/my_module.py").resolve())
  487. assert str(Path(mod1.__file__).resolve()) == expected
  488. expected = str((tmp_path / "src2/my_package2/my_module2.py").resolve())
  489. assert str(Path(mod2.__file__).resolve()) == expected
  490. assert mod1.a == 13
  491. assert mod2.b == 37
  492. def test_dynamic_path_computation(self, tmp_path):
  493. # Follows the example in PEP 420
  494. files = {
  495. "project1": {"parent": {"child": {"one.py": "x = 1"}}},
  496. "project2": {"parent": {"child": {"two.py": "x = 2"}}},
  497. "project3": {"parent": {"child": {"three.py": "x = 3"}}},
  498. }
  499. jaraco.path.build(files, prefix=tmp_path)
  500. mapping = {}
  501. namespaces_ = {"parent": [str(tmp_path / "project1/parent")]}
  502. template = _finder_template(str(uuid4()), mapping, namespaces_)
  503. mods = (f"parent.child.{name}" for name in ("one", "two", "three"))
  504. with contexts.save_paths(), contexts.save_sys_modules():
  505. for mod in ("parent", "parent.child", "parent.child", *mods):
  506. sys.modules.pop(mod, None)
  507. self.install_finder(template)
  508. one = import_module("parent.child.one")
  509. assert one.x == 1
  510. with pytest.raises(ImportError):
  511. import_module("parent.child.two")
  512. sys.path.append(str(tmp_path / "project2"))
  513. two = import_module("parent.child.two")
  514. assert two.x == 2
  515. with pytest.raises(ImportError):
  516. import_module("parent.child.three")
  517. sys.path.append(str(tmp_path / "project3"))
  518. three = import_module("parent.child.three")
  519. assert three.x == 3
  520. def test_no_recursion(self, tmp_path):
  521. # See issue #3550
  522. files = {
  523. "pkg": {
  524. "__init__.py": "from . import pkg",
  525. },
  526. }
  527. jaraco.path.build(files, prefix=tmp_path)
  528. mapping = {
  529. "pkg": str(tmp_path / "pkg"),
  530. }
  531. template = _finder_template(str(uuid4()), mapping, {})
  532. with contexts.save_paths(), contexts.save_sys_modules():
  533. sys.modules.pop("pkg", None)
  534. self.install_finder(template)
  535. with pytest.raises(ImportError, match="pkg"):
  536. import_module("pkg")
  537. def test_similar_name(self, tmp_path):
  538. files = {
  539. "foo": {
  540. "__init__.py": "",
  541. "bar": {
  542. "__init__.py": "",
  543. },
  544. },
  545. }
  546. jaraco.path.build(files, prefix=tmp_path)
  547. mapping = {
  548. "foo": str(tmp_path / "foo"),
  549. }
  550. template = _finder_template(str(uuid4()), mapping, {})
  551. with contexts.save_paths(), contexts.save_sys_modules():
  552. sys.modules.pop("foo", None)
  553. sys.modules.pop("foo.bar", None)
  554. self.install_finder(template)
  555. with pytest.raises(ImportError, match="foobar"):
  556. import_module("foobar")
  557. def test_case_sensitivity(self, tmp_path):
  558. files = {
  559. "foo": {
  560. "__init__.py": "",
  561. "lowercase.py": "x = 1",
  562. "bar": {
  563. "__init__.py": "",
  564. "lowercase.py": "x = 2",
  565. },
  566. },
  567. }
  568. jaraco.path.build(files, prefix=tmp_path)
  569. mapping = {
  570. "foo": str(tmp_path / "foo"),
  571. }
  572. template = _finder_template(str(uuid4()), mapping, {})
  573. with contexts.save_paths(), contexts.save_sys_modules():
  574. sys.modules.pop("foo", None)
  575. self.install_finder(template)
  576. with pytest.raises(ImportError, match="'FOO'"):
  577. import_module("FOO")
  578. with pytest.raises(ImportError, match="'foo\\.LOWERCASE'"):
  579. import_module("foo.LOWERCASE")
  580. with pytest.raises(ImportError, match="'foo\\.bar\\.Lowercase'"):
  581. import_module("foo.bar.Lowercase")
  582. with pytest.raises(ImportError, match="'foo\\.BAR'"):
  583. import_module("foo.BAR.lowercase")
  584. with pytest.raises(ImportError, match="'FOO'"):
  585. import_module("FOO.bar.lowercase")
  586. mod = import_module("foo.lowercase")
  587. assert mod.x == 1
  588. mod = import_module("foo.bar.lowercase")
  589. assert mod.x == 2
  590. def test_namespace_case_sensitivity(self, tmp_path):
  591. files = {
  592. "pkg": {
  593. "__init__.py": "a = 13",
  594. "foo": {
  595. "__init__.py": "b = 37",
  596. "bar.py": "c = 42",
  597. },
  598. },
  599. }
  600. jaraco.path.build(files, prefix=tmp_path)
  601. mapping = {"ns.othername": str(tmp_path / "pkg")}
  602. namespaces = {"ns": []}
  603. template = _finder_template(str(uuid4()), mapping, namespaces)
  604. with contexts.save_paths(), contexts.save_sys_modules():
  605. for mod in ("ns", "ns.othername"):
  606. sys.modules.pop(mod, None)
  607. self.install_finder(template)
  608. pkg = import_module("ns.othername")
  609. expected = str((tmp_path / "pkg").resolve())
  610. assert_path(pkg, expected)
  611. assert pkg.a == 13
  612. foo = import_module("ns.othername.foo")
  613. assert foo.b == 37
  614. bar = import_module("ns.othername.foo.bar")
  615. assert bar.c == 42
  616. with pytest.raises(ImportError, match="'NS'"):
  617. import_module("NS.othername.foo")
  618. with pytest.raises(ImportError, match="'ns\\.othername\\.FOO\\'"):
  619. import_module("ns.othername.FOO")
  620. with pytest.raises(ImportError, match="'ns\\.othername\\.foo\\.BAR\\'"):
  621. import_module("ns.othername.foo.BAR")
  622. def test_intermediate_packages(self, tmp_path):
  623. """
  624. The finder should not import ``fullname`` if the intermediate segments
  625. don't exist (see pypa/setuptools#4019).
  626. """
  627. files = {
  628. "src": {
  629. "mypkg": {
  630. "__init__.py": "",
  631. "config.py": "a = 13",
  632. "helloworld.py": "b = 13",
  633. "components": {
  634. "config.py": "a = 37",
  635. },
  636. },
  637. }
  638. }
  639. jaraco.path.build(files, prefix=tmp_path)
  640. mapping = {"mypkg": str(tmp_path / "src/mypkg")}
  641. template = _finder_template(str(uuid4()), mapping, {})
  642. with contexts.save_paths(), contexts.save_sys_modules():
  643. for mod in (
  644. "mypkg",
  645. "mypkg.config",
  646. "mypkg.helloworld",
  647. "mypkg.components",
  648. "mypkg.components.config",
  649. "mypkg.components.helloworld",
  650. ):
  651. sys.modules.pop(mod, None)
  652. self.install_finder(template)
  653. config = import_module("mypkg.components.config")
  654. assert config.a == 37
  655. helloworld = import_module("mypkg.helloworld")
  656. assert helloworld.b == 13
  657. with pytest.raises(ImportError):
  658. import_module("mypkg.components.helloworld")
  659. def test_pkg_roots(tmp_path):
  660. """This test focus in getting a particular implementation detail right.
  661. If at some point in time the implementation is changed for something different,
  662. this test can be modified or even excluded.
  663. """
  664. files = {
  665. "a": {"b": {"__init__.py": "ab = 1"}, "__init__.py": "a = 1"},
  666. "d": {"__init__.py": "d = 1", "e": {"__init__.py": "de = 1"}},
  667. "f": {"g": {"h": {"__init__.py": "fgh = 1"}}},
  668. "other": {"__init__.py": "abc = 1"},
  669. "another": {"__init__.py": "abcxyz = 1"},
  670. "yet_another": {"__init__.py": "mnopq = 1"},
  671. }
  672. jaraco.path.build(files, prefix=tmp_path)
  673. package_dir = {
  674. "a.b.c": "other",
  675. "a.b.c.x.y.z": "another",
  676. "m.n.o.p.q": "yet_another",
  677. }
  678. packages = [
  679. "a",
  680. "a.b",
  681. "a.b.c",
  682. "a.b.c.x.y",
  683. "a.b.c.x.y.z",
  684. "d",
  685. "d.e",
  686. "f",
  687. "f.g",
  688. "f.g.h",
  689. "m.n.o.p.q",
  690. ]
  691. roots = _find_package_roots(packages, package_dir, tmp_path)
  692. assert roots == {
  693. "a": str(tmp_path / "a"),
  694. "a.b.c": str(tmp_path / "other"),
  695. "a.b.c.x.y.z": str(tmp_path / "another"),
  696. "d": str(tmp_path / "d"),
  697. "f": str(tmp_path / "f"),
  698. "m.n.o.p.q": str(tmp_path / "yet_another"),
  699. }
  700. ns = set(dict(_find_namespaces(packages, roots)))
  701. assert ns == {"f", "f.g"}
  702. ns = set(_find_virtual_namespaces(roots))
  703. assert ns == {"a.b", "a.b.c.x", "a.b.c.x.y", "m", "m.n", "m.n.o", "m.n.o.p"}
  704. class TestOverallBehaviour:
  705. PYPROJECT = """\
  706. [build-system]
  707. requires = ["setuptools"]
  708. build-backend = "setuptools.build_meta"
  709. [project]
  710. name = "mypkg"
  711. version = "3.14159"
  712. """
  713. # Any: Would need a TypedDict. Keep it simple for tests
  714. FLAT_LAYOUT: dict[str, Any] = {
  715. "pyproject.toml": dedent(PYPROJECT),
  716. "MANIFEST.in": EXAMPLE["MANIFEST.in"],
  717. "otherfile.py": "",
  718. "mypkg": {
  719. "__init__.py": "",
  720. "mod1.py": "var = 42",
  721. "subpackage": {
  722. "__init__.py": "",
  723. "mod2.py": "var = 13",
  724. "resource_file.txt": "resource 39",
  725. },
  726. },
  727. }
  728. EXAMPLES = {
  729. "flat-layout": FLAT_LAYOUT,
  730. "src-layout": {
  731. "pyproject.toml": dedent(PYPROJECT),
  732. "MANIFEST.in": EXAMPLE["MANIFEST.in"],
  733. "otherfile.py": "",
  734. "src": {"mypkg": FLAT_LAYOUT["mypkg"]},
  735. },
  736. "custom-layout": {
  737. "pyproject.toml": dedent(PYPROJECT)
  738. + dedent(
  739. """\
  740. [tool.setuptools]
  741. packages = ["mypkg", "mypkg.subpackage"]
  742. [tool.setuptools.package-dir]
  743. "mypkg.subpackage" = "other"
  744. """
  745. ),
  746. "MANIFEST.in": EXAMPLE["MANIFEST.in"],
  747. "otherfile.py": "",
  748. "mypkg": {
  749. "__init__.py": "",
  750. "mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"],
  751. },
  752. "other": FLAT_LAYOUT["mypkg"]["subpackage"],
  753. },
  754. "namespace": {
  755. "pyproject.toml": dedent(PYPROJECT),
  756. "MANIFEST.in": EXAMPLE["MANIFEST.in"],
  757. "otherfile.py": "",
  758. "src": {
  759. "mypkg": {
  760. "mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"],
  761. "subpackage": FLAT_LAYOUT["mypkg"]["subpackage"],
  762. },
  763. },
  764. },
  765. }
  766. @pytest.mark.xfail(sys.platform == "darwin", reason="pypa/setuptools#4328")
  767. @pytest.mark.parametrize("layout", EXAMPLES.keys())
  768. def test_editable_install(self, tmp_path, venv, layout, editable_opts):
  769. project, _ = install_project(
  770. "mypkg", venv, tmp_path, self.EXAMPLES[layout], *editable_opts
  771. )
  772. # Ensure stray files are not importable
  773. cmd_import_error = """\
  774. try:
  775. import otherfile
  776. except ImportError as ex:
  777. print(ex)
  778. """
  779. out = venv.run(["python", "-c", dedent(cmd_import_error)])
  780. assert "No module named 'otherfile'" in out
  781. # Ensure the modules are importable
  782. cmd_get_vars = """\
  783. import mypkg, mypkg.mod1, mypkg.subpackage.mod2
  784. print(mypkg.mod1.var, mypkg.subpackage.mod2.var)
  785. """
  786. out = venv.run(["python", "-c", dedent(cmd_get_vars)])
  787. assert "42 13" in out
  788. # Ensure resources are reachable
  789. cmd_get_resource = """\
  790. import mypkg.subpackage
  791. from setuptools._importlib import resources as importlib_resources
  792. text = importlib_resources.files(mypkg.subpackage) / "resource_file.txt"
  793. print(text.read_text(encoding="utf-8"))
  794. """
  795. out = venv.run(["python", "-c", dedent(cmd_get_resource)])
  796. assert "resource 39" in out
  797. # Ensure files are editable
  798. mod1 = next(project.glob("**/mod1.py"))
  799. mod2 = next(project.glob("**/mod2.py"))
  800. resource_file = next(project.glob("**/resource_file.txt"))
  801. mod1.write_text("var = 17", encoding="utf-8")
  802. mod2.write_text("var = 781", encoding="utf-8")
  803. resource_file.write_text("resource 374", encoding="utf-8")
  804. out = venv.run(["python", "-c", dedent(cmd_get_vars)])
  805. assert "42 13" not in out
  806. assert "17 781" in out
  807. out = venv.run(["python", "-c", dedent(cmd_get_resource)])
  808. assert "resource 39" not in out
  809. assert "resource 374" in out
  810. class TestLinkTree:
  811. FILES = deepcopy(TestOverallBehaviour.EXAMPLES["src-layout"])
  812. FILES["pyproject.toml"] += dedent(
  813. """\
  814. [tool.setuptools]
  815. # Temporary workaround: both `include-package-data` and `package-data` configs
  816. # can be removed after #3260 is fixed.
  817. include-package-data = false
  818. package-data = {"*" = ["*.txt"]}
  819. [tool.setuptools.packages.find]
  820. where = ["src"]
  821. exclude = ["*.subpackage*"]
  822. """
  823. )
  824. FILES["src"]["mypkg"]["resource.not_in_manifest"] = "abc"
  825. def test_generated_tree(self, tmp_path):
  826. jaraco.path.build(self.FILES, prefix=tmp_path)
  827. with _Path(tmp_path):
  828. name = "mypkg-3.14159"
  829. dist = Distribution({"script_name": "%PEP 517%"})
  830. dist.parse_config_files()
  831. wheel = Mock()
  832. aux = tmp_path / ".aux"
  833. build = tmp_path / ".build"
  834. aux.mkdir()
  835. build.mkdir()
  836. build_py = dist.get_command_obj("build_py")
  837. build_py.editable_mode = True
  838. build_py.build_lib = str(build)
  839. build_py.ensure_finalized()
  840. outputs = build_py.get_outputs()
  841. output_mapping = build_py.get_output_mapping()
  842. make_tree = _LinkTree(dist, name, aux, build)
  843. make_tree(wheel, outputs, output_mapping)
  844. mod1 = next(aux.glob("**/mod1.py"))
  845. expected = tmp_path / "src/mypkg/mod1.py"
  846. assert_link_to(mod1, expected)
  847. assert next(aux.glob("**/subpackage"), None) is None
  848. assert next(aux.glob("**/mod2.py"), None) is None
  849. assert next(aux.glob("**/resource_file.txt"), None) is None
  850. assert next(aux.glob("**/resource.not_in_manifest"), None) is None
  851. def test_strict_install(self, tmp_path, venv):
  852. opts = ["--config-settings", "editable-mode=strict"]
  853. install_project("mypkg", venv, tmp_path, self.FILES, *opts)
  854. out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"])
  855. assert "42" in out
  856. # Ensure packages excluded from distribution are not importable
  857. cmd_import_error = """\
  858. try:
  859. from mypkg import subpackage
  860. except ImportError as ex:
  861. print(ex)
  862. """
  863. out = venv.run(["python", "-c", dedent(cmd_import_error)])
  864. assert "cannot import name 'subpackage'" in out
  865. # Ensure resource files excluded from distribution are not reachable
  866. cmd_get_resource = """\
  867. import mypkg
  868. from setuptools._importlib import resources as importlib_resources
  869. try:
  870. text = importlib_resources.files(mypkg) / "resource.not_in_manifest"
  871. print(text.read_text(encoding="utf-8"))
  872. except FileNotFoundError as ex:
  873. print(ex)
  874. """
  875. out = venv.run(["python", "-c", dedent(cmd_get_resource)])
  876. assert "No such file or directory" in out
  877. assert "resource.not_in_manifest" in out
  878. @pytest.mark.filterwarnings("ignore:.*compat.*:setuptools.SetuptoolsDeprecationWarning")
  879. def test_compat_install(tmp_path, venv):
  880. # TODO: Remove `compat` after Dec/2022.
  881. opts = ["--config-settings", "editable-mode=compat"]
  882. files = TestOverallBehaviour.EXAMPLES["custom-layout"]
  883. install_project("mypkg", venv, tmp_path, files, *opts)
  884. out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"])
  885. assert "42" in out
  886. expected_path = comparable_path(str(tmp_path))
  887. # Compatible behaviour will make spurious modules and excluded
  888. # files importable directly from the original path
  889. for cmd in (
  890. "import otherfile; print(otherfile)",
  891. "import other; print(other)",
  892. "import mypkg; print(mypkg)",
  893. ):
  894. out = comparable_path(venv.run(["python", "-c", cmd]))
  895. assert expected_path in out
  896. # Compatible behaviour will not consider custom mappings
  897. cmd = """\
  898. try:
  899. from mypkg import subpackage;
  900. except ImportError as ex:
  901. print(ex)
  902. """
  903. out = venv.run(["python", "-c", dedent(cmd)])
  904. assert "cannot import name 'subpackage'" in out
  905. @pytest.mark.uses_network
  906. def test_pbr_integration(pbr_package, venv, editable_opts):
  907. """Ensure editable installs work with pbr, issue #3500"""
  908. cmd = [
  909. 'python',
  910. '-m',
  911. 'pip',
  912. '-v',
  913. 'install',
  914. '--editable',
  915. pbr_package,
  916. *editable_opts,
  917. ]
  918. venv.run(cmd, stderr=subprocess.STDOUT)
  919. out = venv.run(["python", "-c", "import mypkg.hello"])
  920. assert "Hello world!" in out
  921. class TestCustomBuildPy:
  922. """
  923. Issue #3501 indicates that some plugins/customizations might rely on:
  924. 1. ``build_py`` not running
  925. 2. ``build_py`` always copying files to ``build_lib``
  926. During the transition period setuptools should prevent potential errors from
  927. happening due to those assumptions.
  928. """
  929. # TODO: Remove tests after _run_build_steps is removed.
  930. FILES = {
  931. **TestOverallBehaviour.EXAMPLES["flat-layout"],
  932. "setup.py": dedent(
  933. """\
  934. import pathlib
  935. from setuptools import setup
  936. from setuptools.command.build_py import build_py as orig
  937. class my_build_py(orig):
  938. def run(self):
  939. super().run()
  940. raise ValueError("TEST_RAISE")
  941. setup(cmdclass={"build_py": my_build_py})
  942. """
  943. ),
  944. }
  945. def test_safeguarded_from_errors(self, tmp_path, venv):
  946. """Ensure that errors in custom build_py are reported as warnings"""
  947. # Warnings should show up
  948. _, out = install_project("mypkg", venv, tmp_path, self.FILES)
  949. assert "SetuptoolsDeprecationWarning" in out
  950. assert "ValueError: TEST_RAISE" in out
  951. # but installation should be successful
  952. out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"])
  953. assert "42" in out
  954. class TestCustomBuildWheel:
  955. def install_custom_build_wheel(self, dist):
  956. bdist_wheel_cls = dist.get_command_class("bdist_wheel")
  957. class MyBdistWheel(bdist_wheel_cls):
  958. def get_tag(self):
  959. # In issue #3513, we can see that some extensions may try to access
  960. # the `plat_name` property in bdist_wheel
  961. if self.plat_name.startswith("macosx-"):
  962. _ = "macOS platform"
  963. return super().get_tag()
  964. dist.cmdclass["bdist_wheel"] = MyBdistWheel
  965. def test_access_plat_name(self, tmpdir_cwd):
  966. # Even when a custom bdist_wheel tries to access plat_name the build should
  967. # be successful
  968. jaraco.path.build({"module.py": "x = 42"})
  969. dist = Distribution()
  970. dist.script_name = "setup.py"
  971. dist.set_defaults()
  972. self.install_custom_build_wheel(dist)
  973. cmd = editable_wheel(dist)
  974. cmd.ensure_finalized()
  975. cmd.run()
  976. wheel_file = str(next(Path().glob('dist/*.whl')))
  977. assert "editable" in wheel_file
  978. class TestCustomBuildExt:
  979. def install_custom_build_ext_distutils(self, dist):
  980. from distutils.command.build_ext import build_ext as build_ext_cls
  981. class MyBuildExt(build_ext_cls):
  982. pass
  983. dist.cmdclass["build_ext"] = MyBuildExt
  984. @pytest.mark.skipif(
  985. sys.platform != "linux", reason="compilers may fail without correct setup"
  986. )
  987. def test_distutils_leave_inplace_files(self, tmpdir_cwd):
  988. jaraco.path.build({"module.c": ""})
  989. attrs = {
  990. "ext_modules": [Extension("module", ["module.c"])],
  991. }
  992. dist = Distribution(attrs)
  993. dist.script_name = "setup.py"
  994. dist.set_defaults()
  995. self.install_custom_build_ext_distutils(dist)
  996. cmd = editable_wheel(dist)
  997. cmd.ensure_finalized()
  998. cmd.run()
  999. wheel_file = str(next(Path().glob('dist/*.whl')))
  1000. assert "editable" in wheel_file
  1001. files = [p for p in Path().glob("module.*") if p.suffix != ".c"]
  1002. assert len(files) == 1
  1003. name = files[0].name
  1004. assert any(name.endswith(ext) for ext in EXTENSION_SUFFIXES)
  1005. def test_debugging_tips(tmpdir_cwd, monkeypatch):
  1006. """Make sure to display useful debugging tips to the user."""
  1007. jaraco.path.build({"module.py": "x = 42"})
  1008. dist = Distribution()
  1009. dist.script_name = "setup.py"
  1010. dist.set_defaults()
  1011. cmd = editable_wheel(dist)
  1012. cmd.ensure_finalized()
  1013. SimulatedErr = type("SimulatedErr", (Exception,), {})
  1014. simulated_failure = Mock(side_effect=SimulatedErr())
  1015. monkeypatch.setattr(cmd, "get_finalized_command", simulated_failure)
  1016. with pytest.raises(SimulatedErr) as ctx:
  1017. cmd.run()
  1018. assert any('debugging-tips' in note for note in ctx.value.__notes__)
  1019. @pytest.mark.filterwarnings("error")
  1020. def test_encode_pth():
  1021. """Ensure _encode_pth function does not produce encoding warnings"""
  1022. content = _encode_pth("tkmilan_ç_utf8") # no warnings (would be turned into errors)
  1023. assert isinstance(content, bytes)
  1024. def install_project(name, venv, tmp_path, files, *opts):
  1025. project = tmp_path / name
  1026. project.mkdir()
  1027. jaraco.path.build(files, prefix=project)
  1028. opts = [*opts, "--no-build-isolation"] # force current version of setuptools
  1029. out = venv.run(
  1030. ["python", "-m", "pip", "-v", "install", "-e", str(project), *opts],
  1031. stderr=subprocess.STDOUT,
  1032. )
  1033. return project, out
  1034. def _addsitedirs(new_dirs):
  1035. """To use this function, it is necessary to insert new_dir in front of sys.path.
  1036. The Python process will try to import a ``sitecustomize`` module on startup.
  1037. If we manipulate sys.path/PYTHONPATH, we can force it to run our code,
  1038. which invokes ``addsitedir`` and ensure ``.pth`` files are loaded.
  1039. """
  1040. content = '\n'.join(
  1041. ("import site",)
  1042. + tuple(f"site.addsitedir({os.fspath(new_dir)!r})" for new_dir in new_dirs)
  1043. )
  1044. (new_dirs[0] / "sitecustomize.py").write_text(content, encoding="utf-8")
  1045. # ---- Assertion Helpers ----
  1046. def assert_path(pkg, expected):
  1047. # __path__ is not guaranteed to exist, so we have to account for that
  1048. if pkg.__path__:
  1049. path = next(iter(pkg.__path__), None)
  1050. if path:
  1051. assert str(Path(path).resolve()) == expected
  1052. def assert_link_to(file: Path, other: Path) -> None:
  1053. if file.is_symlink():
  1054. assert str(file.resolve()) == str(other.resolve())
  1055. else:
  1056. file_stat = file.stat()
  1057. other_stat = other.stat()
  1058. assert file_stat[stat.ST_INO] == other_stat[stat.ST_INO]
  1059. assert file_stat[stat.ST_DEV] == other_stat[stat.ST_DEV]
  1060. def comparable_path(str_with_path: str) -> str:
  1061. return str_with_path.lower().replace(os.sep, "/").replace("//", "/")