test_pip_state.py 26 KB

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