1
0

test_jinja.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Tests for salt.utils.jinja
  4. '''
  5. # Import Python libs
  6. from __future__ import absolute_import, unicode_literals, print_function
  7. from jinja2 import Environment, DictLoader, exceptions
  8. import ast
  9. import copy
  10. import datetime
  11. import os
  12. import pprint
  13. import re
  14. import tempfile
  15. # Import Salt Testing libs
  16. from tests.support.unit import skipIf, TestCase
  17. from tests.support.case import ModuleCase
  18. from tests.support.helpers import flaky
  19. from tests.support.mock import NO_MOCK, NO_MOCK_REASON, patch, MagicMock, Mock
  20. from tests.support.paths import BASE_FILES, TMP, TMP_CONF_DIR
  21. # Import Salt libs
  22. import salt.config
  23. import salt.loader
  24. from salt.exceptions import SaltRenderError
  25. from salt.ext import six
  26. from salt.ext.six.moves import builtins
  27. import salt.utils.json
  28. from salt.utils.decorators.jinja import JinjaFilter
  29. from salt.utils.jinja import (
  30. SaltCacheLoader,
  31. SerializerExtension,
  32. ensure_sequence_filter,
  33. tojson
  34. )
  35. from salt.utils.odict import OrderedDict
  36. from salt.utils.templates import JINJA, render_jinja_tmpl
  37. # dateutils is needed so that the strftime jinja filter is loaded
  38. import salt.utils.dateutils # pylint: disable=unused-import
  39. import salt.utils.files
  40. import salt.utils.stringutils
  41. import salt.utils.yaml
  42. # Import 3rd party libs
  43. try:
  44. import timelib # pylint: disable=W0611
  45. HAS_TIMELIB = True
  46. except ImportError:
  47. HAS_TIMELIB = False
  48. CACHEDIR = os.path.join(TMP, 'jinja-template-cache')
  49. BLINESEP = salt.utils.stringutils.to_bytes(os.linesep)
  50. class JinjaTestCase(TestCase):
  51. def test_tojson(self):
  52. '''
  53. Test the tojson filter for those using Jinja < 2.9. Non-ascii unicode
  54. content should be dumped with ensure_ascii=True.
  55. '''
  56. data = {'Non-ascii words': ['süß', 'спам', 'яйца']}
  57. result = tojson(data)
  58. expected = '{"Non-ascii words": ["s\\u00fc\\u00df", "\\u0441\\u043f\\u0430\\u043c", "\\u044f\\u0439\\u0446\\u0430"]}'
  59. assert result == expected, result
  60. class MockFileClient(object):
  61. '''
  62. Does not download files but records any file request for testing
  63. '''
  64. def __init__(self, loader=None):
  65. if loader:
  66. loader._file_client = self
  67. self.requests = []
  68. def get_file(self, template, dest='', makedirs=False, saltenv='base'):
  69. self.requests.append({
  70. 'path': template,
  71. 'dest': dest,
  72. 'makedirs': makedirs,
  73. 'saltenv': saltenv
  74. })
  75. def _setup_test_dir(src_dir, test_dir):
  76. os.makedirs(test_dir)
  77. salt.utils.files.recursive_copy(src_dir, test_dir)
  78. filename = os.path.join(test_dir, 'non_ascii')
  79. with salt.utils.files.fopen(filename, 'wb') as fp:
  80. fp.write(b'Assun\xc3\xa7\xc3\xa3o' + BLINESEP)
  81. filename = os.path.join(test_dir, 'hello_simple')
  82. with salt.utils.files.fopen(filename, 'wb') as fp:
  83. fp.write(b'world' + BLINESEP)
  84. filename = os.path.join(test_dir, 'hello_import')
  85. lines = [
  86. r"{% from 'macro' import mymacro -%}",
  87. r"{% from 'macro' import mymacro -%}",
  88. r"{{ mymacro('Hey') ~ mymacro(a|default('a'), b|default('b')) }}",
  89. ]
  90. with salt.utils.files.fopen(filename, 'wb') as fp:
  91. for line in lines:
  92. fp.write(line.encode('utf-8') + BLINESEP)
  93. class TestSaltCacheLoader(TestCase):
  94. def setUp(self):
  95. self.tempdir = tempfile.mkdtemp()
  96. self.template_dir = os.path.join(self.tempdir, 'files', 'test')
  97. _setup_test_dir(
  98. os.path.join(BASE_FILES, 'templates'),
  99. self.template_dir
  100. )
  101. self.opts = {
  102. 'file_buffer_size': 1048576,
  103. 'cachedir': self.tempdir,
  104. 'file_roots': {
  105. 'test': [self.template_dir]
  106. },
  107. 'pillar_roots': {
  108. 'test': [self.template_dir]
  109. },
  110. 'extension_modules': os.path.join(
  111. os.path.dirname(os.path.abspath(__file__)),
  112. 'extmods'),
  113. }
  114. super(TestSaltCacheLoader, self).setUp()
  115. def tearDown(self):
  116. salt.utils.files.rm_rf(self.tempdir)
  117. def test_searchpath(self):
  118. '''
  119. The searchpath is based on the cachedir option and the saltenv parameter
  120. '''
  121. tmp = tempfile.gettempdir()
  122. opts = copy.deepcopy(self.opts)
  123. opts.update({'cachedir': tmp})
  124. loader = self.get_loader(opts=opts, saltenv='test')
  125. assert loader.searchpath == [os.path.join(tmp, 'files', 'test')]
  126. def test_mockclient(self):
  127. '''
  128. A MockFileClient is used that records all file requests normally sent
  129. to the master.
  130. '''
  131. loader = self.get_loader(opts=self.opts, saltenv='test')
  132. res = loader.get_source(None, 'hello_simple')
  133. assert len(res) == 3
  134. # res[0] on Windows is unicode and use os.linesep so it works cross OS
  135. self.assertEqual(six.text_type(res[0]), 'world' + os.linesep)
  136. tmpl_dir = os.path.join(self.template_dir, 'hello_simple')
  137. self.assertEqual(res[1], tmpl_dir)
  138. assert res[2](), 'Template up to date?'
  139. assert len(loader._file_client.requests)
  140. self.assertEqual(loader._file_client.requests[0]['path'], 'salt://hello_simple')
  141. def get_loader(self, opts=None, saltenv='base'):
  142. '''
  143. Now that we instantiate the client in the __init__, we need to mock it
  144. '''
  145. if opts is None:
  146. opts = self.opts
  147. with patch.object(SaltCacheLoader, 'file_client', Mock()):
  148. loader = SaltCacheLoader(opts, saltenv)
  149. # Create a mock file client and attach it to the loader
  150. MockFileClient(loader)
  151. return loader
  152. def get_test_saltenv(self):
  153. '''
  154. Setup a simple jinja test environment
  155. '''
  156. loader = self.get_loader(saltenv='test')
  157. jinja = Environment(loader=loader)
  158. return loader._file_client, jinja
  159. def test_import(self):
  160. '''
  161. You can import and use macros from other files
  162. '''
  163. fc, jinja = self.get_test_saltenv()
  164. result = jinja.get_template('hello_import').render()
  165. self.assertEqual(result, 'Hey world !a b !')
  166. assert len(fc.requests) == 2
  167. self.assertEqual(fc.requests[0]['path'], 'salt://hello_import')
  168. self.assertEqual(fc.requests[1]['path'], 'salt://macro')
  169. def test_relative_import(self):
  170. '''
  171. You can import using relative paths
  172. issue-13889
  173. '''
  174. fc, jinja = self.get_test_saltenv()
  175. tmpl = jinja.get_template(os.path.join('relative', 'rhello'))
  176. result = tmpl.render()
  177. self.assertEqual(result, 'Hey world !a b !')
  178. assert len(fc.requests) == 3
  179. self.assertEqual(fc.requests[0]['path'], os.path.join('salt://relative', 'rhello'))
  180. self.assertEqual(fc.requests[1]['path'], os.path.join('salt://relative', 'rmacro'))
  181. self.assertEqual(fc.requests[2]['path'], 'salt://macro')
  182. # This must fail when rendered: attempts to import from outside file root
  183. template = jinja.get_template('relative/rescape')
  184. self.assertRaises(exceptions.TemplateNotFound, template.render)
  185. def test_include(self):
  186. '''
  187. You can also include a template that imports and uses macros
  188. '''
  189. fc, jinja = self.get_test_saltenv()
  190. result = jinja.get_template('hello_include').render()
  191. self.assertEqual(result, 'Hey world !a b !')
  192. assert len(fc.requests) == 3
  193. self.assertEqual(fc.requests[0]['path'], 'salt://hello_include')
  194. self.assertEqual(fc.requests[1]['path'], 'salt://hello_import')
  195. self.assertEqual(fc.requests[2]['path'], 'salt://macro')
  196. def test_include_context(self):
  197. '''
  198. Context variables are passes to the included template by default.
  199. '''
  200. _, jinja = self.get_test_saltenv()
  201. result = jinja.get_template('hello_include').render(a='Hi', b='Salt')
  202. self.assertEqual(result, 'Hey world !Hi Salt !')
  203. def test_cached_file_client(self):
  204. '''
  205. Multiple instantiations of SaltCacheLoader use the cached file client
  206. '''
  207. with patch('salt.transport.client.ReqChannel.factory', Mock()):
  208. loader_a = SaltCacheLoader(self.opts)
  209. loader_b = SaltCacheLoader(self.opts)
  210. assert loader_a._file_client is loader_b._file_client
  211. def test_file_client_kwarg(self):
  212. '''
  213. A file client can be passed to SaltCacheLoader overriding the any
  214. cached file client
  215. '''
  216. mfc = MockFileClient()
  217. loader = SaltCacheLoader(self.opts, _file_client=mfc)
  218. assert loader._file_client is mfc
  219. def test_cache_loader_shutdown(self):
  220. '''
  221. The shudown method can be called without raising an exception when the
  222. file_client does not have a destroy method
  223. '''
  224. mfc = MockFileClient()
  225. assert not hasattr(mfc, 'destroy')
  226. loader = SaltCacheLoader(self.opts, _file_client=mfc)
  227. assert loader._file_client is mfc
  228. # Shutdown method should not raise any exceptions
  229. loader.shutdown()
  230. class TestGetTemplate(TestCase):
  231. def setUp(self):
  232. self.tempdir = tempfile.mkdtemp()
  233. self.template_dir = os.path.join(self.tempdir, 'files', 'test')
  234. _setup_test_dir(
  235. os.path.join(BASE_FILES, 'templates'),
  236. self.template_dir
  237. )
  238. self.local_opts = {
  239. 'file_buffer_size': 1048576,
  240. 'cachedir': self.tempdir,
  241. 'file_client': 'local',
  242. 'file_ignore_regex': None,
  243. 'file_ignore_glob': None,
  244. 'file_roots': {
  245. 'test': [self.template_dir]
  246. },
  247. 'pillar_roots': {
  248. 'test': [self.template_dir]
  249. },
  250. 'fileserver_backend': ['roots'],
  251. 'hash_type': 'md5',
  252. 'extension_modules': os.path.join(
  253. os.path.dirname(os.path.abspath(__file__)),
  254. 'extmods'),
  255. }
  256. self.local_salt = {}
  257. super(TestGetTemplate, self).setUp()
  258. def tearDown(self):
  259. salt.utils.files.rm_rf(self.tempdir)
  260. def test_fallback(self):
  261. '''
  262. A Template with a filesystem loader is returned as fallback
  263. if the file is not contained in the searchpath
  264. '''
  265. fn_ = os.path.join(self.template_dir, 'hello_simple')
  266. with salt.utils.files.fopen(fn_) as fp_:
  267. out = render_jinja_tmpl(
  268. salt.utils.stringutils.to_unicode(fp_.read()),
  269. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  270. )
  271. self.assertEqual(out, 'world' + os.linesep)
  272. def test_fallback_noloader(self):
  273. '''
  274. A Template with a filesystem loader is returned as fallback
  275. if the file is not contained in the searchpath
  276. '''
  277. filename = os.path.join(self.template_dir, 'hello_import')
  278. with salt.utils.files.fopen(filename) as fp_:
  279. out = render_jinja_tmpl(
  280. salt.utils.stringutils.to_unicode(fp_.read()),
  281. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  282. )
  283. self.assertEqual(out, 'Hey world !a b !' + os.linesep)
  284. def test_saltenv(self):
  285. '''
  286. If the template is within the searchpath it can
  287. import, include and extend other templates.
  288. The initial template is expected to be already cached
  289. get_template does not request it from the master again.
  290. '''
  291. fc = MockFileClient()
  292. with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
  293. filename = os.path.join(self.template_dir, 'hello_import')
  294. with salt.utils.files.fopen(filename) as fp_:
  295. out = render_jinja_tmpl(
  296. salt.utils.stringutils.to_unicode(fp_.read()),
  297. dict(opts={'cachedir': self.tempdir, 'file_client': 'remote',
  298. 'file_roots': self.local_opts['file_roots'],
  299. 'pillar_roots': self.local_opts['pillar_roots']},
  300. a='Hi', b='Salt', saltenv='test', salt=self.local_salt))
  301. self.assertEqual(out, 'Hey world !Hi Salt !' + os.linesep)
  302. self.assertEqual(fc.requests[0]['path'], 'salt://macro')
  303. def test_macro_additional_log_for_generalexc(self):
  304. '''
  305. If we failed in a macro because of e.g. a TypeError, get
  306. more output from trace.
  307. '''
  308. expected = r'''Jinja error:.*division.*
  309. .*macrogeneral\(2\):
  310. ---
  311. \{% macro mymacro\(\) -%\}
  312. \{\{ 1/0 \}\} <======================
  313. \{%- endmacro %\}
  314. ---.*'''
  315. filename = os.path.join(self.template_dir, 'hello_import_generalerror')
  316. fc = MockFileClient()
  317. with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
  318. with salt.utils.files.fopen(filename) as fp_:
  319. self.assertRaisesRegex(
  320. SaltRenderError,
  321. expected,
  322. render_jinja_tmpl,
  323. salt.utils.stringutils.to_unicode(fp_.read()),
  324. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  325. def test_macro_additional_log_for_undefined(self):
  326. '''
  327. If we failed in a macro because of undefined variables, get
  328. more output from trace.
  329. '''
  330. expected = r'''Jinja variable 'b' is undefined
  331. .*macroundefined\(2\):
  332. ---
  333. \{% macro mymacro\(\) -%\}
  334. \{\{b.greetee\}\} <-- error is here <======================
  335. \{%- endmacro %\}
  336. ---'''
  337. filename = os.path.join(self.template_dir, 'hello_import_undefined')
  338. fc = MockFileClient()
  339. with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
  340. with salt.utils.files.fopen(filename) as fp_:
  341. self.assertRaisesRegex(
  342. SaltRenderError,
  343. expected,
  344. render_jinja_tmpl,
  345. salt.utils.stringutils.to_unicode(fp_.read()),
  346. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  347. def test_macro_additional_log_syntaxerror(self):
  348. '''
  349. If we failed in a macro, get more output from trace.
  350. '''
  351. expected = r'''Jinja syntax error: expected token .*end.*got '-'.*
  352. .*macroerror\(2\):
  353. ---
  354. # macro
  355. \{% macro mymacro\(greeting, greetee='world'\) -\} <-- error is here <======================
  356. \{\{ greeting ~ ' ' ~ greetee \}\} !
  357. \{%- endmacro %\}
  358. ---.*'''
  359. filename = os.path.join(self.template_dir, 'hello_import_error')
  360. fc = MockFileClient()
  361. with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
  362. with salt.utils.files.fopen(filename) as fp_:
  363. self.assertRaisesRegex(
  364. SaltRenderError,
  365. expected,
  366. render_jinja_tmpl,
  367. salt.utils.stringutils.to_unicode(fp_.read()),
  368. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  369. def test_non_ascii_encoding(self):
  370. fc = MockFileClient()
  371. with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
  372. filename = os.path.join(self.template_dir, 'hello_import')
  373. with salt.utils.files.fopen(filename) as fp_:
  374. out = render_jinja_tmpl(
  375. salt.utils.stringutils.to_unicode(fp_.read()),
  376. dict(opts={'cachedir': self.tempdir, 'file_client': 'remote',
  377. 'file_roots': self.local_opts['file_roots'],
  378. 'pillar_roots': self.local_opts['pillar_roots']},
  379. a='Hi', b='Sàlt', saltenv='test', salt=self.local_salt))
  380. self.assertEqual(out, salt.utils.stringutils.to_unicode('Hey world !Hi Sàlt !' + os.linesep))
  381. self.assertEqual(fc.requests[0]['path'], 'salt://macro')
  382. filename = os.path.join(self.template_dir, 'non_ascii')
  383. with salt.utils.files.fopen(filename, 'rb') as fp_:
  384. out = render_jinja_tmpl(
  385. salt.utils.stringutils.to_unicode(fp_.read(), 'utf-8'),
  386. dict(opts={'cachedir': self.tempdir, 'file_client': 'remote',
  387. 'file_roots': self.local_opts['file_roots'],
  388. 'pillar_roots': self.local_opts['pillar_roots']},
  389. a='Hi', b='Sàlt', saltenv='test', salt=self.local_salt))
  390. self.assertEqual('Assunção' + os.linesep, out)
  391. self.assertEqual(fc.requests[0]['path'], 'salt://macro')
  392. @skipIf(HAS_TIMELIB is False, 'The `timelib` library is not installed.')
  393. def test_strftime(self):
  394. response = render_jinja_tmpl(
  395. '{{ "2002/12/25"|strftime }}',
  396. dict(
  397. opts=self.local_opts,
  398. saltenv='test',
  399. salt=self.local_salt
  400. ))
  401. self.assertEqual(response, '2002-12-25')
  402. objects = (
  403. datetime.datetime(2002, 12, 25, 12, 00, 00, 00),
  404. '2002/12/25',
  405. 1040814000,
  406. '1040814000'
  407. )
  408. for object in objects:
  409. response = render_jinja_tmpl(
  410. '{{ object|strftime }}',
  411. dict(
  412. object=object,
  413. opts=self.local_opts,
  414. saltenv='test',
  415. salt=self.local_salt
  416. ))
  417. self.assertEqual(response, '2002-12-25')
  418. response = render_jinja_tmpl(
  419. '{{ object|strftime("%b %d, %Y") }}',
  420. dict(
  421. object=object,
  422. opts=self.local_opts,
  423. saltenv='test',
  424. salt=self.local_salt
  425. ))
  426. self.assertEqual(response, 'Dec 25, 2002')
  427. response = render_jinja_tmpl(
  428. '{{ object|strftime("%y") }}',
  429. dict(
  430. object=object,
  431. opts=self.local_opts,
  432. saltenv='test',
  433. salt=self.local_salt
  434. ))
  435. self.assertEqual(response, '02')
  436. def test_non_ascii(self):
  437. fn = os.path.join(self.template_dir, 'non_ascii')
  438. out = JINJA(
  439. fn,
  440. opts=self.local_opts,
  441. saltenv='test',
  442. salt=self.local_salt
  443. )
  444. with salt.utils.files.fopen(out['data'], 'rb') as fp:
  445. result = salt.utils.stringutils.to_unicode(fp.read(), 'utf-8')
  446. self.assertEqual(salt.utils.stringutils.to_unicode('Assunção' + os.linesep), result)
  447. def test_get_context_has_enough_context(self):
  448. template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf'
  449. context = salt.utils.stringutils.get_context(template, 8)
  450. expected = '---\n[...]\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\n[...]\n---'
  451. self.assertEqual(expected, context)
  452. def test_get_context_at_top_of_file(self):
  453. template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf'
  454. context = salt.utils.stringutils.get_context(template, 1)
  455. expected = '---\n1\n2\n3\n4\n5\n6\n[...]\n---'
  456. self.assertEqual(expected, context)
  457. def test_get_context_at_bottom_of_file(self):
  458. template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf'
  459. context = salt.utils.stringutils.get_context(template, 15)
  460. expected = '---\n[...]\na\nb\nc\nd\ne\nf\n---'
  461. self.assertEqual(expected, context)
  462. def test_get_context_2_context_lines(self):
  463. template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf'
  464. context = salt.utils.stringutils.get_context(template, 8, num_lines=2)
  465. expected = '---\n[...]\n6\n7\n8\n9\na\n[...]\n---'
  466. self.assertEqual(expected, context)
  467. def test_get_context_with_marker(self):
  468. template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf'
  469. context = salt.utils.stringutils.get_context(template, 8, num_lines=2, marker=' <---')
  470. expected = '---\n[...]\n6\n7\n8 <---\n9\na\n[...]\n---'
  471. self.assertEqual(expected, context)
  472. def test_render_with_syntax_error(self):
  473. template = 'hello\n\n{{ bad\n\nfoo'
  474. expected = r'.*---\nhello\n\n{{ bad\n\nfoo <======================\n---'
  475. self.assertRaisesRegex(
  476. SaltRenderError,
  477. expected,
  478. render_jinja_tmpl,
  479. template,
  480. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  481. )
  482. @skipIf(six.PY3, 'Not applicable to Python 3')
  483. @skipIf(NO_MOCK, NO_MOCK_REASON)
  484. def test_render_with_unicode_syntax_error(self):
  485. with patch.object(builtins, '__salt_system_encoding__', 'utf-8'):
  486. template = 'hello\n\n{{ bad\n\nfoo한'
  487. expected = r'.*---\nhello\n\n{{ bad\n\nfoo\xed\x95\x9c <======================\n---'
  488. self.assertRaisesRegex(
  489. SaltRenderError,
  490. expected,
  491. render_jinja_tmpl,
  492. template,
  493. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  494. )
  495. @skipIf(NO_MOCK, NO_MOCK_REASON)
  496. def test_render_with_utf8_syntax_error(self):
  497. with patch.object(builtins, '__salt_system_encoding__', 'utf-8'):
  498. template = 'hello\n\n{{ bad\n\nfoo한'
  499. expected = salt.utils.stringutils.to_str(
  500. r'.*---\nhello\n\n{{ bad\n\nfoo한 <======================\n---'
  501. )
  502. self.assertRaisesRegex(
  503. SaltRenderError,
  504. expected,
  505. render_jinja_tmpl,
  506. template,
  507. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  508. )
  509. def test_render_with_undefined_variable(self):
  510. template = "hello\n\n{{ foo }}\n\nfoo"
  511. expected = r'Jinja variable \'foo\' is undefined'
  512. self.assertRaisesRegex(
  513. SaltRenderError,
  514. expected,
  515. render_jinja_tmpl,
  516. template,
  517. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  518. )
  519. def test_render_with_undefined_variable_utf8(self):
  520. template = "hello\xed\x95\x9c\n\n{{ foo }}\n\nfoo"
  521. expected = r'Jinja variable \'foo\' is undefined'
  522. self.assertRaisesRegex(
  523. SaltRenderError,
  524. expected,
  525. render_jinja_tmpl,
  526. template,
  527. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  528. )
  529. def test_render_with_undefined_variable_unicode(self):
  530. template = 'hello한\n\n{{ foo }}\n\nfoo'
  531. expected = r'Jinja variable \'foo\' is undefined'
  532. self.assertRaisesRegex(
  533. SaltRenderError,
  534. expected,
  535. render_jinja_tmpl,
  536. template,
  537. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  538. )
  539. class TestJinjaDefaultOptions(TestCase):
  540. def __init__(self, *args, **kws):
  541. TestCase.__init__(self, *args, **kws)
  542. self.local_opts = {
  543. 'cachedir': CACHEDIR,
  544. 'file_buffer_size': 1048576,
  545. 'file_client': 'local',
  546. 'file_ignore_regex': None,
  547. 'file_ignore_glob': None,
  548. 'file_roots': {
  549. 'test': [os.path.join(BASE_FILES, 'templates')]
  550. },
  551. 'pillar_roots': {
  552. 'test': [os.path.join(BASE_FILES, 'templates')]
  553. },
  554. 'fileserver_backend': ['roots'],
  555. 'hash_type': 'md5',
  556. 'extension_modules': os.path.join(
  557. os.path.dirname(os.path.abspath(__file__)),
  558. 'extmods'),
  559. 'jinja_env': {
  560. 'line_comment_prefix': '##',
  561. 'line_statement_prefix': '%',
  562. },
  563. }
  564. self.local_salt = {
  565. 'myvar': 'zero',
  566. 'mylist': [0, 1, 2, 3],
  567. }
  568. def test_comment_prefix(self):
  569. template = """
  570. %- set myvar = 'one'
  571. ## ignored comment 1
  572. {{- myvar -}}
  573. {%- set myvar = 'two' %} ## ignored comment 2
  574. {{- myvar }} ## ignored comment 3
  575. %- if myvar == 'two':
  576. %- set myvar = 'three'
  577. %- endif
  578. {{- myvar -}}
  579. """
  580. rendered = render_jinja_tmpl(template,
  581. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  582. self.assertEqual(rendered, 'onetwothree')
  583. def test_statement_prefix(self):
  584. template = """
  585. {%- set mylist = ['1', '2', '3'] %}
  586. %- set mylist = ['one', 'two', 'three']
  587. %- for item in mylist:
  588. {{- item }}
  589. %- endfor
  590. """
  591. rendered = render_jinja_tmpl(template,
  592. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  593. self.assertEqual(rendered, 'onetwothree')
  594. class TestCustomExtensions(TestCase):
  595. def __init__(self, *args, **kws):
  596. super(TestCustomExtensions, self).__init__(*args, **kws)
  597. self.local_opts = {
  598. 'cachedir': CACHEDIR,
  599. 'file_buffer_size': 1048576,
  600. 'file_client': 'local',
  601. 'file_ignore_regex': None,
  602. 'file_ignore_glob': None,
  603. 'file_roots': {
  604. 'test': [os.path.join(BASE_FILES, 'templates')]
  605. },
  606. 'pillar_roots': {
  607. 'test': [os.path.join(BASE_FILES, 'templates')]
  608. },
  609. 'fileserver_backend': ['roots'],
  610. 'hash_type': 'md5',
  611. 'extension_modules': os.path.join(
  612. os.path.dirname(os.path.abspath(__file__)),
  613. 'extmods'),
  614. }
  615. self.local_salt = {
  616. # 'dns.A': dnsutil.A,
  617. # 'dns.AAAA': dnsutil.AAAA,
  618. # 'file.exists': filemod.file_exists,
  619. # 'file.basename': filemod.basename,
  620. # 'file.dirname': filemod.dirname
  621. }
  622. def test_regex_escape(self):
  623. dataset = 'foo?:.*/\\bar'
  624. env = Environment(extensions=[SerializerExtension])
  625. env.filters.update(JinjaFilter.salt_jinja_filters)
  626. rendered = env.from_string('{{ dataset|regex_escape }}').render(dataset=dataset)
  627. self.assertEqual(rendered, re.escape(dataset))
  628. def test_unique_string(self):
  629. dataset = 'foo'
  630. unique = set(dataset)
  631. env = Environment(extensions=[SerializerExtension])
  632. env.filters.update(JinjaFilter.salt_jinja_filters)
  633. if six.PY3:
  634. rendered = env.from_string('{{ dataset|unique }}').render(dataset=dataset).strip("'{}").split("', '")
  635. self.assertEqual(sorted(rendered), sorted(list(unique)))
  636. else:
  637. rendered = env.from_string('{{ dataset|unique }}').render(dataset=dataset)
  638. self.assertEqual(rendered, "{0}".format(unique))
  639. def test_unique_tuple(self):
  640. dataset = ('foo', 'foo', 'bar')
  641. unique = set(dataset)
  642. env = Environment(extensions=[SerializerExtension])
  643. env.filters.update(JinjaFilter.salt_jinja_filters)
  644. if six.PY3:
  645. rendered = env.from_string('{{ dataset|unique }}').render(dataset=dataset).strip("'{}").split("', '")
  646. self.assertEqual(sorted(rendered), sorted(list(unique)))
  647. else:
  648. rendered = env.from_string('{{ dataset|unique }}').render(dataset=dataset)
  649. self.assertEqual(rendered, "{0}".format(unique))
  650. def test_unique_list(self):
  651. dataset = ['foo', 'foo', 'bar']
  652. unique = ['foo', 'bar']
  653. env = Environment(extensions=[SerializerExtension])
  654. env.filters.update(JinjaFilter.salt_jinja_filters)
  655. if six.PY3:
  656. rendered = env.from_string('{{ dataset|unique }}').render(dataset=dataset).strip("'[]").split("', '")
  657. self.assertEqual(rendered, unique)
  658. else:
  659. rendered = env.from_string('{{ dataset|unique }}').render(dataset=dataset)
  660. self.assertEqual(rendered, "{0}".format(unique))
  661. def test_serialize_json(self):
  662. dataset = {
  663. "foo": True,
  664. "bar": 42,
  665. "baz": [1, 2, 3],
  666. "qux": 2.0
  667. }
  668. env = Environment(extensions=[SerializerExtension])
  669. rendered = env.from_string('{{ dataset|json }}').render(dataset=dataset)
  670. self.assertEqual(dataset, salt.utils.json.loads(rendered))
  671. def test_serialize_yaml(self):
  672. dataset = {
  673. "foo": True,
  674. "bar": 42,
  675. "baz": [1, 2, 3],
  676. "qux": 2.0,
  677. "spam": OrderedDict([
  678. ('foo', OrderedDict([
  679. ('bar', 'baz'),
  680. ('qux', 42)
  681. ])
  682. )
  683. ])
  684. }
  685. env = Environment(extensions=[SerializerExtension])
  686. rendered = env.from_string('{{ dataset|yaml }}').render(dataset=dataset)
  687. self.assertEqual(dataset, salt.utils.yaml.safe_load(rendered))
  688. def test_serialize_yaml_str(self):
  689. dataset = "str value"
  690. env = Environment(extensions=[SerializerExtension])
  691. rendered = env.from_string('{{ dataset|yaml }}').render(dataset=dataset)
  692. self.assertEqual(dataset, rendered)
  693. def test_serialize_yaml_unicode(self):
  694. dataset = 'str value'
  695. env = Environment(extensions=[SerializerExtension])
  696. rendered = env.from_string('{{ dataset|yaml }}').render(dataset=dataset)
  697. if six.PY3:
  698. self.assertEqual("str value", rendered)
  699. else:
  700. # Due to a bug in the equality handler, this check needs to be split
  701. # up into several different assertions. We need to check that the various
  702. # string segments are present in the rendered value, as well as the
  703. # type of the rendered variable (should be unicode, which is the same as
  704. # six.text_type). This should cover all use cases but also allow the test
  705. # to pass on CentOS 6 running Python 2.7.
  706. self.assertIn('str value', rendered)
  707. self.assertIsInstance(rendered, six.text_type)
  708. def test_serialize_python(self):
  709. dataset = {
  710. "foo": True,
  711. "bar": 42,
  712. "baz": [1, 2, 3],
  713. "qux": 2.0
  714. }
  715. env = Environment(extensions=[SerializerExtension])
  716. rendered = env.from_string('{{ dataset|python }}').render(dataset=dataset)
  717. self.assertEqual(rendered, pprint.pformat(dataset))
  718. def test_load_yaml(self):
  719. env = Environment(extensions=[SerializerExtension])
  720. rendered = env.from_string('{% set document = "{foo: it works}"|load_yaml %}{{ document.foo }}').render()
  721. self.assertEqual(rendered, "it works")
  722. rendered = env.from_string('{% set document = document|load_yaml %}'
  723. '{{ document.foo }}').render(document="{foo: it works}")
  724. self.assertEqual(rendered, "it works")
  725. with self.assertRaises((TypeError, exceptions.TemplateRuntimeError)):
  726. env.from_string('{% set document = document|load_yaml %}'
  727. '{{ document.foo }}').render(document={"foo": "it works"})
  728. def test_load_tag(self):
  729. env = Environment(extensions=[SerializerExtension])
  730. source = '{{ bar }}, ' + \
  731. '{% load_yaml as docu %}{foo: it works, {{ bar }}: baz}{% endload %}' + \
  732. '{{ docu.foo }}'
  733. rendered = env.from_string(source).render(bar="barred")
  734. self.assertEqual(rendered, "barred, it works")
  735. source = '{{ bar }}, {% load_json as docu %}{"foo": "it works", "{{ bar }}": "baz"}{% endload %}' + \
  736. '{{ docu.foo }}'
  737. rendered = env.from_string(source).render(bar="barred")
  738. self.assertEqual(rendered, "barred, it works")
  739. with self.assertRaises(exceptions.TemplateSyntaxError):
  740. env.from_string('{% load_yamle as document %}{foo, bar: it works}{% endload %}').render()
  741. with self.assertRaises(exceptions.TemplateRuntimeError):
  742. env.from_string('{% load_json as document %}{foo, bar: it works}{% endload %}').render()
  743. def test_load_json(self):
  744. env = Environment(extensions=[SerializerExtension])
  745. rendered = env.from_string('{% set document = \'{"foo": "it works"}\'|load_json %}'
  746. '{{ document.foo }}').render()
  747. self.assertEqual(rendered, "it works")
  748. rendered = env.from_string('{% set document = document|load_json %}'
  749. '{{ document.foo }}').render(document='{"foo": "it works"}')
  750. self.assertEqual(rendered, "it works")
  751. # bad quotes
  752. with self.assertRaises(exceptions.TemplateRuntimeError):
  753. env.from_string("{{ document|load_json }}").render(document="{'foo': 'it works'}")
  754. # not a string
  755. with self.assertRaises(exceptions.TemplateRuntimeError):
  756. env.from_string('{{ document|load_json }}').render(document={"foo": "it works"})
  757. def test_load_yaml_template(self):
  758. loader = DictLoader({'foo': '{bar: "my god is blue", foo: [1, 2, 3]}'})
  759. env = Environment(extensions=[SerializerExtension], loader=loader)
  760. rendered = env.from_string('{% import_yaml "foo" as doc %}{{ doc.bar }}').render()
  761. self.assertEqual(rendered, "my god is blue")
  762. with self.assertRaises(exceptions.TemplateNotFound):
  763. env.from_string('{% import_yaml "does not exists" as doc %}').render()
  764. def test_load_json_template(self):
  765. loader = DictLoader({'foo': '{"bar": "my god is blue", "foo": [1, 2, 3]}'})
  766. env = Environment(extensions=[SerializerExtension], loader=loader)
  767. rendered = env.from_string('{% import_json "foo" as doc %}{{ doc.bar }}').render()
  768. self.assertEqual(rendered, "my god is blue")
  769. with self.assertRaises(exceptions.TemplateNotFound):
  770. env.from_string('{% import_json "does not exists" as doc %}').render()
  771. def test_load_text_template(self):
  772. loader = DictLoader({'foo': 'Foo!'})
  773. env = Environment(extensions=[SerializerExtension], loader=loader)
  774. rendered = env.from_string('{% import_text "foo" as doc %}{{ doc }}').render()
  775. self.assertEqual(rendered, "Foo!")
  776. with self.assertRaises(exceptions.TemplateNotFound):
  777. env.from_string('{% import_text "does not exists" as doc %}').render()
  778. def test_catalog(self):
  779. loader = DictLoader({
  780. 'doc1': '{bar: "my god is blue"}',
  781. 'doc2': '{% import_yaml "doc1" as local2 %} never exported',
  782. 'doc3': '{% load_yaml as local3 %}{"foo": "it works"}{% endload %} me neither',
  783. 'main1': '{% from "doc2" import local2 %}{{ local2.bar }}',
  784. 'main2': '{% from "doc3" import local3 %}{{ local3.foo }}',
  785. 'main3': '''
  786. {% import "doc2" as imported2 %}
  787. {% import "doc3" as imported3 %}
  788. {{ imported2.local2.bar }}
  789. ''',
  790. 'main4': '''
  791. {% import "doc2" as imported2 %}
  792. {% import "doc3" as imported3 %}
  793. {{ imported3.local3.foo }}
  794. ''',
  795. 'main5': '''
  796. {% from "doc2" import local2 as imported2 %}
  797. {% from "doc3" import local3 as imported3 %}
  798. {{ imported2.bar }}
  799. ''',
  800. 'main6': '''
  801. {% from "doc2" import local2 as imported2 %}
  802. {% from "doc3" import local3 as imported3 %}
  803. {{ imported3.foo }}
  804. '''
  805. })
  806. env = Environment(extensions=[SerializerExtension], loader=loader)
  807. rendered = env.get_template('main1').render()
  808. self.assertEqual(rendered, "my god is blue")
  809. rendered = env.get_template('main2').render()
  810. self.assertEqual(rendered, "it works")
  811. rendered = env.get_template('main3').render().strip()
  812. self.assertEqual(rendered, "my god is blue")
  813. rendered = env.get_template('main4').render().strip()
  814. self.assertEqual(rendered, "it works")
  815. rendered = env.get_template('main5').render().strip()
  816. self.assertEqual(rendered, "my god is blue")
  817. rendered = env.get_template('main6').render().strip()
  818. self.assertEqual(rendered, "it works")
  819. def test_nested_structures(self):
  820. env = Environment(extensions=[SerializerExtension])
  821. rendered = env.from_string('{{ data }}').render(data="foo")
  822. self.assertEqual(rendered, "foo")
  823. data = OrderedDict([
  824. ('foo', OrderedDict([
  825. ('bar', 'baz'),
  826. ('qux', 42)
  827. ])
  828. )
  829. ])
  830. rendered = env.from_string('{{ data }}').render(data=data)
  831. self.assertEqual(
  832. rendered,
  833. "{u'foo': {u'bar': u'baz', u'qux': 42}}" if six.PY2
  834. else "{'foo': {'bar': 'baz', 'qux': 42}}"
  835. )
  836. rendered = env.from_string('{{ data }}').render(data=[
  837. OrderedDict(
  838. foo='bar',
  839. ),
  840. OrderedDict(
  841. baz=42,
  842. )
  843. ])
  844. self.assertEqual(
  845. rendered,
  846. "[{'foo': u'bar'}, {'baz': 42}]" if six.PY2
  847. else "[{'foo': 'bar'}, {'baz': 42}]"
  848. )
  849. def test_sequence(self):
  850. env = Environment()
  851. env.filters['sequence'] = ensure_sequence_filter
  852. rendered = env.from_string('{{ data | sequence | length }}') \
  853. .render(data='foo')
  854. self.assertEqual(rendered, '1')
  855. rendered = env.from_string('{{ data | sequence | length }}') \
  856. .render(data=['foo', 'bar'])
  857. self.assertEqual(rendered, '2')
  858. rendered = env.from_string('{{ data | sequence | length }}') \
  859. .render(data=('foo', 'bar'))
  860. self.assertEqual(rendered, '2')
  861. rendered = env.from_string('{{ data | sequence | length }}') \
  862. .render(data=set(['foo', 'bar']))
  863. self.assertEqual(rendered, '2')
  864. rendered = env.from_string('{{ data | sequence | length }}') \
  865. .render(data={'foo': 'bar'})
  866. self.assertEqual(rendered, '1')
  867. def test_is_ip(self):
  868. '''
  869. Test the `is_ip` Jinja filter.
  870. '''
  871. rendered = render_jinja_tmpl("{{ '192.168.0.1' | is_ip }}",
  872. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  873. self.assertEqual(rendered, 'True')
  874. rendered = render_jinja_tmpl("{{ 'FE80::' | is_ip }}",
  875. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  876. self.assertEqual(rendered, 'True')
  877. rendered = render_jinja_tmpl("{{ 'random' | is_ip }}",
  878. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  879. self.assertEqual(rendered, 'False')
  880. def test_is_ipv4(self):
  881. '''
  882. Test the `is_ipv4` Jinja filter.
  883. '''
  884. rendered = render_jinja_tmpl("{{ '192.168.0.1' | is_ipv4 }}",
  885. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  886. self.assertEqual(rendered, 'True')
  887. rendered = render_jinja_tmpl("{{ 'FE80::' | is_ipv4 }}",
  888. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  889. self.assertEqual(rendered, 'False')
  890. rendered = render_jinja_tmpl("{{ 'random' | is_ipv4 }}",
  891. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  892. self.assertEqual(rendered, 'False')
  893. def test_is_ipv6(self):
  894. '''
  895. Test the `is_ipv6` Jinja filter.
  896. '''
  897. rendered = render_jinja_tmpl("{{ '192.168.0.1' | is_ipv6 }}",
  898. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  899. self.assertEqual(rendered, 'False')
  900. rendered = render_jinja_tmpl("{{ 'fe80::20d:b9ff:fe01:ea8%eth0' | is_ipv6 }}",
  901. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  902. self.assertEqual(rendered, 'True')
  903. rendered = render_jinja_tmpl("{{ 'FE80::' | is_ipv6 }}",
  904. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  905. self.assertEqual(rendered, 'True')
  906. rendered = render_jinja_tmpl("{{ 'random' | is_ipv6 }}",
  907. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  908. self.assertEqual(rendered, 'False')
  909. def test_ipaddr(self):
  910. '''
  911. Test the `ipaddr` Jinja filter.
  912. '''
  913. rendered = render_jinja_tmpl("{{ '::' | ipaddr }}",
  914. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  915. self.assertEqual(rendered, '::')
  916. rendered = render_jinja_tmpl("{{ '192.168.0.1' | ipaddr }}",
  917. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  918. self.assertEqual(rendered, '192.168.0.1')
  919. # provides a list with valid IP addresses only
  920. rendered = render_jinja_tmpl("{{ ['192.168.0.1', '172.17.17.1', 'foo', 'bar', '::'] | ipaddr | join(', ') }}",
  921. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  922. self.assertEqual(rendered, '192.168.0.1, 172.17.17.1, ::')
  923. # return only multicast addresses
  924. rendered = render_jinja_tmpl("{{ ['224.0.0.1', 'FF01::1', '::'] | ipaddr(options='multicast') | join(', ') }}",
  925. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  926. self.assertEqual(rendered, '224.0.0.1, ff01::1')
  927. def test_ipv4(self):
  928. '''
  929. Test the `ipv4` Jinja filter.
  930. '''
  931. rendered = render_jinja_tmpl("{{ '192.168.0.1' | ipv4 }}",
  932. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  933. self.assertEqual(rendered, '192.168.0.1')
  934. rendered = render_jinja_tmpl("{{ ['192.168.0.1', '172.17.17.1'] | ipv4 | join(', ')}}",
  935. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  936. self.assertEqual(rendered, '192.168.0.1, 172.17.17.1')
  937. rendered = render_jinja_tmpl("{{ 'fe80::' | ipv4 }}",
  938. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  939. self.assertEqual(rendered, 'None')
  940. rendered = render_jinja_tmpl("{{ 'random' | ipv4 }}",
  941. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  942. self.assertEqual(rendered, 'None')
  943. rendered = render_jinja_tmpl("{{ '192.168.0.1' | ipv4(options='lo') }}",
  944. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  945. self.assertEqual(rendered, 'None')
  946. rendered = render_jinja_tmpl("{{ '127.0.0.1' | ipv4(options='lo') }}",
  947. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  948. self.assertEqual(rendered, '127.0.0.1')
  949. def test_ipv6(self):
  950. '''
  951. Test the `ipv6` Jinja filter.
  952. '''
  953. rendered = render_jinja_tmpl("{{ '192.168.0.1' | ipv6 }}",
  954. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  955. self.assertEqual(rendered, 'None')
  956. rendered = render_jinja_tmpl("{{ 'random' | ipv6 }}",
  957. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  958. self.assertEqual(rendered, 'None')
  959. # returns the standard format value
  960. rendered = render_jinja_tmpl("{{ 'FE80:0:0::0' | ipv6 }}",
  961. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  962. self.assertEqual(rendered, 'fe80::')
  963. # fe80:: is link local therefore will be returned
  964. rendered = render_jinja_tmpl("{{ 'fe80::' | ipv6(options='ll') }}",
  965. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  966. self.assertEqual(rendered, 'fe80::')
  967. # fe80:: is not loopback
  968. rendered = render_jinja_tmpl("{{ 'fe80::' | ipv6(options='lo') }}",
  969. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  970. self.assertEqual(rendered, 'None')
  971. # returns only IPv6 addresses in the list
  972. rendered = render_jinja_tmpl("{{ ['fe80::', '192.168.0.1'] | ipv6 | join(', ') }}",
  973. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  974. self.assertEqual(rendered, 'fe80::')
  975. rendered = render_jinja_tmpl("{{ ['fe80::', '::'] | ipv6 | join(', ') }}",
  976. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  977. self.assertEqual(rendered, 'fe80::, ::')
  978. def test_network_hosts(self):
  979. '''
  980. Test the `network_hosts` Jinja filter.
  981. '''
  982. rendered = render_jinja_tmpl("{{ '192.168.0.1/30' | network_hosts | join(', ') }}",
  983. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  984. self.assertEqual(rendered, '192.168.0.1, 192.168.0.2')
  985. def test_network_size(self):
  986. '''
  987. Test the `network_size` Jinja filter.
  988. '''
  989. rendered = render_jinja_tmpl("{{ '192.168.0.1' | network_size }}",
  990. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  991. self.assertEqual(rendered, '1')
  992. rendered = render_jinja_tmpl("{{ '192.168.0.1/8' | network_size }}",
  993. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  994. self.assertEqual(rendered, '16777216')
  995. @flaky
  996. def test_http_query(self):
  997. '''
  998. Test the `http_query` Jinja filter.
  999. '''
  1000. for backend in ('requests', 'tornado', 'urllib2'):
  1001. rendered = render_jinja_tmpl("{{ 'http://icanhazip.com' | http_query(backend='" + backend + "') }}",
  1002. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1003. self.assertIsInstance(rendered, six.text_type, 'Failed with backend: {}'.format(backend))
  1004. dict_reply = ast.literal_eval(rendered)
  1005. self.assertIsInstance(dict_reply, dict, 'Failed with backend: {}'.format(backend))
  1006. self.assertIsInstance(dict_reply['body'], six.string_types, 'Failed with backend: {}'.format(backend))
  1007. def test_to_bool(self):
  1008. '''
  1009. Test the `to_bool` Jinja filter.
  1010. '''
  1011. rendered = render_jinja_tmpl("{{ 1 | to_bool }}",
  1012. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1013. self.assertEqual(rendered, 'True')
  1014. rendered = render_jinja_tmpl("{{ 'True' | to_bool }}",
  1015. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1016. self.assertEqual(rendered, 'True')
  1017. rendered = render_jinja_tmpl("{{ 0 | to_bool }}",
  1018. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1019. self.assertEqual(rendered, 'False')
  1020. rendered = render_jinja_tmpl("{{ 'Yes' | to_bool }}",
  1021. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1022. self.assertEqual(rendered, 'True')
  1023. def test_quote(self):
  1024. '''
  1025. Test the `quote` Jinja filter.
  1026. '''
  1027. rendered = render_jinja_tmpl("{{ 'random' | quote }}",
  1028. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1029. self.assertEqual(rendered, 'random')
  1030. def test_regex_search(self):
  1031. '''
  1032. Test the `regex_search` Jinja filter.
  1033. '''
  1034. rendered = render_jinja_tmpl("{{ 'abcdefabcdef' | regex_search('BC(.*)', ignorecase=True) }}",
  1035. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1036. self.assertEqual(rendered, "('defabcdef',)") # because search looks only at the beginning
  1037. def test_regex_match(self):
  1038. '''
  1039. Test the `regex_match` Jinja filter.
  1040. '''
  1041. rendered = render_jinja_tmpl("{{ 'abcdefabcdef' | regex_match('BC(.*)', ignorecase=True)}}",
  1042. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1043. self.assertEqual(rendered, "None")
  1044. def test_regex_replace(self):
  1045. '''
  1046. Test the `regex_replace` Jinja filter.
  1047. '''
  1048. rendered = render_jinja_tmpl(r"{{ 'lets replace spaces' | regex_replace('\s+', '__') }}",
  1049. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1050. self.assertEqual(rendered, 'lets__replace__spaces')
  1051. def test_uuid(self):
  1052. '''
  1053. Test the `uuid` Jinja filter.
  1054. '''
  1055. rendered = render_jinja_tmpl("{{ 'random' | uuid }}",
  1056. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1057. self.assertEqual(rendered, '3652b285-26ad-588e-a5dc-c2ee65edc804')
  1058. def test_min(self):
  1059. '''
  1060. Test the `min` Jinja filter.
  1061. '''
  1062. rendered = render_jinja_tmpl("{{ [1, 2, 3] | min }}",
  1063. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1064. self.assertEqual(rendered, '1')
  1065. def test_max(self):
  1066. '''
  1067. Test the `max` Jinja filter.
  1068. '''
  1069. rendered = render_jinja_tmpl("{{ [1, 2, 3] | max }}",
  1070. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1071. self.assertEqual(rendered, '3')
  1072. def test_avg(self):
  1073. '''
  1074. Test the `avg` Jinja filter.
  1075. '''
  1076. rendered = render_jinja_tmpl("{{ [1, 2, 3] | avg }}",
  1077. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1078. self.assertEqual(rendered, '2.0')
  1079. def test_union(self):
  1080. '''
  1081. Test the `union` Jinja filter.
  1082. '''
  1083. rendered = render_jinja_tmpl("{{ [1, 2, 3] | union([2, 3, 4]) | join(', ') }}",
  1084. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1085. self.assertEqual(rendered, '1, 2, 3, 4')
  1086. def test_intersect(self):
  1087. '''
  1088. Test the `intersect` Jinja filter.
  1089. '''
  1090. rendered = render_jinja_tmpl("{{ [1, 2, 3] | intersect([2, 3, 4]) | join(', ') }}",
  1091. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1092. self.assertEqual(rendered, '2, 3')
  1093. def test_difference(self):
  1094. '''
  1095. Test the `difference` Jinja filter.
  1096. '''
  1097. rendered = render_jinja_tmpl("{{ [1, 2, 3] | difference([2, 3, 4]) | join(', ') }}",
  1098. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1099. self.assertEqual(rendered, '1')
  1100. def test_symmetric_difference(self):
  1101. '''
  1102. Test the `symmetric_difference` Jinja filter.
  1103. '''
  1104. rendered = render_jinja_tmpl("{{ [1, 2, 3] | symmetric_difference([2, 3, 4]) | join(', ') }}",
  1105. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1106. self.assertEqual(rendered, '1, 4')
  1107. def test_md5(self):
  1108. '''
  1109. Test the `md5` Jinja filter.
  1110. '''
  1111. rendered = render_jinja_tmpl("{{ 'random' | md5 }}",
  1112. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1113. self.assertEqual(rendered, '7ddf32e17a6ac5ce04a8ecbf782ca509')
  1114. def test_sha256(self):
  1115. '''
  1116. Test the `sha256` Jinja filter.
  1117. '''
  1118. rendered = render_jinja_tmpl("{{ 'random' | sha256 }}",
  1119. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1120. self.assertEqual(rendered, 'a441b15fe9a3cf56661190a0b93b9dec7d04127288cc87250967cf3b52894d11')
  1121. def test_sha512(self):
  1122. '''
  1123. Test the `sha512` Jinja filter.
  1124. '''
  1125. rendered = render_jinja_tmpl("{{ 'random' | sha512 }}",
  1126. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1127. self.assertEqual(rendered, six.text_type(('811a90e1c8e86c7b4c0eef5b2c0bf0ec1b19c4b1b5a242e6455be93787cb473cb7bc'
  1128. '9b0fdeb960d00d5c6881c2094dd63c5c900ce9057255e2a4e271fc25fef1')))
  1129. def test_hmac(self):
  1130. '''
  1131. Test the `hmac` Jinja filter.
  1132. '''
  1133. rendered = render_jinja_tmpl("{{ 'random' | hmac('secret', 'blah') }}",
  1134. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1135. self.assertEqual(rendered, 'False')
  1136. rendered = render_jinja_tmpl(("{{ 'get salted' | "
  1137. "hmac('shared secret', 'eBWf9bstXg+NiP5AOwppB5HMvZiYMPzEM9W5YMm/AmQ=') }}"),
  1138. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1139. self.assertEqual(rendered, 'True')
  1140. def test_base64_encode(self):
  1141. '''
  1142. Test the `base64_encode` Jinja filter.
  1143. '''
  1144. rendered = render_jinja_tmpl("{{ 'random' | base64_encode }}",
  1145. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1146. self.assertEqual(rendered, 'cmFuZG9t')
  1147. def test_base64_decode(self):
  1148. '''
  1149. Test the `base64_decode` Jinja filter.
  1150. '''
  1151. rendered = render_jinja_tmpl("{{ 'cmFuZG9t' | base64_decode }}",
  1152. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1153. self.assertEqual(rendered, 'random')
  1154. # def test_print(self):
  1155. # env = Environment(extensions=[SerializerExtension])
  1156. # source = '{% import_yaml "toto.foo" as docu %}'
  1157. # name, filename = None, '<filename>'
  1158. # parsed = env._parse(source, name, filename)
  1159. # print parsed
  1160. # print
  1161. # compiled = env._generate(parsed, name, filename)
  1162. # print compiled
  1163. # return
  1164. class TestDotNotationLookup(ModuleCase):
  1165. '''
  1166. Tests to call Salt functions via Jinja with various lookup syntaxes
  1167. '''
  1168. def setUp(self, *args, **kwargs):
  1169. functions = {
  1170. 'mocktest.ping': lambda: True,
  1171. 'mockgrains.get': lambda x: 'jerry',
  1172. }
  1173. minion_opts = salt.config.minion_config(os.path.join(TMP_CONF_DIR, 'minion'))
  1174. render = salt.loader.render(minion_opts, functions)
  1175. self.jinja = render.get('jinja')
  1176. def tearDown(self):
  1177. del self.jinja
  1178. def render(self, tmpl_str, context=None):
  1179. return self.jinja(tmpl_str, context=context or {}, from_str=True).read()
  1180. def test_normlookup(self):
  1181. '''
  1182. Sanity-check the normal dictionary-lookup syntax for our stub function
  1183. '''
  1184. tmpl_str = '''Hello, {{ salt['mocktest.ping']() }}.'''
  1185. with patch.object(SaltCacheLoader, 'file_client', Mock()):
  1186. ret = self.render(tmpl_str)
  1187. self.assertEqual(ret, 'Hello, True.')
  1188. def test_dotlookup(self):
  1189. '''
  1190. Check calling a stub function using awesome dot-notation
  1191. '''
  1192. tmpl_str = '''Hello, {{ salt.mocktest.ping() }}.'''
  1193. with patch.object(SaltCacheLoader, 'file_client', Mock()):
  1194. ret = self.render(tmpl_str)
  1195. self.assertEqual(ret, 'Hello, True.')
  1196. def test_shadowed_dict_method(self):
  1197. '''
  1198. Check calling a stub function with a name that shadows a ``dict``
  1199. method name
  1200. '''
  1201. tmpl_str = '''Hello, {{ salt.mockgrains.get('id') }}.'''
  1202. with patch.object(SaltCacheLoader, 'file_client', Mock()):
  1203. ret = self.render(tmpl_str)
  1204. self.assertEqual(ret, 'Hello, jerry.')