test_easy_install.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. # -*- coding: utf-8 -*-
  2. """Easy install Tests
  3. """
  4. from __future__ import absolute_import
  5. import sys
  6. import os
  7. import tempfile
  8. import site
  9. import contextlib
  10. import tarfile
  11. import logging
  12. import itertools
  13. import distutils.errors
  14. import io
  15. from setuptools.extern.six.moves import urllib
  16. import time
  17. import pytest
  18. try:
  19. from unittest import mock
  20. except ImportError:
  21. import mock
  22. from setuptools import sandbox
  23. from setuptools.sandbox import run_setup
  24. import setuptools.command.easy_install as ei
  25. from setuptools.command.easy_install import PthDistributions
  26. from setuptools.command import easy_install as easy_install_pkg
  27. from setuptools.dist import Distribution
  28. from pkg_resources import working_set
  29. from pkg_resources import Distribution as PRDistribution
  30. import setuptools.tests.server
  31. import pkg_resources
  32. from .py26compat import tarfile_open
  33. from . import contexts
  34. from .textwrap import DALS
  35. class FakeDist(object):
  36. def get_entry_map(self, group):
  37. if group != 'console_scripts':
  38. return {}
  39. return {'name': 'ep'}
  40. def as_requirement(self):
  41. return 'spec'
  42. SETUP_PY = DALS("""
  43. from setuptools import setup
  44. setup(name='foo')
  45. """)
  46. class TestEasyInstallTest:
  47. def test_install_site_py(self, tmpdir):
  48. dist = Distribution()
  49. cmd = ei.easy_install(dist)
  50. cmd.sitepy_installed = False
  51. cmd.install_dir = str(tmpdir)
  52. cmd.install_site_py()
  53. assert (tmpdir / 'site.py').exists()
  54. def test_get_script_args(self):
  55. header = ei.CommandSpec.best().from_environment().as_header()
  56. expected = header + DALS("""
  57. # EASY-INSTALL-ENTRY-SCRIPT: 'spec','console_scripts','name'
  58. __requires__ = 'spec'
  59. import sys
  60. from pkg_resources import load_entry_point
  61. if __name__ == '__main__':
  62. sys.exit(
  63. load_entry_point('spec', 'console_scripts', 'name')()
  64. )
  65. """)
  66. dist = FakeDist()
  67. args = next(ei.ScriptWriter.get_args(dist))
  68. name, script = itertools.islice(args, 2)
  69. assert script == expected
  70. def test_no_find_links(self):
  71. # new option '--no-find-links', that blocks find-links added at
  72. # the project level
  73. dist = Distribution()
  74. cmd = ei.easy_install(dist)
  75. cmd.check_pth_processing = lambda: True
  76. cmd.no_find_links = True
  77. cmd.find_links = ['link1', 'link2']
  78. cmd.install_dir = os.path.join(tempfile.mkdtemp(), 'ok')
  79. cmd.args = ['ok']
  80. cmd.ensure_finalized()
  81. assert cmd.package_index.scanned_urls == {}
  82. # let's try without it (default behavior)
  83. cmd = ei.easy_install(dist)
  84. cmd.check_pth_processing = lambda: True
  85. cmd.find_links = ['link1', 'link2']
  86. cmd.install_dir = os.path.join(tempfile.mkdtemp(), 'ok')
  87. cmd.args = ['ok']
  88. cmd.ensure_finalized()
  89. keys = sorted(cmd.package_index.scanned_urls.keys())
  90. assert keys == ['link1', 'link2']
  91. def test_write_exception(self):
  92. """
  93. Test that `cant_write_to_target` is rendered as a DistutilsError.
  94. """
  95. dist = Distribution()
  96. cmd = ei.easy_install(dist)
  97. cmd.install_dir = os.getcwd()
  98. with pytest.raises(distutils.errors.DistutilsError):
  99. cmd.cant_write_to_target()
  100. def test_all_site_dirs(self, monkeypatch):
  101. """
  102. get_site_dirs should always return site dirs reported by
  103. site.getsitepackages.
  104. """
  105. mock_gsp = lambda: ['/setuptools/test/site-packages']
  106. monkeypatch.setattr(site, 'getsitepackages', mock_gsp, raising=False)
  107. assert '/setuptools/test/site-packages' in ei.get_site_dirs()
  108. def test_all_site_dirs_works_without_getsitepackages(self, monkeypatch):
  109. monkeypatch.delattr(site, 'getsitepackages', raising=False)
  110. assert ei.get_site_dirs()
  111. class TestPTHFileWriter:
  112. def test_add_from_cwd_site_sets_dirty(self):
  113. '''a pth file manager should set dirty
  114. if a distribution is in site but also the cwd
  115. '''
  116. pth = PthDistributions('does-not_exist', [os.getcwd()])
  117. assert not pth.dirty
  118. pth.add(PRDistribution(os.getcwd()))
  119. assert pth.dirty
  120. def test_add_from_site_is_ignored(self):
  121. location = '/test/location/does-not-have-to-exist'
  122. # PthDistributions expects all locations to be normalized
  123. location = pkg_resources.normalize_path(location)
  124. pth = PthDistributions('does-not_exist', [location, ])
  125. assert not pth.dirty
  126. pth.add(PRDistribution(location))
  127. assert not pth.dirty
  128. @pytest.yield_fixture
  129. def setup_context(tmpdir):
  130. with (tmpdir/'setup.py').open('w') as f:
  131. f.write(SETUP_PY)
  132. with tmpdir.as_cwd():
  133. yield tmpdir
  134. @pytest.mark.usefixtures("user_override")
  135. @pytest.mark.usefixtures("setup_context")
  136. class TestUserInstallTest:
  137. # prevent check that site-packages is writable. easy_install
  138. # shouldn't be writing to system site-packages during finalize
  139. # options, but while it does, bypass the behavior.
  140. prev_sp_write = mock.patch(
  141. 'setuptools.command.easy_install.easy_install.check_site_dir',
  142. mock.Mock(),
  143. )
  144. # simulate setuptools installed in user site packages
  145. @mock.patch('setuptools.command.easy_install.__file__', site.USER_SITE)
  146. @mock.patch('site.ENABLE_USER_SITE', True)
  147. @prev_sp_write
  148. def test_user_install_not_implied_user_site_enabled(self):
  149. self.assert_not_user_site()
  150. @mock.patch('site.ENABLE_USER_SITE', False)
  151. @prev_sp_write
  152. def test_user_install_not_implied_user_site_disabled(self):
  153. self.assert_not_user_site()
  154. @staticmethod
  155. def assert_not_user_site():
  156. # create a finalized easy_install command
  157. dist = Distribution()
  158. dist.script_name = 'setup.py'
  159. cmd = ei.easy_install(dist)
  160. cmd.args = ['py']
  161. cmd.ensure_finalized()
  162. assert not cmd.user, 'user should not be implied'
  163. def test_multiproc_atexit(self):
  164. pytest.importorskip('multiprocessing')
  165. log = logging.getLogger('test_easy_install')
  166. logging.basicConfig(level=logging.INFO, stream=sys.stderr)
  167. log.info('this should not break')
  168. @pytest.fixture()
  169. def foo_package(self, tmpdir):
  170. egg_file = tmpdir / 'foo-1.0.egg-info'
  171. with egg_file.open('w') as f:
  172. f.write('Name: foo\n')
  173. return str(tmpdir)
  174. @pytest.yield_fixture()
  175. def install_target(self, tmpdir):
  176. target = str(tmpdir)
  177. with mock.patch('sys.path', sys.path + [target]):
  178. python_path = os.path.pathsep.join(sys.path)
  179. with mock.patch.dict(os.environ, PYTHONPATH=python_path):
  180. yield target
  181. def test_local_index(self, foo_package, install_target):
  182. """
  183. The local index must be used when easy_install locates installed
  184. packages.
  185. """
  186. dist = Distribution()
  187. dist.script_name = 'setup.py'
  188. cmd = ei.easy_install(dist)
  189. cmd.install_dir = install_target
  190. cmd.args = ['foo']
  191. cmd.ensure_finalized()
  192. cmd.local_index.scan([foo_package])
  193. res = cmd.easy_install('foo')
  194. actual = os.path.normcase(os.path.realpath(res.location))
  195. expected = os.path.normcase(os.path.realpath(foo_package))
  196. assert actual == expected
  197. @contextlib.contextmanager
  198. def user_install_setup_context(self, *args, **kwargs):
  199. """
  200. Wrap sandbox.setup_context to patch easy_install in that context to
  201. appear as user-installed.
  202. """
  203. with self.orig_context(*args, **kwargs):
  204. import setuptools.command.easy_install as ei
  205. ei.__file__ = site.USER_SITE
  206. yield
  207. def patched_setup_context(self):
  208. self.orig_context = sandbox.setup_context
  209. return mock.patch(
  210. 'setuptools.sandbox.setup_context',
  211. self.user_install_setup_context,
  212. )
  213. @pytest.yield_fixture
  214. def distutils_package():
  215. distutils_setup_py = SETUP_PY.replace(
  216. 'from setuptools import setup',
  217. 'from distutils.core import setup',
  218. )
  219. with contexts.tempdir(cd=os.chdir):
  220. with open('setup.py', 'w') as f:
  221. f.write(distutils_setup_py)
  222. yield
  223. class TestDistutilsPackage:
  224. def test_bdist_egg_available_on_distutils_pkg(self, distutils_package):
  225. run_setup('setup.py', ['bdist_egg'])
  226. class TestSetupRequires:
  227. def test_setup_requires_honors_fetch_params(self):
  228. """
  229. When easy_install installs a source distribution which specifies
  230. setup_requires, it should honor the fetch parameters (such as
  231. allow-hosts, index-url, and find-links).
  232. """
  233. # set up a server which will simulate an alternate package index.
  234. p_index = setuptools.tests.server.MockServer()
  235. p_index.start()
  236. netloc = 1
  237. p_index_loc = urllib.parse.urlparse(p_index.url)[netloc]
  238. if p_index_loc.endswith(':0'):
  239. # Some platforms (Jython) don't find a port to which to bind,
  240. # so skip this test for them.
  241. return
  242. with contexts.quiet():
  243. # create an sdist that has a build-time dependency.
  244. with TestSetupRequires.create_sdist() as dist_file:
  245. with contexts.tempdir() as temp_install_dir:
  246. with contexts.environment(PYTHONPATH=temp_install_dir):
  247. ei_params = [
  248. '--index-url', p_index.url,
  249. '--allow-hosts', p_index_loc,
  250. '--exclude-scripts',
  251. '--install-dir', temp_install_dir,
  252. dist_file,
  253. ]
  254. with sandbox.save_argv(['easy_install']):
  255. # attempt to install the dist. It should fail because
  256. # it doesn't exist.
  257. with pytest.raises(SystemExit):
  258. easy_install_pkg.main(ei_params)
  259. # there should have been two or three requests to the server
  260. # (three happens on Python 3.3a)
  261. assert 2 <= len(p_index.requests) <= 3
  262. assert p_index.requests[0].path == '/does-not-exist/'
  263. @staticmethod
  264. @contextlib.contextmanager
  265. def create_sdist():
  266. """
  267. Return an sdist with a setup_requires dependency (of something that
  268. doesn't exist)
  269. """
  270. with contexts.tempdir() as dir:
  271. dist_path = os.path.join(dir, 'setuptools-test-fetcher-1.0.tar.gz')
  272. make_sdist(dist_path, [
  273. ('setup.py', DALS("""
  274. import setuptools
  275. setuptools.setup(
  276. name="setuptools-test-fetcher",
  277. version="1.0",
  278. setup_requires = ['does-not-exist'],
  279. )
  280. """))])
  281. yield dist_path
  282. def test_setup_requires_overrides_version_conflict(self):
  283. """
  284. Regression test for distribution issue 323:
  285. https://bitbucket.org/tarek/distribute/issues/323
  286. Ensures that a distribution's setup_requires requirements can still be
  287. installed and used locally even if a conflicting version of that
  288. requirement is already on the path.
  289. """
  290. fake_dist = PRDistribution('does-not-matter', project_name='foobar',
  291. version='0.0')
  292. working_set.add(fake_dist)
  293. with contexts.save_pkg_resources_state():
  294. with contexts.tempdir() as temp_dir:
  295. test_pkg = create_setup_requires_package(temp_dir)
  296. test_setup_py = os.path.join(test_pkg, 'setup.py')
  297. with contexts.quiet() as (stdout, stderr):
  298. # Don't even need to install the package, just
  299. # running the setup.py at all is sufficient
  300. run_setup(test_setup_py, ['--name'])
  301. lines = stdout.readlines()
  302. assert len(lines) > 0
  303. assert lines[-1].strip(), 'test_pkg'
  304. def test_setup_requires_override_nspkg(self):
  305. """
  306. Like ``test_setup_requires_overrides_version_conflict`` but where the
  307. ``setup_requires`` package is part of a namespace package that has
  308. *already* been imported.
  309. """
  310. with contexts.save_pkg_resources_state():
  311. with contexts.tempdir() as temp_dir:
  312. foobar_1_archive = os.path.join(temp_dir, 'foo.bar-0.1.tar.gz')
  313. make_nspkg_sdist(foobar_1_archive, 'foo.bar', '0.1')
  314. # Now actually go ahead an extract to the temp dir and add the
  315. # extracted path to sys.path so foo.bar v0.1 is importable
  316. foobar_1_dir = os.path.join(temp_dir, 'foo.bar-0.1')
  317. os.mkdir(foobar_1_dir)
  318. with tarfile_open(foobar_1_archive) as tf:
  319. tf.extractall(foobar_1_dir)
  320. sys.path.insert(1, foobar_1_dir)
  321. dist = PRDistribution(foobar_1_dir, project_name='foo.bar',
  322. version='0.1')
  323. working_set.add(dist)
  324. template = DALS("""\
  325. import foo # Even with foo imported first the
  326. # setup_requires package should override
  327. import setuptools
  328. setuptools.setup(**%r)
  329. if not (hasattr(foo, '__path__') and
  330. len(foo.__path__) == 2):
  331. print('FAIL')
  332. if 'foo.bar-0.2' not in foo.__path__[0]:
  333. print('FAIL')
  334. """)
  335. test_pkg = create_setup_requires_package(
  336. temp_dir, 'foo.bar', '0.2', make_nspkg_sdist, template)
  337. test_setup_py = os.path.join(test_pkg, 'setup.py')
  338. with contexts.quiet() as (stdout, stderr):
  339. try:
  340. # Don't even need to install the package, just
  341. # running the setup.py at all is sufficient
  342. run_setup(test_setup_py, ['--name'])
  343. except pkg_resources.VersionConflict:
  344. self.fail('Installing setup.py requirements '
  345. 'caused a VersionConflict')
  346. assert 'FAIL' not in stdout.getvalue()
  347. lines = stdout.readlines()
  348. assert len(lines) > 0
  349. assert lines[-1].strip() == 'test_pkg'
  350. def make_trivial_sdist(dist_path, distname, version):
  351. """
  352. Create a simple sdist tarball at dist_path, containing just a simple
  353. setup.py.
  354. """
  355. make_sdist(dist_path, [
  356. ('setup.py',
  357. DALS("""\
  358. import setuptools
  359. setuptools.setup(
  360. name=%r,
  361. version=%r
  362. )
  363. """ % (distname, version)))])
  364. def make_nspkg_sdist(dist_path, distname, version):
  365. """
  366. Make an sdist tarball with distname and version which also contains one
  367. package with the same name as distname. The top-level package is
  368. designated a namespace package).
  369. """
  370. parts = distname.split('.')
  371. nspackage = parts[0]
  372. packages = ['.'.join(parts[:idx]) for idx in range(1, len(parts) + 1)]
  373. setup_py = DALS("""\
  374. import setuptools
  375. setuptools.setup(
  376. name=%r,
  377. version=%r,
  378. packages=%r,
  379. namespace_packages=[%r]
  380. )
  381. """ % (distname, version, packages, nspackage))
  382. init = "__import__('pkg_resources').declare_namespace(__name__)"
  383. files = [('setup.py', setup_py),
  384. (os.path.join(nspackage, '__init__.py'), init)]
  385. for package in packages[1:]:
  386. filename = os.path.join(*(package.split('.') + ['__init__.py']))
  387. files.append((filename, ''))
  388. make_sdist(dist_path, files)
  389. def make_sdist(dist_path, files):
  390. """
  391. Create a simple sdist tarball at dist_path, containing the files
  392. listed in ``files`` as ``(filename, content)`` tuples.
  393. """
  394. with tarfile_open(dist_path, 'w:gz') as dist:
  395. for filename, content in files:
  396. file_bytes = io.BytesIO(content.encode('utf-8'))
  397. file_info = tarfile.TarInfo(name=filename)
  398. file_info.size = len(file_bytes.getvalue())
  399. file_info.mtime = int(time.time())
  400. dist.addfile(file_info, fileobj=file_bytes)
  401. def create_setup_requires_package(path, distname='foobar', version='0.1',
  402. make_package=make_trivial_sdist,
  403. setup_py_template=None):
  404. """Creates a source tree under path for a trivial test package that has a
  405. single requirement in setup_requires--a tarball for that requirement is
  406. also created and added to the dependency_links argument.
  407. ``distname`` and ``version`` refer to the name/version of the package that
  408. the test package requires via ``setup_requires``. The name of the test
  409. package itself is just 'test_pkg'.
  410. """
  411. test_setup_attrs = {
  412. 'name': 'test_pkg', 'version': '0.0',
  413. 'setup_requires': ['%s==%s' % (distname, version)],
  414. 'dependency_links': [os.path.abspath(path)]
  415. }
  416. test_pkg = os.path.join(path, 'test_pkg')
  417. test_setup_py = os.path.join(test_pkg, 'setup.py')
  418. os.mkdir(test_pkg)
  419. if setup_py_template is None:
  420. setup_py_template = DALS("""\
  421. import setuptools
  422. setuptools.setup(**%r)
  423. """)
  424. with open(test_setup_py, 'w') as f:
  425. f.write(setup_py_template % test_setup_attrs)
  426. foobar_path = os.path.join(path, '%s-%s.tar.gz' % (distname, version))
  427. make_package(foobar_path, distname, version)
  428. return test_pkg
  429. def make_trivial_sdist(dist_path, setup_py):
  430. """Create a simple sdist tarball at dist_path, containing just a
  431. setup.py, the contents of which are provided by the setup_py string.
  432. """
  433. setup_py_file = tarfile.TarInfo(name='setup.py')
  434. setup_py_bytes = io.BytesIO(setup_py.encode('utf-8'))
  435. setup_py_file.size = len(setup_py_bytes.getvalue())
  436. with tarfile_open(dist_path, 'w:gz') as dist:
  437. dist.addfile(setup_py_file, fileobj=setup_py_bytes)
  438. class TestScriptHeader:
  439. non_ascii_exe = '/Users/José/bin/python'
  440. exe_with_spaces = r'C:\Program Files\Python33\python.exe'
  441. @pytest.mark.skipif(
  442. sys.platform.startswith('java') and ei.is_sh(sys.executable),
  443. reason="Test cannot run under java when executable is sh"
  444. )
  445. def test_get_script_header(self):
  446. expected = '#!%s\n' % ei.nt_quote_arg(os.path.normpath(sys.executable))
  447. actual = ei.ScriptWriter.get_script_header('#!/usr/local/bin/python')
  448. assert actual == expected
  449. expected = '#!%s -x\n' % ei.nt_quote_arg(os.path.normpath
  450. (sys.executable))
  451. actual = ei.ScriptWriter.get_script_header('#!/usr/bin/python -x')
  452. assert actual == expected
  453. actual = ei.ScriptWriter.get_script_header('#!/usr/bin/python',
  454. executable=self.non_ascii_exe)
  455. expected = '#!%s -x\n' % self.non_ascii_exe
  456. assert actual == expected
  457. actual = ei.ScriptWriter.get_script_header('#!/usr/bin/python',
  458. executable='"'+self.exe_with_spaces+'"')
  459. expected = '#!"%s"\n' % self.exe_with_spaces
  460. assert actual == expected
  461. class TestCommandSpec:
  462. def test_custom_launch_command(self):
  463. """
  464. Show how a custom CommandSpec could be used to specify a #! executable
  465. which takes parameters.
  466. """
  467. cmd = ei.CommandSpec(['/usr/bin/env', 'python3'])
  468. assert cmd.as_header() == '#!/usr/bin/env python3\n'
  469. def test_from_param_for_CommandSpec_is_passthrough(self):
  470. """
  471. from_param should return an instance of a CommandSpec
  472. """
  473. cmd = ei.CommandSpec(['python'])
  474. cmd_new = ei.CommandSpec.from_param(cmd)
  475. assert cmd is cmd_new
  476. @mock.patch('sys.executable', TestScriptHeader.exe_with_spaces)
  477. @mock.patch.dict(os.environ)
  478. def test_from_environment_with_spaces_in_executable(self):
  479. os.environ.pop('__PYVENV_LAUNCHER__', None)
  480. cmd = ei.CommandSpec.from_environment()
  481. assert len(cmd) == 1
  482. assert cmd.as_header().startswith('#!"')
  483. def test_from_simple_string_uses_shlex(self):
  484. """
  485. In order to support `executable = /usr/bin/env my-python`, make sure
  486. from_param invokes shlex on that input.
  487. """
  488. cmd = ei.CommandSpec.from_param('/usr/bin/env my-python')
  489. assert len(cmd) == 2
  490. assert '"' not in cmd.as_header()
  491. def test_sys_executable(self):
  492. """
  493. CommandSpec.from_string(sys.executable) should contain just that param.
  494. """
  495. writer = ei.ScriptWriter.best()
  496. cmd = writer.command_spec_class.from_string(sys.executable)
  497. assert len(cmd) == 1
  498. assert cmd[0] == sys.executable
  499. class TestWindowsScriptWriter:
  500. def test_header(self):
  501. hdr = ei.WindowsScriptWriter.get_script_header('')
  502. assert hdr.startswith('#!')
  503. assert hdr.endswith('\n')
  504. hdr = hdr.lstrip('#!')
  505. hdr = hdr.rstrip('\n')
  506. # header should not start with an escaped quote
  507. assert not hdr.startswith('\\"')