test_pillar.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. # -*- coding: utf-8 -*-
  2. '''
  3. :codeauthor: Pedro Algarvio (pedro@algarvio.me)
  4. :codeauthor: Alexandru Bleotu (alexandru.bleotu@morganstanley.com)
  5. tests.unit.pillar_test
  6. ~~~~~~~~~~~~~~~~~~~~~~
  7. '''
  8. # Import python libs
  9. from __future__ import absolute_import
  10. import shutil
  11. import tempfile
  12. # Import Salt Testing libs
  13. from tests.support.helpers import with_tempdir
  14. from tests.support.unit import skipIf, TestCase
  15. from tests.support.mock import NO_MOCK, NO_MOCK_REASON, MagicMock, patch
  16. from tests.support.paths import TMP
  17. # Import salt libs
  18. import salt.fileclient
  19. import salt.pillar
  20. import salt.utils.stringutils
  21. import salt.exceptions
  22. class MockFileclient(object):
  23. def __init__(self, cache_file=None, get_state=None, list_states=None):
  24. if cache_file is not None:
  25. self.cache_file = lambda *x, **y: cache_file
  26. if get_state is not None:
  27. self.get_state = lambda sls, env: get_state[sls]
  28. if list_states is not None:
  29. self.list_states = lambda *x, **y: list_states
  30. # pylint: disable=unused-argument,no-method-argument,method-hidden
  31. def cache_file(*args, **kwargs):
  32. raise NotImplementedError()
  33. def get_state(*args, **kwargs):
  34. raise NotImplementedError()
  35. def list_states(*args, **kwargs):
  36. raise NotImplementedError()
  37. # pylint: enable=unused-argument,no-method-argument,method-hidden
  38. @skipIf(NO_MOCK, NO_MOCK_REASON)
  39. class PillarTestCase(TestCase):
  40. def tearDown(self):
  41. for attrname in ('generic_file', 'generic_minion_file', 'ssh_file', 'ssh_minion_file', 'top_file'):
  42. try:
  43. delattr(self, attrname)
  44. except AttributeError:
  45. continue
  46. def test_pillarenv_from_saltenv(self):
  47. with patch('salt.pillar.compile_template') as compile_template:
  48. opts = {
  49. 'optimization_order': [0, 1, 2],
  50. 'renderer': 'json',
  51. 'renderer_blacklist': [],
  52. 'renderer_whitelist': [],
  53. 'state_top': '',
  54. 'pillar_roots': {
  55. 'dev': [],
  56. 'base': []
  57. },
  58. 'file_roots': {
  59. 'dev': [],
  60. 'base': []
  61. },
  62. 'extension_modules': '',
  63. 'pillarenv_from_saltenv': True
  64. }
  65. grains = {
  66. 'os': 'Ubuntu',
  67. }
  68. pillar = salt.pillar.Pillar(opts, grains, 'mocked-minion', 'dev')
  69. self.assertEqual(pillar.opts['saltenv'], 'dev')
  70. self.assertEqual(pillar.opts['pillarenv'], 'dev')
  71. def test_ext_pillar_no_extra_minion_data_val_dict(self):
  72. opts = {
  73. 'optimization_order': [0, 1, 2],
  74. 'renderer': 'json',
  75. 'renderer_blacklist': [],
  76. 'renderer_whitelist': [],
  77. 'state_top': '',
  78. 'pillar_roots': {
  79. 'dev': [],
  80. 'base': []
  81. },
  82. 'file_roots': {
  83. 'dev': [],
  84. 'base': []
  85. },
  86. 'extension_modules': '',
  87. 'pillarenv_from_saltenv': True
  88. }
  89. mock_ext_pillar_func = MagicMock()
  90. with patch('salt.loader.pillars',
  91. MagicMock(return_value={'fake_ext_pillar':
  92. mock_ext_pillar_func})):
  93. pillar = salt.pillar.Pillar(opts, {}, 'mocked-minion', 'dev')
  94. # ext pillar function doesn't have the extra_minion_data arg
  95. with patch('salt.utils.args.get_function_argspec',
  96. MagicMock(return_value=MagicMock(args=[]))):
  97. pillar._external_pillar_data('fake_pillar', {'arg': 'foo'},
  98. 'fake_ext_pillar')
  99. mock_ext_pillar_func.assert_called_once_with('mocked-minion',
  100. 'fake_pillar',
  101. arg='foo')
  102. # ext pillar function has the extra_minion_data arg
  103. mock_ext_pillar_func.reset_mock()
  104. with patch('salt.utils.args.get_function_argspec',
  105. MagicMock(return_value=MagicMock(args=['extra_minion_data']))):
  106. pillar._external_pillar_data('fake_pillar', {'arg': 'foo'},
  107. 'fake_ext_pillar')
  108. mock_ext_pillar_func.assert_called_once_with('mocked-minion',
  109. 'fake_pillar',
  110. arg='foo')
  111. def test_ext_pillar_no_extra_minion_data_val_list(self):
  112. opts = {
  113. 'optimization_order': [0, 1, 2],
  114. 'renderer': 'json',
  115. 'renderer_blacklist': [],
  116. 'renderer_whitelist': [],
  117. 'state_top': '',
  118. 'pillar_roots': {
  119. 'dev': [],
  120. 'base': []
  121. },
  122. 'file_roots': {
  123. 'dev': [],
  124. 'base': []
  125. },
  126. 'extension_modules': '',
  127. 'pillarenv_from_saltenv': True
  128. }
  129. mock_ext_pillar_func = MagicMock()
  130. with patch('salt.loader.pillars',
  131. MagicMock(return_value={'fake_ext_pillar':
  132. mock_ext_pillar_func})):
  133. pillar = salt.pillar.Pillar(opts, {}, 'mocked-minion', 'dev')
  134. # ext pillar function doesn't have the extra_minion_data arg
  135. with patch('salt.utils.args.get_function_argspec',
  136. MagicMock(return_value=MagicMock(args=[]))):
  137. pillar._external_pillar_data('fake_pillar', ['foo'],
  138. 'fake_ext_pillar')
  139. mock_ext_pillar_func.assert_called_once_with('mocked-minion',
  140. 'fake_pillar',
  141. 'foo')
  142. # ext pillar function has the extra_minion_data arg
  143. mock_ext_pillar_func.reset_mock()
  144. with patch('salt.utils.args.get_function_argspec',
  145. MagicMock(return_value=MagicMock(args=['extra_minion_data']))):
  146. pillar._external_pillar_data('fake_pillar', ['foo'],
  147. 'fake_ext_pillar')
  148. mock_ext_pillar_func.assert_called_once_with('mocked-minion',
  149. 'fake_pillar',
  150. 'foo')
  151. def test_ext_pillar_no_extra_minion_data_val_elem(self):
  152. opts = {
  153. 'optimization_order': [0, 1, 2],
  154. 'renderer': 'json',
  155. 'renderer_blacklist': [],
  156. 'renderer_whitelist': [],
  157. 'state_top': '',
  158. 'pillar_roots': {
  159. 'dev': [],
  160. 'base': []
  161. },
  162. 'file_roots': {
  163. 'dev': [],
  164. 'base': []
  165. },
  166. 'extension_modules': '',
  167. 'pillarenv_from_saltenv': True
  168. }
  169. mock_ext_pillar_func = MagicMock()
  170. with patch('salt.loader.pillars',
  171. MagicMock(return_value={'fake_ext_pillar':
  172. mock_ext_pillar_func})):
  173. pillar = salt.pillar.Pillar(opts, {}, 'mocked-minion', 'dev')
  174. # ext pillar function doesn't have the extra_minion_data arg
  175. with patch('salt.utils.args.get_function_argspec',
  176. MagicMock(return_value=MagicMock(args=[]))):
  177. pillar._external_pillar_data('fake_pillar', 'fake_val',
  178. 'fake_ext_pillar')
  179. mock_ext_pillar_func.assert_called_once_with('mocked-minion',
  180. 'fake_pillar', 'fake_val')
  181. # ext pillar function has the extra_minion_data arg
  182. mock_ext_pillar_func.reset_mock()
  183. with patch('salt.utils.args.get_function_argspec',
  184. MagicMock(return_value=MagicMock(args=['extra_minion_data']))):
  185. pillar._external_pillar_data('fake_pillar', 'fake_val',
  186. 'fake_ext_pillar')
  187. mock_ext_pillar_func.assert_called_once_with('mocked-minion',
  188. 'fake_pillar', 'fake_val')
  189. def test_ext_pillar_with_extra_minion_data_val_dict(self):
  190. opts = {
  191. 'optimization_order': [0, 1, 2],
  192. 'renderer': 'json',
  193. 'renderer_blacklist': [],
  194. 'renderer_whitelist': [],
  195. 'state_top': '',
  196. 'pillar_roots': {
  197. 'dev': [],
  198. 'base': []
  199. },
  200. 'file_roots': {
  201. 'dev': [],
  202. 'base': []
  203. },
  204. 'extension_modules': '',
  205. 'pillarenv_from_saltenv': True
  206. }
  207. mock_ext_pillar_func = MagicMock()
  208. with patch('salt.loader.pillars',
  209. MagicMock(return_value={'fake_ext_pillar':
  210. mock_ext_pillar_func})):
  211. pillar = salt.pillar.Pillar(opts, {}, 'mocked-minion', 'dev',
  212. extra_minion_data={'fake_key': 'foo'})
  213. # ext pillar function doesn't have the extra_minion_data arg
  214. with patch('salt.utils.args.get_function_argspec',
  215. MagicMock(return_value=MagicMock(args=[]))):
  216. pillar._external_pillar_data('fake_pillar', {'arg': 'foo'},
  217. 'fake_ext_pillar')
  218. mock_ext_pillar_func.assert_called_once_with(
  219. 'mocked-minion', 'fake_pillar', arg='foo')
  220. # ext pillar function has the extra_minion_data arg
  221. mock_ext_pillar_func.reset_mock()
  222. with patch('salt.utils.args.get_function_argspec',
  223. MagicMock(return_value=MagicMock(args=['extra_minion_data']))):
  224. pillar._external_pillar_data('fake_pillar', {'arg': 'foo'},
  225. 'fake_ext_pillar')
  226. mock_ext_pillar_func.assert_called_once_with(
  227. 'mocked-minion', 'fake_pillar', arg='foo',
  228. extra_minion_data={'fake_key': 'foo'})
  229. def test_ext_pillar_with_extra_minion_data_val_list(self):
  230. opts = {
  231. 'optimization_order': [0, 1, 2],
  232. 'renderer': 'json',
  233. 'renderer_blacklist': [],
  234. 'renderer_whitelist': [],
  235. 'state_top': '',
  236. 'pillar_roots': {
  237. 'dev': [],
  238. 'base': []
  239. },
  240. 'file_roots': {
  241. 'dev': [],
  242. 'base': []
  243. },
  244. 'extension_modules': '',
  245. 'pillarenv_from_saltenv': True
  246. }
  247. mock_ext_pillar_func = MagicMock()
  248. with patch('salt.loader.pillars',
  249. MagicMock(return_value={'fake_ext_pillar':
  250. mock_ext_pillar_func})):
  251. pillar = salt.pillar.Pillar(opts, {}, 'mocked-minion', 'dev',
  252. extra_minion_data={'fake_key': 'foo'})
  253. # ext pillar function doesn't have the extra_minion_data arg
  254. with patch('salt.utils.args.get_function_argspec',
  255. MagicMock(return_value=MagicMock(args=[]))):
  256. pillar._external_pillar_data('fake_pillar', ['bar'],
  257. 'fake_ext_pillar')
  258. mock_ext_pillar_func.assert_called_once_with(
  259. 'mocked-minion', 'fake_pillar', 'bar')
  260. # ext pillar function has the extra_minion_data arg
  261. mock_ext_pillar_func.reset_mock()
  262. with patch('salt.utils.args.get_function_argspec',
  263. MagicMock(return_value=MagicMock(args=['extra_minion_data']))):
  264. pillar._external_pillar_data('fake_pillar', ['bar'],
  265. 'fake_ext_pillar')
  266. mock_ext_pillar_func.assert_called_once_with(
  267. 'mocked-minion', 'fake_pillar', 'bar',
  268. extra_minion_data={'fake_key': 'foo'})
  269. def test_ext_pillar_with_extra_minion_data_val_elem(self):
  270. opts = {
  271. 'optimization_order': [0, 1, 2],
  272. 'renderer': 'json',
  273. 'renderer_blacklist': [],
  274. 'renderer_whitelist': [],
  275. 'state_top': '',
  276. 'pillar_roots': {
  277. 'dev': [],
  278. 'base': []
  279. },
  280. 'file_roots': {
  281. 'dev': [],
  282. 'base': []
  283. },
  284. 'extension_modules': '',
  285. 'pillarenv_from_saltenv': True
  286. }
  287. mock_ext_pillar_func = MagicMock()
  288. with patch('salt.loader.pillars',
  289. MagicMock(return_value={'fake_ext_pillar':
  290. mock_ext_pillar_func})):
  291. pillar = salt.pillar.Pillar(opts, {}, 'mocked-minion', 'dev',
  292. extra_minion_data={'fake_key': 'foo'})
  293. # ext pillar function doesn't have the extra_minion_data arg
  294. with patch('salt.utils.args.get_function_argspec',
  295. MagicMock(return_value=MagicMock(args=[]))):
  296. pillar._external_pillar_data('fake_pillar', 'bar',
  297. 'fake_ext_pillar')
  298. mock_ext_pillar_func.assert_called_once_with(
  299. 'mocked-minion', 'fake_pillar', 'bar')
  300. # ext pillar function has the extra_minion_data arg
  301. mock_ext_pillar_func.reset_mock()
  302. with patch('salt.utils.args.get_function_argspec',
  303. MagicMock(return_value=MagicMock(args=['extra_minion_data']))):
  304. pillar._external_pillar_data('fake_pillar', 'bar',
  305. 'fake_ext_pillar')
  306. mock_ext_pillar_func.assert_called_once_with(
  307. 'mocked-minion', 'fake_pillar', 'bar',
  308. extra_minion_data={'fake_key': 'foo'})
  309. def test_dynamic_pillarenv(self):
  310. opts = {
  311. 'optimization_order': [0, 1, 2],
  312. 'renderer': 'json',
  313. 'renderer_blacklist': [],
  314. 'renderer_whitelist': [],
  315. 'state_top': '',
  316. 'pillar_roots': {'__env__': ['/srv/pillar/__env__'], 'base': ['/srv/pillar/base']},
  317. 'file_roots': {'base': ['/srv/salt/base'], 'dev': ['/svr/salt/dev']},
  318. 'extension_modules': '',
  319. }
  320. pillar = salt.pillar.Pillar(opts, {}, 'mocked-minion', 'base', pillarenv='dev')
  321. self.assertEqual(pillar.opts['pillar_roots'],
  322. {'base': ['/srv/pillar/base'], 'dev': ['/srv/pillar/__env__']})
  323. def test_ignored_dynamic_pillarenv(self):
  324. opts = {
  325. 'optimization_order': [0, 1, 2],
  326. 'renderer': 'json',
  327. 'renderer_blacklist': [],
  328. 'renderer_whitelist': [],
  329. 'state_top': '',
  330. 'pillar_roots': {'__env__': ['/srv/pillar/__env__'], 'base': ['/srv/pillar/base']},
  331. 'file_roots': {'base': ['/srv/salt/base'], 'dev': ['/svr/salt/dev']},
  332. 'extension_modules': '',
  333. }
  334. pillar = salt.pillar.Pillar(opts, {}, 'mocked-minion', 'base', pillarenv='base')
  335. self.assertEqual(pillar.opts['pillar_roots'], {'base': ['/srv/pillar/base']})
  336. @patch('salt.fileclient.Client.list_states')
  337. def test_malformed_pillar_sls(self, mock_list_states):
  338. with patch('salt.pillar.compile_template') as compile_template:
  339. opts = {
  340. 'optimization_order': [0, 1, 2],
  341. 'renderer': 'json',
  342. 'renderer_blacklist': [],
  343. 'renderer_whitelist': [],
  344. 'state_top': '',
  345. 'pillar_roots': [],
  346. 'file_roots': [],
  347. 'extension_modules': ''
  348. }
  349. grains = {
  350. 'os': 'Ubuntu',
  351. 'os_family': 'Debian',
  352. 'oscodename': 'raring',
  353. 'osfullname': 'Ubuntu',
  354. 'osrelease': '13.04',
  355. 'kernel': 'Linux'
  356. }
  357. mock_list_states.return_value = ['foo', 'blah']
  358. pillar = salt.pillar.Pillar(opts, grains, 'mocked-minion', 'base')
  359. # Mock getting the proper template files
  360. pillar.client.get_state = MagicMock(
  361. return_value={
  362. 'dest': '/path/to/pillar/files/foo.sls',
  363. 'source': 'salt://foo.sls'
  364. }
  365. )
  366. # Template compilation returned a string
  367. compile_template.return_value = 'BAHHH'
  368. self.assertEqual(
  369. pillar.render_pillar({'base': ['foo.sls']}),
  370. ({}, ['SLS \'foo.sls\' does not render to a dictionary'])
  371. )
  372. # Template compilation returned a list
  373. compile_template.return_value = ['BAHHH']
  374. self.assertEqual(
  375. pillar.render_pillar({'base': ['foo.sls']}),
  376. ({}, ['SLS \'foo.sls\' does not render to a dictionary'])
  377. )
  378. # Template compilation returned a dictionary, which is what's expected
  379. compile_template.return_value = {'foo': 'bar'}
  380. self.assertEqual(
  381. pillar.render_pillar({'base': ['foo.sls']}),
  382. ({'foo': 'bar'}, [])
  383. )
  384. # Test improper includes
  385. compile_template.side_effect = [
  386. {'foo': 'bar', 'include': 'blah'},
  387. {'foo2': 'bar2'}
  388. ]
  389. self.assertEqual(
  390. pillar.render_pillar({'base': ['foo.sls']}),
  391. ({'foo': 'bar', 'include': 'blah'},
  392. ["Include Declaration in SLS 'foo.sls' is not formed as a list"])
  393. )
  394. # Test includes as a list, which is what's expected
  395. compile_template.side_effect = [
  396. {'foo': 'bar', 'include': ['blah']},
  397. {'foo2': 'bar2'}
  398. ]
  399. self.assertEqual(
  400. pillar.render_pillar({'base': ['foo.sls']}),
  401. ({'foo': 'bar', 'foo2': 'bar2'}, [])
  402. )
  403. # Test includes as a list overriding data
  404. compile_template.side_effect = [
  405. {'foo': 'bar', 'include': ['blah']},
  406. {'foo': 'bar2'}
  407. ]
  408. self.assertEqual(
  409. pillar.render_pillar({'base': ['foo.sls']}),
  410. ({'foo': 'bar'}, [])
  411. )
  412. # Test includes using empty key directive
  413. compile_template.side_effect = [
  414. {'foo': 'bar', 'include': [{'blah': {'key': ''}}]},
  415. {'foo': 'bar2'}
  416. ]
  417. self.assertEqual(
  418. pillar.render_pillar({'base': ['foo.sls']}),
  419. ({'foo': 'bar'}, [])
  420. )
  421. # Test includes using simple non-nested key
  422. compile_template.side_effect = [
  423. {'foo': 'bar', 'include': [{'blah': {'key': 'nested'}}]},
  424. {'foo': 'bar2'}
  425. ]
  426. self.assertEqual(
  427. pillar.render_pillar({'base': ['foo.sls']}),
  428. ({'foo': 'bar', 'nested': {'foo': 'bar2'}}, [])
  429. )
  430. # Test includes using nested key
  431. compile_template.side_effect = [
  432. {'foo': 'bar', 'include': [{'blah': {'key': 'nested:level'}}]},
  433. {'foo': 'bar2'}
  434. ]
  435. self.assertEqual(
  436. pillar.render_pillar({'base': ['foo.sls']}),
  437. ({'foo': 'bar', 'nested': {'level': {'foo': 'bar2'}}}, [])
  438. )
  439. def test_includes_override_sls(self):
  440. opts = {
  441. 'optimization_order': [0, 1, 2],
  442. 'renderer': 'json',
  443. 'renderer_blacklist': [],
  444. 'renderer_whitelist': [],
  445. 'state_top': '',
  446. 'pillar_roots': {},
  447. 'file_roots': {},
  448. 'extension_modules': ''
  449. }
  450. grains = {
  451. 'os': 'Ubuntu',
  452. 'os_family': 'Debian',
  453. 'oscodename': 'raring',
  454. 'osfullname': 'Ubuntu',
  455. 'osrelease': '13.04',
  456. 'kernel': 'Linux'
  457. }
  458. with patch('salt.pillar.compile_template') as compile_template, \
  459. patch.object(salt.pillar.Pillar, '_Pillar__gather_avail',
  460. MagicMock(return_value={'base': ['blah', 'foo']})):
  461. # Test with option set to True
  462. opts['pillar_includes_override_sls'] = True
  463. pillar = salt.pillar.Pillar(opts, grains, 'mocked-minion', 'base')
  464. # Mock getting the proper template files
  465. pillar.client.get_state = MagicMock(
  466. return_value={
  467. 'dest': '/path/to/pillar/files/foo.sls',
  468. 'source': 'salt://foo.sls'
  469. }
  470. )
  471. compile_template.side_effect = [
  472. {'foo': 'bar', 'include': ['blah']},
  473. {'foo': 'bar2'}
  474. ]
  475. self.assertEqual(
  476. pillar.render_pillar({'base': ['foo.sls']}),
  477. ({'foo': 'bar2'}, [])
  478. )
  479. # Test with option set to False
  480. opts['pillar_includes_override_sls'] = False
  481. pillar = salt.pillar.Pillar(opts, grains, 'mocked-minion', 'base')
  482. # Mock getting the proper template files
  483. pillar.client.get_state = MagicMock(
  484. return_value={
  485. 'dest': '/path/to/pillar/files/foo.sls',
  486. 'source': 'salt://foo.sls'
  487. }
  488. )
  489. compile_template.side_effect = [
  490. {'foo': 'bar', 'include': ['blah']},
  491. {'foo': 'bar2'}
  492. ]
  493. self.assertEqual(
  494. pillar.render_pillar({'base': ['foo.sls']}),
  495. ({'foo': 'bar'}, [])
  496. )
  497. def test_topfile_order(self):
  498. opts = {
  499. 'optimization_order': [0, 1, 2],
  500. 'renderer': 'yaml',
  501. 'renderer_blacklist': [],
  502. 'renderer_whitelist': [],
  503. 'state_top': '',
  504. 'pillar_roots': [],
  505. 'extension_modules': '',
  506. 'saltenv': 'base',
  507. 'file_roots': [],
  508. }
  509. grains = {
  510. 'os': 'Ubuntu',
  511. 'os_family': 'Debian',
  512. 'oscodename': 'raring',
  513. 'osfullname': 'Ubuntu',
  514. 'osrelease': '13.04',
  515. 'kernel': 'Linux'
  516. }
  517. def _run_test(nodegroup_order, glob_order, expected):
  518. tempdir = tempfile.mkdtemp(dir=TMP)
  519. try:
  520. sls_files = self._setup_test_topfile_sls(
  521. tempdir,
  522. nodegroup_order,
  523. glob_order)
  524. fc_mock = MockFileclient(
  525. cache_file=sls_files['top']['dest'],
  526. list_states=['top', 'ssh', 'ssh.minion',
  527. 'generic', 'generic.minion'],
  528. get_state=sls_files)
  529. with patch.object(salt.fileclient, 'get_file_client',
  530. MagicMock(return_value=fc_mock)):
  531. pillar = salt.pillar.Pillar(opts, grains, 'mocked-minion', 'base')
  532. # Make sure that confirm_top.confirm_top returns True
  533. pillar.matchers['confirm_top.confirm_top'] = lambda *x, **y: True
  534. self.assertEqual(pillar.compile_pillar()['ssh'], expected)
  535. finally:
  536. shutil.rmtree(tempdir, ignore_errors=True)
  537. # test case where glob match happens second and therefore takes
  538. # precedence over nodegroup match.
  539. _run_test(nodegroup_order=1, glob_order=2, expected='bar')
  540. # test case where nodegroup match happens second and therefore takes
  541. # precedence over glob match.
  542. _run_test(nodegroup_order=2, glob_order=1, expected='foo')
  543. def _setup_test_topfile_sls(self, tempdir, nodegroup_order, glob_order):
  544. # Write a simple topfile and two pillar state files
  545. top_file = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  546. s = '''
  547. base:
  548. group:
  549. - match: nodegroup
  550. - order: {nodegroup_order}
  551. - ssh
  552. - generic
  553. '*':
  554. - generic
  555. minion:
  556. - order: {glob_order}
  557. - ssh.minion
  558. - generic.minion
  559. '''.format(nodegroup_order=nodegroup_order, glob_order=glob_order)
  560. top_file.write(salt.utils.stringutils.to_bytes(s))
  561. top_file.flush()
  562. ssh_file = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  563. ssh_file.write(b'''
  564. ssh:
  565. foo
  566. ''')
  567. ssh_file.flush()
  568. ssh_minion_file = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  569. ssh_minion_file.write(b'''
  570. ssh:
  571. bar
  572. ''')
  573. ssh_minion_file.flush()
  574. generic_file = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  575. generic_file.write(b'''
  576. generic:
  577. key1:
  578. - value1
  579. - value2
  580. key2:
  581. sub_key1: []
  582. ''')
  583. generic_file.flush()
  584. generic_minion_file = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  585. generic_minion_file.write(b'''
  586. generic:
  587. key1:
  588. - value3
  589. key2:
  590. sub_key2: []
  591. ''')
  592. generic_minion_file.flush()
  593. return {
  594. 'top': {'path': '', 'dest': top_file.name},
  595. 'ssh': {'path': '', 'dest': ssh_file.name},
  596. 'ssh.minion': {'path': '', 'dest': ssh_minion_file.name},
  597. 'generic': {'path': '', 'dest': generic_file.name},
  598. 'generic.minion': {'path': '', 'dest': generic_minion_file.name},
  599. }
  600. @with_tempdir()
  601. def test_include(self, tempdir):
  602. opts = {
  603. 'optimization_order': [0, 1, 2],
  604. 'renderer': 'yaml',
  605. 'renderer_blacklist': [],
  606. 'renderer_whitelist': [],
  607. 'state_top': '',
  608. 'pillar_roots': [],
  609. 'extension_modules': '',
  610. 'saltenv': 'base',
  611. 'file_roots': [],
  612. }
  613. grains = {
  614. 'os': 'Ubuntu',
  615. 'os_family': 'Debian',
  616. 'oscodename': 'raring',
  617. 'osfullname': 'Ubuntu',
  618. 'osrelease': '13.04',
  619. 'kernel': 'Linux',
  620. }
  621. sls_files = self._setup_test_include_sls(tempdir)
  622. fc_mock = MockFileclient(
  623. cache_file=sls_files['top']['dest'],
  624. get_state=sls_files,
  625. list_states=[
  626. 'top',
  627. 'test.init',
  628. 'test.sub1',
  629. 'test.sub2',
  630. 'test.sub_wildcard_1',
  631. 'test.sub_with_init_dot',
  632. 'test.sub.with.slashes',
  633. ],
  634. )
  635. with patch.object(salt.fileclient, 'get_file_client',
  636. MagicMock(return_value=fc_mock)):
  637. pillar = salt.pillar.Pillar(opts, grains, 'minion', 'base')
  638. # Make sure that confirm_top.confirm_top returns True
  639. pillar.matchers['confirm_top.confirm_top'] = lambda *x, **y: True
  640. compiled_pillar = pillar.compile_pillar()
  641. self.assertEqual(compiled_pillar['foo_wildcard'], 'bar_wildcard')
  642. self.assertEqual(compiled_pillar['foo1'], 'bar1')
  643. self.assertEqual(compiled_pillar['foo2'], 'bar2')
  644. self.assertEqual(compiled_pillar['sub_with_slashes'], 'sub_slashes_worked')
  645. self.assertEqual(compiled_pillar['sub_init_dot'], 'sub_with_init_dot_worked')
  646. def _setup_test_include_sls(self, tempdir):
  647. top_file = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  648. top_file.write(b'''
  649. base:
  650. '*':
  651. - order: 1
  652. - test.sub2
  653. minion:
  654. - order: 2
  655. - test
  656. ''')
  657. top_file.flush()
  658. init_sls = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  659. init_sls.write(b'''
  660. include:
  661. - test.sub1
  662. - test.sub_wildcard*
  663. - .test.sub_with_init_dot
  664. - test/sub/with/slashes
  665. ''')
  666. init_sls.flush()
  667. sub1_sls = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  668. sub1_sls.write(b'''
  669. foo1:
  670. bar1
  671. ''')
  672. sub1_sls.flush()
  673. sub2_sls = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  674. sub2_sls.write(b'''
  675. foo2:
  676. bar2
  677. ''')
  678. sub2_sls.flush()
  679. sub_wildcard_1_sls = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  680. sub_wildcard_1_sls.write(b'''
  681. foo_wildcard:
  682. bar_wildcard
  683. ''')
  684. sub_wildcard_1_sls.flush()
  685. sub_with_init_dot_sls = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  686. sub_with_init_dot_sls.write(b'''
  687. sub_init_dot:
  688. sub_with_init_dot_worked
  689. ''')
  690. sub_with_init_dot_sls.flush()
  691. sub_with_slashes_sls = tempfile.NamedTemporaryFile(dir=tempdir, delete=False)
  692. sub_with_slashes_sls.write(b'''
  693. sub_with_slashes:
  694. sub_slashes_worked
  695. ''')
  696. sub_with_slashes_sls.flush()
  697. return {
  698. 'top': {'path': '', 'dest': top_file.name},
  699. 'test': {'path': '', 'dest': init_sls.name},
  700. 'test.sub1': {'path': '', 'dest': sub1_sls.name},
  701. 'test.sub2': {'path': '', 'dest': sub2_sls.name},
  702. 'test.sub_wildcard_1': {'path': '', 'dest': sub_wildcard_1_sls.name},
  703. 'test.sub_with_init_dot': {'path': '', 'dest': sub_with_init_dot_sls.name},
  704. 'test.sub.with.slashes': {'path': '', 'dest': sub_with_slashes_sls.name},
  705. }
  706. @skipIf(NO_MOCK, NO_MOCK_REASON)
  707. @patch('salt.transport.client.ReqChannel.factory', MagicMock())
  708. class RemotePillarTestCase(TestCase):
  709. '''
  710. Tests for instantiating a RemotePillar in salt.pillar
  711. '''
  712. def setUp(self):
  713. self.grains = {}
  714. def tearDown(self):
  715. for attr in ('grains',):
  716. try:
  717. delattr(self, attr)
  718. except AttributeError:
  719. continue
  720. def test_get_opts_in_pillar_override_call(self):
  721. mock_get_extra_minion_data = MagicMock(return_value={})
  722. with patch(
  723. 'salt.pillar.RemotePillarMixin.get_ext_pillar_extra_minion_data',
  724. mock_get_extra_minion_data):
  725. salt.pillar.RemotePillar({}, self.grains, 'mocked-minion', 'dev')
  726. mock_get_extra_minion_data.assert_called_once_with(
  727. {'saltenv': 'dev'})
  728. def test_multiple_keys_in_opts_added_to_pillar(self):
  729. opts = {
  730. 'renderer': 'json',
  731. 'path_to_add': 'fake_data',
  732. 'path_to_add2': {'fake_data2': ['fake_data3', 'fake_data4']},
  733. 'pass_to_ext_pillars': ['path_to_add', 'path_to_add2']
  734. }
  735. pillar = salt.pillar.RemotePillar(opts, self.grains,
  736. 'mocked-minion', 'dev')
  737. self.assertEqual(pillar.extra_minion_data,
  738. {'path_to_add': 'fake_data',
  739. 'path_to_add2': {'fake_data2': ['fake_data3',
  740. 'fake_data4']}})
  741. def test_subkey_in_opts_added_to_pillar(self):
  742. opts = {
  743. 'renderer': 'json',
  744. 'path_to_add': 'fake_data',
  745. 'path_to_add2': {'fake_data5': 'fake_data6',
  746. 'fake_data2': ['fake_data3', 'fake_data4']},
  747. 'pass_to_ext_pillars': ['path_to_add2:fake_data5']
  748. }
  749. pillar = salt.pillar.RemotePillar(opts, self.grains,
  750. 'mocked-minion', 'dev')
  751. self.assertEqual(pillar.extra_minion_data,
  752. {'path_to_add2': {'fake_data5': 'fake_data6'}})
  753. def test_non_existent_leaf_opt_in_add_to_pillar(self):
  754. opts = {
  755. 'renderer': 'json',
  756. 'path_to_add': 'fake_data',
  757. 'path_to_add2': {'fake_data5': 'fake_data6',
  758. 'fake_data2': ['fake_data3', 'fake_data4']},
  759. 'pass_to_ext_pillars': ['path_to_add2:fake_data_non_exist']
  760. }
  761. pillar = salt.pillar.RemotePillar(opts, self.grains,
  762. 'mocked-minion', 'dev')
  763. self.assertEqual(pillar.pillar_override, {})
  764. def test_non_existent_intermediate_opt_in_add_to_pillar(self):
  765. opts = {
  766. 'renderer': 'json',
  767. 'path_to_add': 'fake_data',
  768. 'path_to_add2': {'fake_data5': 'fake_data6',
  769. 'fake_data2': ['fake_data3', 'fake_data4']},
  770. 'pass_to_ext_pillars': ['path_to_add_no_exist']
  771. }
  772. pillar = salt.pillar.RemotePillar(opts, self.grains,
  773. 'mocked-minion', 'dev')
  774. self.assertEqual(pillar.pillar_override, {})
  775. def test_malformed_add_to_pillar(self):
  776. opts = {
  777. 'renderer': 'json',
  778. 'path_to_add': 'fake_data',
  779. 'path_to_add2': {'fake_data5': 'fake_data6',
  780. 'fake_data2': ['fake_data3', 'fake_data4']},
  781. 'pass_to_ext_pillars': MagicMock()
  782. }
  783. with self.assertRaises(salt.exceptions.SaltClientError) as excinfo:
  784. salt.pillar.RemotePillar(opts, self.grains, 'mocked-minion', 'dev')
  785. self.assertEqual(excinfo.exception.strerror,
  786. '\'pass_to_ext_pillars\' config is malformed.')
  787. def test_pillar_send_extra_minion_data_from_config(self):
  788. opts = {
  789. 'renderer': 'json',
  790. 'pillarenv': 'fake_pillar_env',
  791. 'path_to_add': 'fake_data',
  792. 'path_to_add2': {'fake_data5': 'fake_data6',
  793. 'fake_data2': ['fake_data3', 'fake_data4']},
  794. 'pass_to_ext_pillars': ['path_to_add']}
  795. mock_channel = MagicMock(
  796. crypted_transfer_decode_dictentry=MagicMock(return_value={}))
  797. with patch('salt.transport.client.ReqChannel.factory',
  798. MagicMock(return_value=mock_channel)):
  799. pillar = salt.pillar.RemotePillar(opts, self.grains,
  800. 'mocked_minion', 'fake_env')
  801. ret = pillar.compile_pillar()
  802. self.assertEqual(pillar.channel, mock_channel)
  803. mock_channel.crypted_transfer_decode_dictentry.assert_called_once_with(
  804. {'cmd': '_pillar', 'ver': '2',
  805. 'id': 'mocked_minion',
  806. 'grains': {},
  807. 'saltenv': 'fake_env',
  808. 'pillarenv': 'fake_pillar_env',
  809. 'pillar_override': {},
  810. 'extra_minion_data': {'path_to_add': 'fake_data'}},
  811. dictkey='pillar')
  812. @skipIf(NO_MOCK, NO_MOCK_REASON)
  813. @patch('salt.transport.client.AsyncReqChannel.factory', MagicMock())
  814. class AsyncRemotePillarTestCase(TestCase):
  815. '''
  816. Tests for instantiating a AsyncRemotePillar in salt.pillar
  817. '''
  818. def setUp(self):
  819. self.grains = {}
  820. def tearDown(self):
  821. for attr in ('grains',):
  822. try:
  823. delattr(self, attr)
  824. except AttributeError:
  825. continue
  826. def test_get_opts_in_pillar_override_call(self):
  827. mock_get_extra_minion_data = MagicMock(return_value={})
  828. with patch(
  829. 'salt.pillar.RemotePillarMixin.get_ext_pillar_extra_minion_data',
  830. mock_get_extra_minion_data):
  831. salt.pillar.RemotePillar({}, self.grains, 'mocked-minion', 'dev')
  832. mock_get_extra_minion_data.assert_called_once_with(
  833. {'saltenv': 'dev'})
  834. def test_pillar_send_extra_minion_data_from_config(self):
  835. opts = {
  836. 'renderer': 'json',
  837. 'pillarenv': 'fake_pillar_env',
  838. 'path_to_add': 'fake_data',
  839. 'path_to_add2': {'fake_data5': 'fake_data6',
  840. 'fake_data2': ['fake_data3', 'fake_data4']},
  841. 'pass_to_ext_pillars': ['path_to_add']}
  842. mock_channel = MagicMock(
  843. crypted_transfer_decode_dictentry=MagicMock(return_value={}))
  844. with patch('salt.transport.client.AsyncReqChannel.factory',
  845. MagicMock(return_value=mock_channel)):
  846. pillar = salt.pillar.RemotePillar(opts, self.grains,
  847. 'mocked_minion', 'fake_env')
  848. ret = pillar.compile_pillar()
  849. mock_channel.crypted_transfer_decode_dictentry.assert_called_once_with(
  850. {'cmd': '_pillar', 'ver': '2',
  851. 'id': 'mocked_minion',
  852. 'grains': {},
  853. 'saltenv': 'fake_env',
  854. 'pillarenv': 'fake_pillar_env',
  855. 'pillar_override': {},
  856. 'extra_minion_data': {'path_to_add': 'fake_data'}},
  857. dictkey='pillar')