1
0

test_pip_state.py 25 KB

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