test_pip_state.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. # -*- coding: utf-8 -*-
  2. '''
  3. :codeauthor: Pedro Algarvio (pedro@algarvio.me)
  4. tests.integration.states.pip_state
  5. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  6. '''
  7. # Import python libs
  8. from __future__ import absolute_import, print_function, unicode_literals
  9. import errno
  10. import os
  11. import glob
  12. import pprint
  13. import shutil
  14. import sys
  15. try:
  16. import pwd
  17. HAS_PWD = True
  18. except ImportError:
  19. HAS_PWD = False
  20. # Import Salt Testing libs
  21. from tests.support.case import ModuleCase
  22. from tests.support.helpers import (
  23. requires_system_grains,
  24. with_system_user,
  25. with_tempdir,
  26. patched_environ
  27. )
  28. from tests.support.mixins import SaltReturnAssertsMixin
  29. from tests.support.runtime import RUNTIME_VARS
  30. from tests.support.unit import skipIf
  31. # Import salt libs
  32. import salt.utils.files
  33. import salt.utils.path
  34. import salt.utils.platform
  35. import salt.utils.versions
  36. import salt.utils.win_dacl
  37. import salt.utils.win_functions
  38. import salt.utils.win_runas
  39. from salt.modules.virtualenv_mod import KNOWN_BINARY_NAMES
  40. from salt.exceptions import CommandExecutionError
  41. # Import 3rd-party libs
  42. import pytest
  43. from salt.ext import six
  44. class VirtualEnv(object):
  45. def __init__(self, test, venv_dir):
  46. self.venv_dir = venv_dir
  47. self.test = test
  48. self.test.addCleanup(shutil.rmtree, self.venv_dir, ignore_errors=True)
  49. def __enter__(self):
  50. ret = self.test._create_virtualenv(self.venv_dir)
  51. self.test.assertEqual(
  52. ret['retcode'], 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(salt.utils.path.which_bin(KNOWN_BINARY_NAMES) is None, 'virtualenv not installed')
  60. class PipStateTest(ModuleCase, SaltReturnAssertsMixin):
  61. def _create_virtualenv(self, path):
  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.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'),
  89. python_binary_names
  90. )
  91. )
  92. # We're running off a virtualenv, and we don't want to create a virtualenv off of
  93. # a virtualenv, let's point to the actual python that created the virtualenv
  94. kwargs = {'python': python}
  95. except AttributeError:
  96. # We're running off of the system python
  97. kwargs = {}
  98. return self.run_function('virtualenv.create', [path], **kwargs)
  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('{0} is already installed, uninstall to run this test'.format(name))
  106. ret = self.run_state('pip.installed', name=name)
  107. self.assertSaltTrueReturn(ret)
  108. ret = self.run_state('pip.removed', name=name)
  109. self.assertSaltTrueReturn(ret)
  110. def test_pip_installed_removed_venv(self):
  111. venv_dir = os.path.join(
  112. RUNTIME_VARS.TMP, 'pip_installed_removed'
  113. )
  114. with VirtualEnv(self, venv_dir):
  115. name = 'pudb'
  116. ret = self.run_state('pip.installed', name=name, bin_env=venv_dir)
  117. self.assertSaltTrueReturn(ret)
  118. ret = self.run_state('pip.removed', name=name, bin_env=venv_dir)
  119. self.assertSaltTrueReturn(ret)
  120. def test_pip_installed_errors(self):
  121. venv_dir = os.path.join(
  122. RUNTIME_VARS.TMP, 'pip-installed-errors'
  123. )
  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(
  135. ret,
  136. 'Error installing \'pep8\':'
  137. )
  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(
  180. 'state.sls', mods='pip-installed-weird-install'
  181. )
  182. self.assertSaltTrueReturn(ret)
  183. # We cannot use assertInSaltComment here because we need to skip
  184. # some of the state return parts
  185. for key in six.iterkeys(ret):
  186. self.assertTrue(ret[key]['result'])
  187. if ret[key]['name'] != 'carbon < 1.1':
  188. continue
  189. self.assertEqual(
  190. ret[key]['comment'],
  191. 'There was no error installing package \'carbon < 1.1\' '
  192. 'although it does not show when calling \'pip.freeze\'.'
  193. )
  194. break
  195. else:
  196. raise Exception('Expected state did not run')
  197. finally:
  198. if os.path.isdir(ographite):
  199. shutil.rmtree(ographite, ignore_errors=True)
  200. def test_issue_2028_pip_installed_state(self):
  201. ret = self.run_function('state.sls', mods='issue-2028-pip-installed')
  202. venv_dir = os.path.join(
  203. RUNTIME_VARS.TMP, 'issue-2028-pip-installed'
  204. )
  205. self.addCleanup(shutil.rmtree, venv_dir, ignore_errors=True)
  206. pep8_bin = os.path.join(venv_dir, 'bin', 'pep8')
  207. if salt.utils.platform.is_windows():
  208. pep8_bin = os.path.join(venv_dir, 'Scripts', 'pep8.exe')
  209. self.assertSaltTrueReturn(ret)
  210. self.assertTrue(
  211. os.path.isfile(pep8_bin)
  212. )
  213. def test_issue_2087_missing_pip(self):
  214. venv_dir = os.path.join(
  215. RUNTIME_VARS.TMP, 'issue-2087-missing-pip'
  216. )
  217. # Let's create the testing virtualenv
  218. ret = self._create_virtualenv(venv_dir)
  219. self.assertEqual(
  220. ret['retcode'], 0,
  221. msg='Expected \'retcode\' key did not match. Full return dictionary:\n{}'.format(
  222. pprint.pformat(ret)
  223. )
  224. )
  225. # Let's remove the pip binary
  226. pip_bin = os.path.join(venv_dir, 'bin', 'pip')
  227. site_dir = self.run_function('virtualenv.get_distribution_path', [venv_dir, 'pip'])
  228. if salt.utils.platform.is_windows():
  229. pip_bin = os.path.join(venv_dir, 'Scripts', 'pip.exe')
  230. site_dir = os.path.join(venv_dir, 'lib', 'site-packages')
  231. if not os.path.isfile(pip_bin):
  232. self.skipTest(
  233. 'Failed to find the pip binary to the test virtualenv'
  234. )
  235. os.remove(pip_bin)
  236. # Also remove the pip dir from site-packages
  237. # This is needed now that we're using python -m pip instead of the
  238. # pip binary directly. python -m pip will still work even if the
  239. # pip binary is missing
  240. shutil.rmtree(os.path.join(site_dir, 'pip'))
  241. # Let's run the state which should fail because pip is missing
  242. ret = self.run_function('state.sls', mods='issue-2087-missing-pip')
  243. self.assertSaltFalseReturn(ret)
  244. self.assertInSaltComment(
  245. 'Error installing \'pep8\': Could not find a `pip` binary',
  246. ret
  247. )
  248. def test_issue_5940_multiple_pip_mirrors(self):
  249. '''
  250. Test multiple pip mirrors. This test only works with pip < 7.0.0
  251. '''
  252. ret = self.run_function(
  253. 'state.sls', mods='issue-5940-multiple-pip-mirrors'
  254. )
  255. venv_dir = os.path.join(
  256. RUNTIME_VARS.TMP, '5940-multiple-pip-mirrors'
  257. )
  258. self.addCleanup(shutil.rmtree, venv_dir, ignore_errors=True)
  259. try:
  260. self.assertSaltTrueReturn(ret)
  261. self.assertTrue(
  262. os.path.isfile(os.path.join(venv_dir, 'bin', 'pep8'))
  263. )
  264. except (AssertionError, CommandExecutionError):
  265. pip_version = self.run_function('pip.version', [venv_dir])
  266. if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='7.0.0'):
  267. self.skipTest('the --mirrors arg has been deprecated and removed in pip==7.0.0')
  268. @pytest.mark.destructive_test
  269. @pytest.mark.skip_if_not_root
  270. @with_system_user('issue-6912', on_existing='delete', delete=True,
  271. password='PassWord1!')
  272. @with_tempdir()
  273. def test_issue_6912_wrong_owner(self, temp_dir, username):
  274. # Setup virtual environment directory to be used throughout the test
  275. venv_dir = os.path.join(temp_dir, '6912-wrong-owner')
  276. # The virtual environment needs to be in a location that is accessible
  277. # by both the user running the test and the runas user
  278. if salt.utils.platform.is_windows():
  279. salt.utils.win_dacl.set_permissions(temp_dir, username, 'full_control')
  280. else:
  281. uid = self.run_function('file.user_to_uid', [username])
  282. os.chown(temp_dir, uid, -1)
  283. # Create the virtual environment
  284. venv_create = self.run_function(
  285. 'virtualenv.create', [venv_dir], user=username,
  286. password='PassWord1!')
  287. if venv_create['retcode'] > 0:
  288. self.skipTest('Failed to create testcase virtual environment: {0}'
  289. ''.format(venv_create))
  290. # pip install passing the package name in `name`
  291. ret = self.run_state(
  292. 'pip.installed', name='pep8', user=username, bin_env=venv_dir,
  293. password='PassWord1!')
  294. self.assertSaltTrueReturn(ret)
  295. if HAS_PWD:
  296. uid = pwd.getpwnam(username).pw_uid
  297. for globmatch in (os.path.join(venv_dir, '**', 'pep8*'),
  298. os.path.join(venv_dir, '*', '**', 'pep8*'),
  299. os.path.join(venv_dir, '*', '*', '**', 'pep8*')):
  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(
  305. salt.utils.win_dacl.get_owner(path), username)
  306. @pytest.mark.destructive_test
  307. @pytest.mark.skip_if_not_root
  308. @skipIf(salt.utils.platform.is_darwin(), 'Test is flaky on macosx')
  309. @with_system_user('issue-6912', on_existing='delete', delete=True,
  310. password='PassWord1!')
  311. @with_tempdir()
  312. def test_issue_6912_wrong_owner_requirements_file(self, temp_dir, username):
  313. # Setup virtual environment directory to be used throughout the test
  314. venv_dir = os.path.join(temp_dir, '6912-wrong-owner')
  315. # The virtual environment needs to be in a location that is accessible
  316. # by both the user running the test and the runas user
  317. if salt.utils.platform.is_windows():
  318. salt.utils.win_dacl.set_permissions(temp_dir, username, 'full_control')
  319. else:
  320. uid = self.run_function('file.user_to_uid', [username])
  321. os.chown(temp_dir, uid, -1)
  322. # Create the virtual environment again as it should have been removed
  323. venv_create = self.run_function(
  324. 'virtualenv.create', [venv_dir], user=username,
  325. password='PassWord1!')
  326. if venv_create['retcode'] > 0:
  327. self.skipTest('failed to create testcase virtual environment: {0}'
  328. ''.format(venv_create))
  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', name='', user=username, bin_env=venv_dir,
  337. requirements='salt://issue-6912-requirements.txt',
  338. password='PassWord1!')
  339. self.assertSaltTrueReturn(ret)
  340. if HAS_PWD:
  341. uid = pwd.getpwnam(username).pw_uid
  342. for globmatch in (os.path.join(venv_dir, '**', 'pep8*'),
  343. os.path.join(venv_dir, '*', '**', 'pep8*'),
  344. os.path.join(venv_dir, '*', '*', '**', 'pep8*')):
  345. for path in glob.glob(globmatch):
  346. if HAS_PWD:
  347. self.assertEqual(uid, os.stat(path).st_uid)
  348. elif salt.utils.platform.is_windows():
  349. self.assertEqual(
  350. salt.utils.win_dacl.get_owner(path), username)
  351. def test_issue_6833_pip_upgrade_pip(self):
  352. # Create the testing virtualenv
  353. venv_dir = os.path.join(
  354. RUNTIME_VARS.TMP, '6833-pip-upgrade-pip'
  355. )
  356. ret = self._create_virtualenv(venv_dir)
  357. self.assertEqual(
  358. ret['retcode'], 0,
  359. msg='Expected \'retcode\' key did not match. Full return dictionary:\n{}'.format(
  360. pprint.pformat(ret)
  361. )
  362. )
  363. self.assertIn(
  364. 'New python executable',
  365. ret['stdout'],
  366. msg='Expected STDOUT did not match. Full return dictionary:\n{}'.format(
  367. pprint.pformat(ret)
  368. )
  369. )
  370. # Let's install a fixed version pip over whatever pip was
  371. # previously installed
  372. ret = self.run_function(
  373. 'pip.install', ['pip==8.0'], upgrade=True,
  374. bin_env=venv_dir
  375. )
  376. if not isinstance(ret, dict):
  377. self.fail(
  378. 'The \'pip.install\' command did not return the excepted dictionary. Output:\n{}'.format(ret)
  379. )
  380. self.assertEqual(ret['retcode'], 0)
  381. self.assertIn(
  382. 'Successfully installed pip',
  383. ret['stdout']
  384. )
  385. # Let's make sure we have pip 8.0 installed
  386. self.assertEqual(
  387. self.run_function('pip.list', ['pip'], bin_env=venv_dir),
  388. {'pip': '8.0.0'}
  389. )
  390. # Now the actual pip upgrade pip test
  391. ret = self.run_state(
  392. 'pip.installed', name='pip==8.0.1', upgrade=True,
  393. bin_env=venv_dir
  394. )
  395. if not isinstance(ret, dict):
  396. self.fail(
  397. 'The \'pip.install\' command did not return the excepted dictionary. Output:\n{}'.format(ret)
  398. )
  399. self.assertSaltTrueReturn(ret)
  400. self.assertSaltStateChangesEqual(ret, {'pip==8.0.1': 'Installed'})
  401. def test_pip_installed_specific_env(self):
  402. # Create the testing virtualenv
  403. venv_dir = os.path.join(
  404. RUNTIME_VARS.TMP, 'pip-installed-specific-env'
  405. )
  406. # Let's write a requirements file
  407. requirements_file = os.path.join(
  408. RUNTIME_VARS.TMP_PRODENV_STATE_TREE, 'prod-env-requirements.txt'
  409. )
  410. with salt.utils.files.fopen(requirements_file, 'wb') as reqf:
  411. reqf.write(b'pep8\n')
  412. try:
  413. self._create_virtualenv(venv_dir)
  414. # The requirements file should not be found the base environment
  415. ret = self.run_state(
  416. 'pip.installed', name='', bin_env=venv_dir,
  417. requirements='salt://prod-env-requirements.txt'
  418. )
  419. self.assertSaltFalseReturn(ret)
  420. self.assertInSaltComment(
  421. "'salt://prod-env-requirements.txt' not found", ret
  422. )
  423. # The requirements file must be found in the prod environment
  424. ret = self.run_state(
  425. 'pip.installed', name='', bin_env=venv_dir, saltenv='prod',
  426. requirements='salt://prod-env-requirements.txt'
  427. )
  428. self.assertSaltTrueReturn(ret)
  429. self.assertInSaltComment(
  430. 'Successfully processed requirements file '
  431. 'salt://prod-env-requirements.txt', ret
  432. )
  433. # We're using the base environment but we're passing the prod
  434. # environment as an url arg to salt://
  435. ret = self.run_state(
  436. 'pip.installed', name='', bin_env=venv_dir,
  437. requirements='salt://prod-env-requirements.txt?saltenv=prod'
  438. )
  439. self.assertSaltTrueReturn(ret)
  440. self.assertInSaltComment(
  441. 'Requirements were already installed.',
  442. ret
  443. )
  444. finally:
  445. if os.path.isfile(requirements_file):
  446. os.unlink(requirements_file)
  447. @skipIf(salt.utils.platform.is_darwin() and six.PY2, 'This test hangs on OS X on Py2')
  448. def test_22359_pip_installed_unless_does_not_trigger_warnings(self):
  449. # This test case should be moved to a format_call unit test specific to
  450. # the state internal keywords
  451. venv_dir = os.path.join(RUNTIME_VARS.TMP, 'pip-installed-unless')
  452. venv_create = self._create_virtualenv(venv_dir)
  453. if venv_create['retcode'] > 0:
  454. self.skipTest(
  455. 'Failed to create testcase virtual environment: {0}'.format(
  456. venv_create
  457. )
  458. )
  459. false_cmd = salt.utils.path.which('false')
  460. if salt.utils.platform.is_windows():
  461. false_cmd = 'exit 1 >nul'
  462. try:
  463. ret = self.run_state(
  464. 'pip.installed', name='pep8', bin_env=venv_dir, unless=false_cmd, timeout=600
  465. )
  466. self.assertSaltTrueReturn(ret)
  467. self.assertNotIn('warnings', next(six.itervalues(ret)))
  468. finally:
  469. if os.path.isdir(venv_dir):
  470. shutil.rmtree(venv_dir, ignore_errors=True)
  471. @skipIf(sys.version_info[:2] >= (3, 6), 'Old version of virtualenv too old for python3.6')
  472. @skipIf(salt.utils.platform.is_windows(), "Carbon does not install in Windows")
  473. def test_46127_pip_env_vars(self):
  474. '''
  475. Test that checks if env_vars passed to pip.installed are also passed
  476. to pip.freeze while checking for existing installations
  477. '''
  478. # This issue is most easily checked while installing carbon
  479. # Much of the code here comes from the test_weird_install function above
  480. ographite = '/opt/graphite'
  481. if os.path.isdir(ographite):
  482. self.skipTest(
  483. 'You already have \'{0}\'. This test would overwrite this '
  484. 'directory'.format(ographite)
  485. )
  486. try:
  487. os.makedirs(ographite)
  488. except OSError as err:
  489. if err.errno == errno.EACCES:
  490. # Permission denied
  491. self.skipTest(
  492. 'You don\'t have the required permissions to run this test'
  493. )
  494. finally:
  495. if os.path.isdir(ographite):
  496. shutil.rmtree(ographite, ignore_errors=True)
  497. venv_dir = os.path.join(RUNTIME_VARS.TMP, 'issue-46127-pip-env-vars')
  498. try:
  499. # We may be able to remove this, I had to add it because the custom
  500. # modules from the test suite weren't available in the jinja
  501. # context when running the call to state.sls that comes after.
  502. self.run_function('saltutil.sync_modules')
  503. # Since we don't have the virtualenv created, pip.installed will
  504. # throw an error.
  505. ret = self.run_function(
  506. 'state.sls', mods='issue-46127-pip-env-vars'
  507. )
  508. self.assertSaltTrueReturn(ret)
  509. for key in six.iterkeys(ret):
  510. self.assertTrue(ret[key]['result'])
  511. if ret[key]['name'] != 'carbon < 1.3':
  512. continue
  513. self.assertEqual(
  514. ret[key]['comment'],
  515. 'All packages were successfully installed'
  516. )
  517. break
  518. else:
  519. raise Exception('Expected state did not run')
  520. # Run the state again. Now the already installed message should
  521. # appear
  522. ret = self.run_function(
  523. 'state.sls', mods='issue-46127-pip-env-vars'
  524. )
  525. self.assertSaltTrueReturn(ret)
  526. # We cannot use assertInSaltComment here because we need to skip
  527. # some of the state return parts
  528. for key in six.iterkeys(ret):
  529. self.assertTrue(ret[key]['result'])
  530. # As we are re-running the formula, some states will not be run
  531. # and "name" may or may not be present, so we use .get() pattern
  532. if ret[key].get('name', '') != 'carbon < 1.3':
  533. continue
  534. self.assertEqual(
  535. ret[key]['comment'],
  536. ('All packages were successfully installed'))
  537. break
  538. else:
  539. raise Exception('Expected state did not run')
  540. finally:
  541. if os.path.isdir(ographite):
  542. shutil.rmtree(ographite, ignore_errors=True)
  543. if os.path.isdir(venv_dir):
  544. shutil.rmtree(venv_dir)
  545. class PipStateInRequisiteTest(ModuleCase, SaltReturnAssertsMixin):
  546. @with_tempdir()
  547. def test_issue_54755(self, tmpdir):
  548. '''
  549. Verify github issue 54755 is resolved. This only fails when there is no
  550. pip module in the python environment. Since the test suite normally has
  551. a pip module this test will pass and is here for posterity. See also
  552. unit.states.test_pip_state.PipStateUtilsTest.test_pip_purge_method_with_pip
  553. and
  554. unit.states.test_pip_state.PipStateUtilsTest.test_pip_purge_method_without_pip
  555. Which also validate this issue and will pass/fail regardless of whether
  556. or not pip is installed.
  557. '''
  558. file_path = os.path.join(tmpdir, 'issue-54755')
  559. ret = self.run_function('state.sls', mods='issue-54755', pillar={'file_path': file_path})
  560. key = 'file_|-issue-54755_|-{}_|-managed'.format(file_path)
  561. assert key in ret
  562. assert ret[key]['result'] is True
  563. with salt.utils.files.fopen(file_path, 'r') as fp:
  564. assert fp.read().strip() == 'issue-54755'