test_pip_state.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. # -*- coding: utf-8 -*-
  2. """
  3. :codeauthor: Pedro Algarvio (pedro@algarvio.me)
  4. tests.integration.states.pip_state
  5. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  6. """
  7. from __future__ import absolute_import, print_function, unicode_literals
  8. import errno
  9. import glob
  10. import os
  11. import pprint
  12. import shutil
  13. import sys
  14. import pytest
  15. import salt.utils.files
  16. import salt.utils.path
  17. import salt.utils.platform
  18. import salt.utils.versions
  19. import salt.utils.win_dacl
  20. import salt.utils.win_functions
  21. import salt.utils.win_runas
  22. from salt.exceptions import CommandExecutionError
  23. from salt.ext import six
  24. from salt.modules.virtualenv_mod import KNOWN_BINARY_NAMES
  25. from tests.support.case import ModuleCase
  26. from tests.support.helpers import (
  27. destructiveTest,
  28. patched_environ,
  29. requires_system_grains,
  30. skip_if_not_root,
  31. slowTest,
  32. with_system_user,
  33. with_tempdir,
  34. )
  35. from tests.support.mixins import SaltReturnAssertsMixin
  36. from tests.support.runtests import RUNTIME_VARS
  37. from tests.support.unit import skipIf
  38. try:
  39. import pwd
  40. HAS_PWD = True
  41. except ImportError:
  42. HAS_PWD = False
  43. class VirtualEnv(object):
  44. def __init__(self, test, venv_dir):
  45. self.venv_dir = venv_dir
  46. self.test = test
  47. self.test.addCleanup(shutil.rmtree, self.venv_dir, ignore_errors=True)
  48. def __enter__(self):
  49. ret = self.test._create_virtualenv(self.venv_dir)
  50. self.test.assertEqual(
  51. ret["retcode"],
  52. 0,
  53. msg="Expected 'retcode' key did not match. Full return dictionary:\n{}".format(
  54. pprint.pformat(ret)
  55. ),
  56. )
  57. def __exit__(self, *args):
  58. pass
  59. @skipIf(
  60. salt.utils.path.which_bin(KNOWN_BINARY_NAMES) is None, "virtualenv not installed"
  61. )
  62. @pytest.mark.windows_whitelisted
  63. class PipStateTest(ModuleCase, SaltReturnAssertsMixin):
  64. def _win_user_where(self, username, password, program):
  65. cmd = "cmd.exe /c where {}".format(program)
  66. ret = salt.utils.win_runas.runas(cmd, username, password)
  67. assert ret["retcode"] == 0, "{} returned {}".format(cmd, ret["retcode"])
  68. return ret["stdout"].strip().split("\n")[-1].strip()
  69. def _create_virtualenv(self, path, **kwargs):
  70. """
  71. The reason why the virtualenv creation is proxied by this function is mostly
  72. because under windows, we can't seem to properly create a virtualenv off of
  73. another virtualenv(we can on linux) and also because, we really don't want to
  74. test virtualenv creation off of another virtualenv, we want a virtualenv created
  75. from the original python.
  76. Also, one windows, we must also point to the virtualenv binary outside the existing
  77. virtualenv because it will fail otherwise
  78. """
  79. self.addCleanup(shutil.rmtree, path, ignore_errors=True)
  80. if "python" not in kwargs:
  81. try:
  82. if salt.utils.platform.is_windows():
  83. python = os.path.join(
  84. sys.real_prefix, os.path.basename(sys.executable)
  85. )
  86. else:
  87. python_binary_names = [
  88. "python{}.{}".format(*sys.version_info),
  89. "python{}".format(*sys.version_info),
  90. "python",
  91. ]
  92. for binary_name in python_binary_names:
  93. python = os.path.join(sys.real_prefix, "bin", binary_name)
  94. if os.path.exists(python):
  95. break
  96. else:
  97. self.fail(
  98. "Couldn't find a python binary name under '{}' matching: {}".format(
  99. os.path.join(sys.real_prefix, "bin"),
  100. python_binary_names,
  101. )
  102. )
  103. # We're running off a virtualenv, and we don't want to create a virtualenv off of
  104. # a virtualenv, let's point to the actual python that created the virtualenv
  105. kwargs["python"] = python
  106. except AttributeError:
  107. # We're running off of the system python
  108. pass
  109. return self.run_function("virtualenv.create", [path], **kwargs)
  110. @slowTest
  111. def test_pip_installed_removed(self):
  112. """
  113. Tests installed and removed states
  114. """
  115. name = "pudb"
  116. if name in self.run_function("pip.list"):
  117. self.skipTest(
  118. "{0} is already installed, uninstall to run this test".format(name)
  119. )
  120. ret = self.run_state("pip.installed", name=name)
  121. self.assertSaltTrueReturn(ret)
  122. ret = self.run_state("pip.removed", name=name)
  123. self.assertSaltTrueReturn(ret)
  124. @slowTest
  125. def test_pip_installed_removed_venv(self):
  126. venv_dir = os.path.join(RUNTIME_VARS.TMP, "pip_installed_removed")
  127. with VirtualEnv(self, venv_dir):
  128. name = "pudb"
  129. ret = self.run_state("pip.installed", name=name, bin_env=venv_dir)
  130. self.assertSaltTrueReturn(ret)
  131. ret = self.run_state("pip.removed", name=name, bin_env=venv_dir)
  132. self.assertSaltTrueReturn(ret)
  133. @slowTest
  134. def test_pip_installed_errors(self):
  135. venv_dir = os.path.join(RUNTIME_VARS.TMP, "pip-installed-errors")
  136. self.addCleanup(shutil.rmtree, venv_dir, ignore_errors=True)
  137. # Since we don't have the virtualenv created, pip.installed will
  138. # throw an error.
  139. # Example error strings:
  140. # * "Error installing 'pep8': /tmp/pip-installed-errors: not found"
  141. # * "Error installing 'pep8': /bin/sh: 1: /tmp/pip-installed-errors: not found"
  142. # * "Error installing 'pep8': /bin/bash: /tmp/pip-installed-errors: No such file or directory"
  143. with patched_environ(SHELL="/bin/sh"):
  144. ret = self.run_function("state.sls", mods="pip-installed-errors")
  145. self.assertSaltFalseReturn(ret)
  146. self.assertSaltCommentRegexpMatches(ret, "Error installing 'pep8':")
  147. # We now create the missing virtualenv
  148. ret = self.run_function("virtualenv.create", [venv_dir])
  149. self.assertEqual(ret["retcode"], 0)
  150. # The state should not have any issues running now
  151. ret = self.run_function("state.sls", mods="pip-installed-errors")
  152. self.assertSaltTrueReturn(ret)
  153. @skipIf(six.PY3, "Issue is specific to carbon module, which is PY2-only")
  154. @skipIf(salt.utils.platform.is_windows(), "Carbon does not install in Windows")
  155. @requires_system_grains
  156. def test_pip_installed_weird_install(self, grains=None):
  157. # First, check to see if this is running on CentOS 5 or MacOS.
  158. # If so, skip this test.
  159. if grains["os"] in ("CentOS",) and grains["osrelease_info"][0] in (5,):
  160. self.skipTest("This test does not run reliably on CentOS 5")
  161. if grains["os"] in ("MacOS",):
  162. self.skipTest("This test does not run reliably on MacOS")
  163. ographite = "/opt/graphite"
  164. if os.path.isdir(ographite):
  165. self.skipTest(
  166. "You already have '{0}'. This test would overwrite this "
  167. "directory".format(ographite)
  168. )
  169. try:
  170. os.makedirs(ographite)
  171. except OSError as err:
  172. if err.errno == errno.EACCES:
  173. # Permission denied
  174. self.skipTest(
  175. "You don't have the required permissions to run this test"
  176. )
  177. finally:
  178. if os.path.isdir(ographite):
  179. shutil.rmtree(ographite, ignore_errors=True)
  180. venv_dir = os.path.join(RUNTIME_VARS.TMP, "pip-installed-weird-install")
  181. try:
  182. # We may be able to remove this, I had to add it because the custom
  183. # modules from the test suite weren't available in the jinja
  184. # context when running the call to state.sls that comes after.
  185. self.run_function("saltutil.sync_modules")
  186. # Since we don't have the virtualenv created, pip.installed will
  187. # throw an error.
  188. ret = self.run_function("state.sls", mods="pip-installed-weird-install")
  189. self.assertSaltTrueReturn(ret)
  190. # We cannot use assertInSaltComment here because we need to skip
  191. # some of the state return parts
  192. for key in six.iterkeys(ret):
  193. self.assertTrue(ret[key]["result"])
  194. if ret[key]["name"] != "carbon < 1.1":
  195. continue
  196. self.assertEqual(
  197. ret[key]["comment"],
  198. "There was no error installing package 'carbon < 1.1' "
  199. "although it does not show when calling 'pip.freeze'.",
  200. )
  201. break
  202. else:
  203. raise Exception("Expected state did not run")
  204. finally:
  205. if os.path.isdir(ographite):
  206. shutil.rmtree(ographite, ignore_errors=True)
  207. @slowTest
  208. def test_issue_2028_pip_installed_state(self):
  209. ret = self.run_function("state.sls", mods="issue-2028-pip-installed")
  210. venv_dir = os.path.join(RUNTIME_VARS.TMP, "issue-2028-pip-installed")
  211. self.addCleanup(shutil.rmtree, venv_dir, ignore_errors=True)
  212. pep8_bin = os.path.join(venv_dir, "bin", "pep8")
  213. if salt.utils.platform.is_windows():
  214. pep8_bin = os.path.join(venv_dir, "Scripts", "pep8.exe")
  215. self.assertSaltTrueReturn(ret)
  216. self.assertTrue(os.path.isfile(pep8_bin))
  217. @slowTest
  218. def test_issue_2087_missing_pip(self):
  219. venv_dir = os.path.join(RUNTIME_VARS.TMP, "issue-2087-missing-pip")
  220. # Let's create the testing virtualenv
  221. ret = self._create_virtualenv(venv_dir)
  222. self.assertEqual(
  223. ret["retcode"],
  224. 0,
  225. msg="Expected 'retcode' key did not match. Full return dictionary:\n{}".format(
  226. pprint.pformat(ret)
  227. ),
  228. )
  229. # Let's remove the pip binary
  230. pip_bin = os.path.join(venv_dir, "bin", "pip")
  231. site_dir = self.run_function(
  232. "virtualenv.get_distribution_path", [venv_dir, "pip"]
  233. )
  234. if salt.utils.platform.is_windows():
  235. pip_bin = os.path.join(venv_dir, "Scripts", "pip.exe")
  236. site_dir = os.path.join(venv_dir, "lib", "site-packages")
  237. if not os.path.isfile(pip_bin):
  238. self.skipTest("Failed to find the pip binary to the test virtualenv")
  239. os.remove(pip_bin)
  240. # Also remove the pip dir from site-packages
  241. # This is needed now that we're using python -m pip instead of the
  242. # pip binary directly. python -m pip will still work even if the
  243. # pip binary is missing
  244. shutil.rmtree(os.path.join(site_dir, "pip"))
  245. # Let's run the state which should fail because pip is missing
  246. ret = self.run_function("state.sls", mods="issue-2087-missing-pip")
  247. self.assertSaltFalseReturn(ret)
  248. self.assertInSaltComment(
  249. "Error installing 'pep8': Could not find a `pip` binary", ret
  250. )
  251. def test_issue_5940_multiple_pip_mirrors(self):
  252. """
  253. Test multiple pip mirrors. This test only works with pip < 7.0.0
  254. """
  255. ret = self.run_function("state.sls", mods="issue-5940-multiple-pip-mirrors")
  256. venv_dir = os.path.join(RUNTIME_VARS.TMP, "5940-multiple-pip-mirrors")
  257. self.addCleanup(shutil.rmtree, venv_dir, ignore_errors=True)
  258. try:
  259. self.assertSaltTrueReturn(ret)
  260. self.assertTrue(os.path.isfile(os.path.join(venv_dir, "bin", "pep8")))
  261. except (AssertionError, CommandExecutionError):
  262. pip_version = self.run_function("pip.version", [venv_dir])
  263. if salt.utils.versions.compare(ver1=pip_version, oper=">=", ver2="7.0.0"):
  264. self.skipTest(
  265. "the --mirrors arg has been deprecated and removed in pip==7.0.0"
  266. )
  267. @destructiveTest
  268. @skip_if_not_root
  269. @with_system_user(
  270. "issue-6912", on_existing="delete", delete=True, password="PassWord1!"
  271. )
  272. @with_tempdir()
  273. @slowTest
  274. def test_issue_6912_wrong_owner(self, temp_dir, username):
  275. # Setup virtual environment directory to be used throughout the test
  276. venv_dir = os.path.join(temp_dir, "6912-wrong-owner")
  277. venv_kwargs = {}
  278. # The virtual environment needs to be in a location that is accessible
  279. # by both the user running the test and the runas user
  280. if salt.utils.platform.is_windows():
  281. salt.utils.win_dacl.set_permissions(temp_dir, username, "full_control")
  282. # Make sure we're calling a virtualenv and python
  283. # program that the user has access too.
  284. venv_kwargs["venv_bin"] = self._win_user_where(
  285. username, "PassWord1!", "virtualenv",
  286. )
  287. venv_kwargs["python"] = self._win_user_where(
  288. username, "PassWord1!", "python",
  289. )
  290. else:
  291. uid = self.run_function("file.user_to_uid", [username])
  292. os.chown(temp_dir, uid, -1)
  293. # Create the virtual environment
  294. venv_create = self._create_virtualenv(
  295. venv_dir, user=username, password="PassWord1!", **venv_kwargs
  296. )
  297. if venv_create.get("retcode", 1) > 0:
  298. self.skipTest(
  299. "Failed to create testcase virtual environment: {0}"
  300. "".format(venv_create)
  301. )
  302. # pip install passing the package name in `name`
  303. ret = self.run_state(
  304. "pip.installed",
  305. name="pep8",
  306. user=username,
  307. bin_env=venv_dir,
  308. password="PassWord1!",
  309. )
  310. self.assertSaltTrueReturn(ret)
  311. if HAS_PWD:
  312. uid = pwd.getpwnam(username).pw_uid
  313. for globmatch in (
  314. os.path.join(venv_dir, "**", "pep8*"),
  315. os.path.join(venv_dir, "*", "**", "pep8*"),
  316. os.path.join(venv_dir, "*", "*", "**", "pep8*"),
  317. ):
  318. for path in glob.glob(globmatch):
  319. if HAS_PWD:
  320. self.assertEqual(uid, os.stat(path).st_uid)
  321. elif salt.utils.platform.is_windows():
  322. self.assertEqual(salt.utils.win_dacl.get_owner(path), username)
  323. @destructiveTest
  324. @skip_if_not_root
  325. @skipIf(salt.utils.platform.is_darwin(), "Test is flaky on macosx")
  326. @with_system_user(
  327. "issue-6912", on_existing="delete", delete=True, password="PassWord1!"
  328. )
  329. @with_tempdir()
  330. @slowTest
  331. def test_issue_6912_wrong_owner_requirements_file(self, temp_dir, username):
  332. # Setup virtual environment directory to be used throughout the test
  333. venv_dir = os.path.join(temp_dir, "6912-wrong-owner")
  334. venv_kwargs = {}
  335. # The virtual environment needs to be in a location that is accessible
  336. # by both the user running the test and the runas user
  337. if salt.utils.platform.is_windows():
  338. salt.utils.win_dacl.set_permissions(temp_dir, username, "full_control")
  339. # Make sure we're calling a virtualenv and python
  340. # program that the user has access too.
  341. venv_kwargs["venv_bin"] = self._win_user_where(
  342. username, "PassWord1!", "virtualenv",
  343. )
  344. venv_kwargs["python"] = self._win_user_where(
  345. username, "PassWord1!", "python",
  346. )
  347. else:
  348. uid = self.run_function("file.user_to_uid", [username])
  349. os.chown(temp_dir, uid, -1)
  350. # Create the virtual environment again as it should have been removed
  351. venv_create = self._create_virtualenv(
  352. venv_dir, user=username, password="PassWord1!", **venv_kwargs
  353. )
  354. if venv_create.get("retcode", 1) > 0:
  355. self.skipTest(
  356. "failed to create testcase virtual environment: {0}"
  357. "".format(venv_create)
  358. )
  359. # pip install using a requirements file
  360. req_filename = os.path.join(
  361. RUNTIME_VARS.TMP_STATE_TREE, "issue-6912-requirements.txt"
  362. )
  363. with salt.utils.files.fopen(req_filename, "wb") as reqf:
  364. reqf.write(b"pep8\n")
  365. ret = self.run_state(
  366. "pip.installed",
  367. name="",
  368. user=username,
  369. bin_env=venv_dir,
  370. requirements="salt://issue-6912-requirements.txt",
  371. password="PassWord1!",
  372. )
  373. self.assertSaltTrueReturn(ret)
  374. if HAS_PWD:
  375. uid = pwd.getpwnam(username).pw_uid
  376. for globmatch in (
  377. os.path.join(venv_dir, "**", "pep8*"),
  378. os.path.join(venv_dir, "*", "**", "pep8*"),
  379. os.path.join(venv_dir, "*", "*", "**", "pep8*"),
  380. ):
  381. for path in glob.glob(globmatch):
  382. if HAS_PWD:
  383. self.assertEqual(uid, os.stat(path).st_uid)
  384. elif salt.utils.platform.is_windows():
  385. self.assertEqual(salt.utils.win_dacl.get_owner(path), username)
  386. @destructiveTest
  387. @slowTest
  388. def test_issue_6833_pip_upgrade_pip(self):
  389. # Create the testing virtualenv
  390. if sys.platform == "win32":
  391. # To keeps the path short, we'll create this directory on the root
  392. # of the system drive. Otherwise the path is too long and the pip
  393. # upgrade will fail. Also, I don't know why salt.utils.platform
  394. # doesn't work in this function, that's why I used sys.platform
  395. # Need to use os.sep.join here instead of os.path.join because of
  396. # the colon in SystemDrive
  397. venv_dir = os.sep.join(
  398. [os.environ["SystemDrive"], "tmp-6833-pip-upgrade-pip"]
  399. )
  400. else:
  401. venv_dir = os.path.join(RUNTIME_VARS.TMP, "6833-pip-upgrade-pip")
  402. ret = self._create_virtualenv(venv_dir)
  403. self.assertEqual(
  404. ret["retcode"],
  405. 0,
  406. msg="Expected 'retcode' key did not match. Full return dictionary:\n{}".format(
  407. pprint.pformat(ret)
  408. ),
  409. )
  410. if not (
  411. "New python executable" in ret["stdout"]
  412. or "created virtual environment" in ret["stdout"]
  413. ):
  414. assert (
  415. False
  416. ), "Expected STDOUT did not match. Full return dictionary:\n{}".format(
  417. pprint.pformat(ret)
  418. )
  419. # Let's install a fixed version pip over whatever pip was
  420. # previously installed
  421. ret = self.run_function(
  422. "pip.install", ["pip==9.0.1"], upgrade=True, bin_env=venv_dir
  423. )
  424. if not isinstance(ret, dict):
  425. self.fail(
  426. "The 'pip.install' command did not return the excepted dictionary. Output:\n{}".format(
  427. ret
  428. )
  429. )
  430. self.assertEqual(ret["retcode"], 0)
  431. self.assertIn("Successfully installed pip", ret["stdout"])
  432. # Let's make sure we have pip 9.0.1 installed
  433. self.assertEqual(
  434. self.run_function("pip.list", ["pip"], bin_env=venv_dir), {"pip": "9.0.1"}
  435. )
  436. # Now the actual pip upgrade pip test
  437. ret = self.run_state(
  438. "pip.installed", name="pip==20.0.1", upgrade=True, bin_env=venv_dir
  439. )
  440. if not isinstance(ret, dict):
  441. self.fail(
  442. "The 'pip.install' command did not return the excepted dictionary. Output:\n{}".format(
  443. ret
  444. )
  445. )
  446. self.assertSaltTrueReturn(ret)
  447. self.assertSaltStateChangesEqual(ret, {"pip==20.0.1": "Installed"})
  448. @slowTest
  449. def test_pip_installed_specific_env(self):
  450. # Create the testing virtualenv
  451. venv_dir = os.path.join(RUNTIME_VARS.TMP, "pip-installed-specific-env")
  452. # Let's write a requirements file
  453. requirements_file = os.path.join(
  454. RUNTIME_VARS.TMP_PRODENV_STATE_TREE, "prod-env-requirements.txt"
  455. )
  456. with salt.utils.files.fopen(requirements_file, "wb") as reqf:
  457. reqf.write(b"pep8\n")
  458. try:
  459. self._create_virtualenv(venv_dir)
  460. # The requirements file should not be found the base environment
  461. ret = self.run_state(
  462. "pip.installed",
  463. name="",
  464. bin_env=venv_dir,
  465. requirements="salt://prod-env-requirements.txt",
  466. )
  467. self.assertSaltFalseReturn(ret)
  468. self.assertInSaltComment(
  469. "'salt://prod-env-requirements.txt' not found", ret
  470. )
  471. # The requirements file must be found in the prod environment
  472. ret = self.run_state(
  473. "pip.installed",
  474. name="",
  475. bin_env=venv_dir,
  476. saltenv="prod",
  477. requirements="salt://prod-env-requirements.txt",
  478. )
  479. self.assertSaltTrueReturn(ret)
  480. self.assertInSaltComment(
  481. "Successfully processed requirements file "
  482. "salt://prod-env-requirements.txt",
  483. ret,
  484. )
  485. # We're using the base environment but we're passing the prod
  486. # environment as an url arg to salt://
  487. ret = self.run_state(
  488. "pip.installed",
  489. name="",
  490. bin_env=venv_dir,
  491. requirements="salt://prod-env-requirements.txt?saltenv=prod",
  492. )
  493. self.assertSaltTrueReturn(ret)
  494. self.assertInSaltComment("Requirements were already installed.", ret)
  495. finally:
  496. if os.path.isfile(requirements_file):
  497. os.unlink(requirements_file)
  498. @skipIf(
  499. salt.utils.platform.is_darwin() and six.PY2, "This test hangs on OS X on Py2"
  500. )
  501. @slowTest
  502. def test_22359_pip_installed_unless_does_not_trigger_warnings(self):
  503. # This test case should be moved to a format_call unit test specific to
  504. # the state internal keywords
  505. venv_dir = os.path.join(RUNTIME_VARS.TMP, "pip-installed-unless")
  506. venv_create = self._create_virtualenv(venv_dir)
  507. if venv_create.get("retcode", 1) > 0:
  508. self.skipTest(
  509. "Failed to create testcase virtual environment: {0}".format(venv_create)
  510. )
  511. false_cmd = RUNTIME_VARS.SHELL_FALSE_PATH
  512. if salt.utils.platform.is_windows():
  513. false_cmd = "exit 1 >nul"
  514. try:
  515. ret = self.run_state(
  516. "pip.installed",
  517. name="pep8",
  518. bin_env=venv_dir,
  519. unless=false_cmd,
  520. timeout=600,
  521. )
  522. self.assertSaltTrueReturn(ret)
  523. self.assertNotIn("warnings", next(six.itervalues(ret)))
  524. finally:
  525. if os.path.isdir(venv_dir):
  526. shutil.rmtree(venv_dir, ignore_errors=True)
  527. @skipIf(
  528. sys.version_info[:2] >= (3, 6),
  529. "Old version of virtualenv too old for python3.6",
  530. )
  531. @skipIf(salt.utils.platform.is_windows(), "Carbon does not install in Windows")
  532. @slowTest
  533. def test_46127_pip_env_vars(self):
  534. """
  535. Test that checks if env_vars passed to pip.installed are also passed
  536. to pip.freeze while checking for existing installations
  537. """
  538. # This issue is most easily checked while installing carbon
  539. # Much of the code here comes from the test_weird_install function above
  540. ographite = "/opt/graphite"
  541. if os.path.isdir(ographite):
  542. self.skipTest(
  543. "You already have '{0}'. This test would overwrite this "
  544. "directory".format(ographite)
  545. )
  546. try:
  547. os.makedirs(ographite)
  548. except OSError as err:
  549. if err.errno == errno.EACCES:
  550. # Permission denied
  551. self.skipTest(
  552. "You don't have the required permissions to run this test"
  553. )
  554. finally:
  555. if os.path.isdir(ographite):
  556. shutil.rmtree(ographite, ignore_errors=True)
  557. venv_dir = os.path.join(RUNTIME_VARS.TMP, "issue-46127-pip-env-vars")
  558. try:
  559. # We may be able to remove this, I had to add it because the custom
  560. # modules from the test suite weren't available in the jinja
  561. # context when running the call to state.sls that comes after.
  562. self.run_function("saltutil.sync_modules")
  563. # Since we don't have the virtualenv created, pip.installed will
  564. # throw an error.
  565. ret = self.run_function("state.sls", mods="issue-46127-pip-env-vars")
  566. self.assertSaltTrueReturn(ret)
  567. for key in six.iterkeys(ret):
  568. self.assertTrue(ret[key]["result"])
  569. if ret[key]["name"] != "carbon < 1.3":
  570. continue
  571. self.assertEqual(
  572. ret[key]["comment"], "All packages were successfully installed"
  573. )
  574. break
  575. else:
  576. raise Exception("Expected state did not run")
  577. # Run the state again. Now the already installed message should
  578. # appear
  579. ret = self.run_function("state.sls", mods="issue-46127-pip-env-vars")
  580. self.assertSaltTrueReturn(ret)
  581. # We cannot use assertInSaltComment here because we need to skip
  582. # some of the state return parts
  583. for key in six.iterkeys(ret):
  584. self.assertTrue(ret[key]["result"])
  585. # As we are re-running the formula, some states will not be run
  586. # and "name" may or may not be present, so we use .get() pattern
  587. if ret[key].get("name", "") != "carbon < 1.3":
  588. continue
  589. self.assertEqual(
  590. ret[key]["comment"], ("All packages were successfully installed")
  591. )
  592. break
  593. else:
  594. raise Exception("Expected state did not run")
  595. finally:
  596. if os.path.isdir(ographite):
  597. shutil.rmtree(ographite, ignore_errors=True)
  598. if os.path.isdir(venv_dir):
  599. shutil.rmtree(venv_dir)
  600. @pytest.mark.windows_whitelisted
  601. class PipStateInRequisiteTest(ModuleCase, SaltReturnAssertsMixin):
  602. @with_tempdir()
  603. @slowTest
  604. def test_issue_54755(self, tmpdir):
  605. """
  606. Verify github issue 54755 is resolved. This only fails when there is no
  607. pip module in the python environment. Since the test suite normally has
  608. a pip module this test will pass and is here for posterity. See also
  609. unit.states.test_pip_state.PipStateUtilsTest.test_pip_purge_method_with_pip
  610. and
  611. unit.states.test_pip_state.PipStateUtilsTest.test_pip_purge_method_without_pip
  612. Which also validate this issue and will pass/fail regardless of whether
  613. or not pip is installed.
  614. """
  615. file_path = os.path.join(tmpdir, "issue-54755")
  616. ret = self.run_function(
  617. "state.sls", mods="issue-54755", pillar={"file_path": file_path}
  618. )
  619. key = "file_|-issue-54755_|-{}_|-managed".format(file_path)
  620. assert key in ret
  621. assert ret[key]["result"] is True
  622. with salt.utils.files.fopen(file_path, "r") as fp:
  623. assert fp.read().strip() == "issue-54755"