1
0

test_jinja.py 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  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.runtests import RUNTIME_VARS
  17. from tests.support.unit import skipIf, TestCase
  18. from tests.support.case import ModuleCase
  19. from tests.support.helpers import flaky
  20. from tests.support.mock import patch, MagicMock, Mock
  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. BLINESEP = salt.utils.stringutils.to_bytes(os.linesep)
  49. class JinjaTestCase(TestCase):
  50. def test_tojson(self):
  51. '''
  52. Test the tojson filter for those using Jinja < 2.9. Non-ascii unicode
  53. content should be dumped with ensure_ascii=True.
  54. '''
  55. data = {'Non-ascii words': ['süß', 'спам', 'яйца']}
  56. result = tojson(data)
  57. expected = ('{"Non-ascii words": ["s\\u00fc\\u00df", '
  58. '"\\u0441\\u043f\\u0430\\u043c", '
  59. '"\\u044f\\u0439\\u0446\\u0430"]}')
  60. assert result == expected, result
  61. class MockFileClient(object):
  62. '''
  63. Does not download files but records any file request for testing
  64. '''
  65. def __init__(self, loader=None):
  66. if loader:
  67. loader._file_client = self
  68. self.requests = []
  69. def get_file(self, template, dest='', makedirs=False, saltenv='base'):
  70. self.requests.append({
  71. 'path': template,
  72. 'dest': dest,
  73. 'makedirs': makedirs,
  74. 'saltenv': saltenv
  75. })
  76. def _setup_test_dir(src_dir, test_dir):
  77. os.makedirs(test_dir)
  78. salt.utils.files.recursive_copy(src_dir, test_dir)
  79. filename = os.path.join(test_dir, 'non_ascii')
  80. with salt.utils.files.fopen(filename, 'wb') as fp:
  81. fp.write(b'Assun\xc3\xa7\xc3\xa3o' + BLINESEP)
  82. filename = os.path.join(test_dir, 'hello_simple')
  83. with salt.utils.files.fopen(filename, 'wb') as fp:
  84. fp.write(b'world' + BLINESEP)
  85. filename = os.path.join(test_dir, 'hello_import')
  86. lines = [
  87. r"{% from 'macro' import mymacro -%}",
  88. r"{% from 'macro' import mymacro -%}",
  89. r"{{ mymacro('Hey') ~ mymacro(a|default('a'), b|default('b')) }}",
  90. ]
  91. with salt.utils.files.fopen(filename, 'wb') as fp:
  92. for line in lines:
  93. fp.write(line.encode('utf-8') + BLINESEP)
  94. class TestSaltCacheLoader(TestCase):
  95. def setUp(self):
  96. self.tempdir = tempfile.mkdtemp()
  97. self.template_dir = os.path.join(self.tempdir, 'files', 'test')
  98. _setup_test_dir(
  99. os.path.join(RUNTIME_VARS.BASE_FILES, 'templates'),
  100. self.template_dir
  101. )
  102. self.opts = {
  103. 'file_buffer_size': 1048576,
  104. 'cachedir': self.tempdir,
  105. 'file_roots': {
  106. 'test': [self.template_dir]
  107. },
  108. 'pillar_roots': {
  109. 'test': [self.template_dir]
  110. },
  111. 'extension_modules': os.path.join(
  112. os.path.dirname(os.path.abspath(__file__)),
  113. 'extmods'),
  114. }
  115. super(TestSaltCacheLoader, self).setUp()
  116. def tearDown(self):
  117. salt.utils.files.rm_rf(self.tempdir)
  118. def test_searchpath(self):
  119. '''
  120. The searchpath is based on the cachedir option and the saltenv parameter
  121. '''
  122. tmp = tempfile.gettempdir()
  123. opts = copy.deepcopy(self.opts)
  124. opts.update({'cachedir': tmp})
  125. loader = self.get_loader(opts=opts, saltenv='test')
  126. assert loader.searchpath == [os.path.join(tmp, 'files', 'test')]
  127. def test_mockclient(self):
  128. '''
  129. A MockFileClient is used that records all file requests normally sent
  130. to the master.
  131. '''
  132. loader = self.get_loader(opts=self.opts, saltenv='test')
  133. res = loader.get_source(None, 'hello_simple')
  134. assert len(res) == 3
  135. # res[0] on Windows is unicode and use os.linesep so it works cross OS
  136. self.assertEqual(six.text_type(res[0]), 'world' + os.linesep)
  137. tmpl_dir = os.path.join(self.template_dir, 'hello_simple')
  138. self.assertEqual(res[1], tmpl_dir)
  139. assert res[2](), 'Template up to date?'
  140. assert len(loader._file_client.requests)
  141. self.assertEqual(loader._file_client.requests[0]['path'], 'salt://hello_simple')
  142. def get_loader(self, opts=None, saltenv='base'):
  143. '''
  144. Now that we instantiate the client in the __init__, we need to mock it
  145. '''
  146. if opts is None:
  147. opts = self.opts
  148. with patch.object(SaltCacheLoader, 'file_client', Mock()):
  149. loader = SaltCacheLoader(opts, saltenv)
  150. self.addCleanup(setattr, SaltCacheLoader, '_cached_client', None)
  151. # Create a mock file client and attach it to the loader
  152. MockFileClient(loader)
  153. return loader
  154. def get_test_saltenv(self):
  155. '''
  156. Setup a simple jinja test environment
  157. '''
  158. loader = self.get_loader(saltenv='test')
  159. jinja = Environment(loader=loader)
  160. return loader._file_client, jinja
  161. def test_import(self):
  162. '''
  163. You can import and use macros from other files
  164. '''
  165. fc, jinja = self.get_test_saltenv()
  166. result = jinja.get_template('hello_import').render()
  167. self.assertEqual(result, 'Hey world !a b !')
  168. assert len(fc.requests) == 2
  169. self.assertEqual(fc.requests[0]['path'], 'salt://hello_import')
  170. self.assertEqual(fc.requests[1]['path'], 'salt://macro')
  171. def test_relative_import(self):
  172. '''
  173. You can import using relative paths
  174. issue-13889
  175. '''
  176. fc, jinja = self.get_test_saltenv()
  177. tmpl = jinja.get_template(os.path.join('relative', 'rhello'))
  178. result = tmpl.render()
  179. self.assertEqual(result, 'Hey world !a b !')
  180. assert len(fc.requests) == 3
  181. self.assertEqual(fc.requests[0]['path'], os.path.join('salt://relative', 'rhello'))
  182. self.assertEqual(fc.requests[1]['path'], os.path.join('salt://relative', 'rmacro'))
  183. self.assertEqual(fc.requests[2]['path'], 'salt://macro')
  184. # This must fail when rendered: attempts to import from outside file root
  185. template = jinja.get_template('relative/rescape')
  186. self.assertRaises(exceptions.TemplateNotFound, template.render)
  187. def test_include(self):
  188. '''
  189. You can also include a template that imports and uses macros
  190. '''
  191. fc, jinja = self.get_test_saltenv()
  192. result = jinja.get_template('hello_include').render()
  193. self.assertEqual(result, 'Hey world !a b !')
  194. assert len(fc.requests) == 3
  195. self.assertEqual(fc.requests[0]['path'], 'salt://hello_include')
  196. self.assertEqual(fc.requests[1]['path'], 'salt://hello_import')
  197. self.assertEqual(fc.requests[2]['path'], 'salt://macro')
  198. def test_include_context(self):
  199. '''
  200. Context variables are passes to the included template by default.
  201. '''
  202. _, jinja = self.get_test_saltenv()
  203. result = jinja.get_template('hello_include').render(a='Hi', b='Salt')
  204. self.assertEqual(result, 'Hey world !Hi Salt !')
  205. def test_cached_file_client(self):
  206. '''
  207. Multiple instantiations of SaltCacheLoader use the cached file client
  208. '''
  209. with patch('salt.transport.client.ReqChannel.factory', Mock()):
  210. loader_a = SaltCacheLoader(self.opts)
  211. loader_b = SaltCacheLoader(self.opts)
  212. assert loader_a._file_client is loader_b._file_client
  213. def test_file_client_kwarg(self):
  214. '''
  215. A file client can be passed to SaltCacheLoader overriding the any
  216. cached file client
  217. '''
  218. mfc = MockFileClient()
  219. loader = SaltCacheLoader(self.opts, _file_client=mfc)
  220. assert loader._file_client is mfc
  221. def test_cache_loader_shutdown(self):
  222. '''
  223. The shudown method can be called without raising an exception when the
  224. file_client does not have a destroy method
  225. '''
  226. mfc = MockFileClient()
  227. assert not hasattr(mfc, 'destroy')
  228. loader = SaltCacheLoader(self.opts, _file_client=mfc)
  229. assert loader._file_client is mfc
  230. # Shutdown method should not raise any exceptions
  231. loader.shutdown()
  232. class TestGetTemplate(TestCase):
  233. def setUp(self):
  234. self.tempdir = tempfile.mkdtemp()
  235. self.template_dir = os.path.join(self.tempdir, 'files', 'test')
  236. _setup_test_dir(
  237. os.path.join(RUNTIME_VARS.BASE_FILES, 'templates'),
  238. self.template_dir
  239. )
  240. self.local_opts = {
  241. 'file_buffer_size': 1048576,
  242. 'cachedir': self.tempdir,
  243. 'file_client': 'local',
  244. 'file_ignore_regex': None,
  245. 'file_ignore_glob': None,
  246. 'file_roots': {
  247. 'test': [self.template_dir]
  248. },
  249. 'pillar_roots': {
  250. 'test': [self.template_dir]
  251. },
  252. 'fileserver_backend': ['roots'],
  253. 'hash_type': 'md5',
  254. 'extension_modules': os.path.join(
  255. os.path.dirname(os.path.abspath(__file__)),
  256. 'extmods'),
  257. }
  258. self.local_salt = {}
  259. super(TestGetTemplate, self).setUp()
  260. def tearDown(self):
  261. salt.utils.files.rm_rf(self.tempdir)
  262. def test_fallback(self):
  263. '''
  264. A Template with a filesystem loader is returned as fallback
  265. if the file is not contained in the searchpath
  266. '''
  267. fn_ = os.path.join(self.template_dir, 'hello_simple')
  268. with salt.utils.files.fopen(fn_) as fp_:
  269. out = render_jinja_tmpl(
  270. salt.utils.stringutils.to_unicode(fp_.read()),
  271. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  272. )
  273. self.assertEqual(out, 'world' + os.linesep)
  274. def test_fallback_noloader(self):
  275. '''
  276. A Template with a filesystem loader is returned as fallback
  277. if the file is not contained in the searchpath
  278. '''
  279. filename = os.path.join(self.template_dir, 'hello_import')
  280. with salt.utils.files.fopen(filename) as fp_:
  281. out = render_jinja_tmpl(
  282. salt.utils.stringutils.to_unicode(fp_.read()),
  283. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  284. )
  285. self.assertEqual(out, 'Hey world !a b !' + os.linesep)
  286. def test_saltenv(self):
  287. '''
  288. If the template is within the searchpath it can
  289. import, include and extend other templates.
  290. The initial template is expected to be already cached
  291. get_template does not request it from the master again.
  292. '''
  293. fc = MockFileClient()
  294. with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
  295. filename = os.path.join(self.template_dir, 'hello_import')
  296. with salt.utils.files.fopen(filename) as fp_:
  297. out = render_jinja_tmpl(
  298. salt.utils.stringutils.to_unicode(fp_.read()),
  299. dict(opts={'cachedir': self.tempdir, 'file_client': 'remote',
  300. 'file_roots': self.local_opts['file_roots'],
  301. 'pillar_roots': self.local_opts['pillar_roots']},
  302. a='Hi', b='Salt', saltenv='test', salt=self.local_salt))
  303. self.assertEqual(out, 'Hey world !Hi Salt !' + os.linesep)
  304. self.assertEqual(fc.requests[0]['path'], 'salt://macro')
  305. def test_macro_additional_log_for_generalexc(self):
  306. '''
  307. If we failed in a macro because of e.g. a TypeError, get
  308. more output from trace.
  309. '''
  310. expected = r'''Jinja error:.*division.*
  311. .*macrogeneral\(2\):
  312. ---
  313. \{% macro mymacro\(\) -%\}
  314. \{\{ 1/0 \}\} <======================
  315. \{%- endmacro %\}
  316. ---.*'''
  317. filename = os.path.join(self.template_dir, 'hello_import_generalerror')
  318. fc = MockFileClient()
  319. with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
  320. with salt.utils.files.fopen(filename) as fp_:
  321. self.assertRaisesRegex(
  322. SaltRenderError,
  323. expected,
  324. render_jinja_tmpl,
  325. salt.utils.stringutils.to_unicode(fp_.read()),
  326. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  327. def test_macro_additional_log_for_undefined(self):
  328. '''
  329. If we failed in a macro because of undefined variables, get
  330. more output from trace.
  331. '''
  332. expected = r'''Jinja variable 'b' is undefined
  333. .*macroundefined\(2\):
  334. ---
  335. \{% macro mymacro\(\) -%\}
  336. \{\{b.greetee\}\} <-- error is here <======================
  337. \{%- endmacro %\}
  338. ---'''
  339. filename = os.path.join(self.template_dir, 'hello_import_undefined')
  340. fc = MockFileClient()
  341. with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
  342. with salt.utils.files.fopen(filename) as fp_:
  343. self.assertRaisesRegex(
  344. SaltRenderError,
  345. expected,
  346. render_jinja_tmpl,
  347. salt.utils.stringutils.to_unicode(fp_.read()),
  348. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  349. def test_macro_additional_log_syntaxerror(self):
  350. '''
  351. If we failed in a macro, get more output from trace.
  352. '''
  353. expected = r'''Jinja syntax error: expected token .*end.*got '-'.*
  354. .*macroerror\(2\):
  355. ---
  356. # macro
  357. \{% macro mymacro\(greeting, greetee='world'\) -\} <-- error is here <======================
  358. \{\{ greeting ~ ' ' ~ greetee \}\} !
  359. \{%- endmacro %\}
  360. ---.*'''
  361. filename = os.path.join(self.template_dir, 'hello_import_error')
  362. fc = MockFileClient()
  363. with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
  364. with salt.utils.files.fopen(filename) as fp_:
  365. self.assertRaisesRegex(
  366. SaltRenderError,
  367. expected,
  368. render_jinja_tmpl,
  369. salt.utils.stringutils.to_unicode(fp_.read()),
  370. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  371. def test_non_ascii_encoding(self):
  372. fc = MockFileClient()
  373. with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
  374. filename = os.path.join(self.template_dir, 'hello_import')
  375. with salt.utils.files.fopen(filename) as fp_:
  376. out = render_jinja_tmpl(
  377. salt.utils.stringutils.to_unicode(fp_.read()),
  378. dict(opts={'cachedir': self.tempdir, 'file_client': 'remote',
  379. 'file_roots': self.local_opts['file_roots'],
  380. 'pillar_roots': self.local_opts['pillar_roots']},
  381. a='Hi', b='Sàlt', saltenv='test', salt=self.local_salt))
  382. self.assertEqual(out, salt.utils.stringutils.to_unicode('Hey world !Hi Sàlt !' + os.linesep))
  383. self.assertEqual(fc.requests[0]['path'], 'salt://macro')
  384. filename = os.path.join(self.template_dir, 'non_ascii')
  385. with salt.utils.files.fopen(filename, 'rb') as fp_:
  386. out = render_jinja_tmpl(
  387. salt.utils.stringutils.to_unicode(fp_.read(), 'utf-8'),
  388. dict(opts={'cachedir': self.tempdir, 'file_client': 'remote',
  389. 'file_roots': self.local_opts['file_roots'],
  390. 'pillar_roots': self.local_opts['pillar_roots']},
  391. a='Hi', b='Sàlt', saltenv='test', salt=self.local_salt))
  392. self.assertEqual('Assunção' + os.linesep, out)
  393. self.assertEqual(fc.requests[0]['path'], 'salt://macro')
  394. @skipIf(HAS_TIMELIB is False, 'The `timelib` library is not installed.')
  395. def test_strftime(self):
  396. response = render_jinja_tmpl(
  397. '{{ "2002/12/25"|strftime }}',
  398. dict(
  399. opts=self.local_opts,
  400. saltenv='test',
  401. salt=self.local_salt
  402. ))
  403. self.assertEqual(response, '2002-12-25')
  404. objects = (
  405. datetime.datetime(2002, 12, 25, 12, 00, 00, 00),
  406. '2002/12/25',
  407. 1040814000,
  408. '1040814000'
  409. )
  410. for object in objects:
  411. response = render_jinja_tmpl(
  412. '{{ object|strftime }}',
  413. dict(
  414. object=object,
  415. opts=self.local_opts,
  416. saltenv='test',
  417. salt=self.local_salt
  418. ))
  419. self.assertEqual(response, '2002-12-25')
  420. response = render_jinja_tmpl(
  421. '{{ object|strftime("%b %d, %Y") }}',
  422. dict(
  423. object=object,
  424. opts=self.local_opts,
  425. saltenv='test',
  426. salt=self.local_salt
  427. ))
  428. self.assertEqual(response, 'Dec 25, 2002')
  429. response = render_jinja_tmpl(
  430. '{{ object|strftime("%y") }}',
  431. dict(
  432. object=object,
  433. opts=self.local_opts,
  434. saltenv='test',
  435. salt=self.local_salt
  436. ))
  437. self.assertEqual(response, '02')
  438. def test_non_ascii(self):
  439. fn = os.path.join(self.template_dir, 'non_ascii')
  440. out = JINJA(
  441. fn,
  442. opts=self.local_opts,
  443. saltenv='test',
  444. salt=self.local_salt
  445. )
  446. with salt.utils.files.fopen(out['data'], 'rb') as fp:
  447. result = salt.utils.stringutils.to_unicode(fp.read(), 'utf-8')
  448. self.assertEqual(salt.utils.stringutils.to_unicode('Assunção' + os.linesep), result)
  449. def test_get_context_has_enough_context(self):
  450. template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf'
  451. context = salt.utils.stringutils.get_context(template, 8)
  452. expected = '---\n[...]\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\n[...]\n---'
  453. self.assertEqual(expected, context)
  454. def test_get_context_at_top_of_file(self):
  455. template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf'
  456. context = salt.utils.stringutils.get_context(template, 1)
  457. expected = '---\n1\n2\n3\n4\n5\n6\n[...]\n---'
  458. self.assertEqual(expected, context)
  459. def test_get_context_at_bottom_of_file(self):
  460. template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf'
  461. context = salt.utils.stringutils.get_context(template, 15)
  462. expected = '---\n[...]\na\nb\nc\nd\ne\nf\n---'
  463. self.assertEqual(expected, context)
  464. def test_get_context_2_context_lines(self):
  465. template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf'
  466. context = salt.utils.stringutils.get_context(template, 8, num_lines=2)
  467. expected = '---\n[...]\n6\n7\n8\n9\na\n[...]\n---'
  468. self.assertEqual(expected, context)
  469. def test_get_context_with_marker(self):
  470. template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf'
  471. context = salt.utils.stringutils.get_context(template, 8, num_lines=2, marker=' <---')
  472. expected = '---\n[...]\n6\n7\n8 <---\n9\na\n[...]\n---'
  473. self.assertEqual(expected, context)
  474. def test_render_with_syntax_error(self):
  475. template = 'hello\n\n{{ bad\n\nfoo'
  476. expected = r'.*---\nhello\n\n{{ bad\n\nfoo <======================\n---'
  477. self.assertRaisesRegex(
  478. SaltRenderError,
  479. expected,
  480. render_jinja_tmpl,
  481. template,
  482. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  483. )
  484. @skipIf(six.PY3, 'Not applicable to Python 3')
  485. def test_render_with_unicode_syntax_error(self):
  486. with patch.object(builtins, '__salt_system_encoding__', 'utf-8'):
  487. template = 'hello\n\n{{ bad\n\nfoo한'
  488. expected = r'.*---\nhello\n\n{{ bad\n\nfoo\xed\x95\x9c <======================\n---'
  489. self.assertRaisesRegex(
  490. SaltRenderError,
  491. expected,
  492. render_jinja_tmpl,
  493. template,
  494. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  495. )
  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': os.path.join(RUNTIME_VARS.TMP, 'jinja-template-cache'),
  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(RUNTIME_VARS.BASE_FILES, 'templates')]
  550. },
  551. 'pillar_roots': {
  552. 'test': [os.path.join(RUNTIME_VARS.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': os.path.join(RUNTIME_VARS.TMP, 'jinja-template-cache'),
  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(RUNTIME_VARS.BASE_FILES, 'templates')]
  605. },
  606. 'pillar_roots': {
  607. 'test': [os.path.join(RUNTIME_VARS.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. rendered = env.from_string('{{ data }}').render(data=data)
  830. self.assertEqual(
  831. rendered,
  832. "{u'foo': {u'bar': u'baz', u'qux': 42}}" if six.PY2
  833. else "{'foo': {'bar': 'baz', 'qux': 42}}"
  834. )
  835. rendered = env.from_string('{{ data }}').render(data=[
  836. OrderedDict(
  837. foo='bar',
  838. ),
  839. OrderedDict(
  840. baz=42,
  841. )
  842. ])
  843. self.assertEqual(
  844. rendered,
  845. "[{'foo': u'bar'}, {'baz': 42}]" if six.PY2
  846. else "[{'foo': 'bar'}, {'baz': 42}]"
  847. )
  848. def test_set_dict_key_value(self):
  849. '''
  850. Test the `set_dict_key_value` Jinja filter.
  851. '''
  852. rendered = render_jinja_tmpl("{{ {} | set_dict_key_value('foo:bar:baz', 42) }}",
  853. dict(opts=self.local_opts,
  854. saltenv='test',
  855. salt=self.local_salt))
  856. self.assertEqual(rendered, "{'foo': {'bar': {'baz': 42}}}")
  857. rendered = render_jinja_tmpl("{{ {} | set_dict_key_value('foo.bar.baz', 42, delimiter='.') }}",
  858. dict(opts=self.local_opts,
  859. saltenv='test',
  860. salt=self.local_salt))
  861. self.assertEqual(rendered, "{'foo': {'bar': {'baz': 42}}}")
  862. def test_update_dict_key_value(self):
  863. '''
  864. Test the `update_dict_key_value` Jinja filter.
  865. '''
  866. # Use OrderedDicts to avoid random key-order-switches in the rendered string.
  867. expected = OrderedDict([('bar', OrderedDict([('baz', OrderedDict([('qux', 1), ('quux', 3)]))]))])
  868. dataset = OrderedDict([('bar', OrderedDict([('baz', OrderedDict([('qux', 1)]))]))])
  869. dataset_exp = OrderedDict([('quux', 3)])
  870. rendered = render_jinja_tmpl("{{ foo | update_dict_key_value('bar:baz', exp) }}",
  871. dict(foo=dataset,
  872. exp=dataset_exp,
  873. opts=self.local_opts,
  874. saltenv='test',
  875. salt=self.local_salt))
  876. self.assertEqual(
  877. rendered,
  878. "{u'bar': {u'baz': {u'qux': 1, u'quux': 3}}}" if six.PY2
  879. else "{'bar': {'baz': {'qux': 1, 'quux': 3}}}")
  880. # Test incorrect usage
  881. for update_with in [42, 'foo', [42]]:
  882. template = "{{ {} | update_dict_key_value('bar:baz', update_with) }}"
  883. expected = r"Cannot update {} with a {}.".format(type({}), type(update_with))
  884. self.assertRaisesRegex(
  885. SaltRenderError,
  886. expected,
  887. render_jinja_tmpl,
  888. template,
  889. dict(update_with=update_with,
  890. opts=self.local_opts,
  891. saltenv='test',
  892. salt=self.local_salt)
  893. )
  894. def test_append_dict_key_value(self):
  895. '''
  896. Test the `append_dict_key_value` Jinja filter.
  897. '''
  898. rendered = render_jinja_tmpl("{{ {} | append_dict_key_value('foo:bar:baz', 42) }}",
  899. dict(opts=self.local_opts,
  900. saltenv='test',
  901. salt=self.local_salt))
  902. self.assertEqual(rendered, "{'foo': {'bar': {'baz': [42]}}}")
  903. rendered = render_jinja_tmpl("{{ foo | append_dict_key_value('bar:baz', 42) }}",
  904. dict(foo={'bar': {'baz': [1, 2]}},
  905. opts=self.local_opts,
  906. saltenv='test',
  907. salt=self.local_salt))
  908. self.assertEqual(
  909. rendered,
  910. "{u'bar': {u'baz': [1, 2, 42]}}" if six.PY2
  911. else "{'bar': {'baz': [1, 2, 42]}}"
  912. )
  913. def test_extend_dict_key_value(self):
  914. '''
  915. Test the `extend_dict_key_value` Jinja filter.
  916. '''
  917. rendered = render_jinja_tmpl("{{ {} | extend_dict_key_value('foo:bar:baz', [42]) }}",
  918. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  919. self.assertEqual(rendered, "{'foo': {'bar': {'baz': [42]}}}")
  920. rendered = render_jinja_tmpl("{{ foo | extend_dict_key_value('bar:baz', [42, 43]) }}",
  921. dict(foo={'bar': {'baz': [1, 2]}},
  922. opts=self.local_opts,
  923. saltenv='test',
  924. salt=self.local_salt))
  925. self.assertEqual(
  926. rendered,
  927. "{u'bar': {u'baz': [1, 2, 42, 43]}}" if six.PY2
  928. else "{'bar': {'baz': [1, 2, 42, 43]}}"
  929. )
  930. # Edge cases
  931. rendered = render_jinja_tmpl("{{ {} | extend_dict_key_value('foo:bar:baz', 'quux') }}",
  932. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  933. self.assertEqual(rendered, "{'foo': {'bar': {'baz': ['q', 'u', 'u', 'x']}}}")
  934. # Beware! When supplying a dict, the list gets extended with the dict coerced to a list,
  935. # which will only contain the keys of the dict.
  936. rendered = render_jinja_tmpl("{{ {} | extend_dict_key_value('foo:bar:baz', {'foo': 'bar'}) }}",
  937. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  938. self.assertEqual(rendered, "{'foo': {'bar': {'baz': ['foo']}}}")
  939. # Test incorrect usage
  940. template = "{{ {} | extend_dict_key_value('bar:baz', 42) }}"
  941. expected = r"Cannot extend {} with a {}.".format(type([]), type(42))
  942. self.assertRaisesRegex(
  943. SaltRenderError,
  944. expected,
  945. render_jinja_tmpl,
  946. template,
  947. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt)
  948. )
  949. def test_sequence(self):
  950. env = Environment()
  951. env.filters['sequence'] = ensure_sequence_filter
  952. rendered = env.from_string('{{ data | sequence | length }}') \
  953. .render(data='foo')
  954. self.assertEqual(rendered, '1')
  955. rendered = env.from_string('{{ data | sequence | length }}') \
  956. .render(data=['foo', 'bar'])
  957. self.assertEqual(rendered, '2')
  958. rendered = env.from_string('{{ data | sequence | length }}') \
  959. .render(data=('foo', 'bar'))
  960. self.assertEqual(rendered, '2')
  961. rendered = env.from_string('{{ data | sequence | length }}') \
  962. .render(data=set(['foo', 'bar']))
  963. self.assertEqual(rendered, '2')
  964. rendered = env.from_string('{{ data | sequence | length }}') \
  965. .render(data={'foo': 'bar'})
  966. self.assertEqual(rendered, '1')
  967. def test_camel_to_snake_case(self):
  968. '''
  969. Test the `to_snake_case` Jinja filter.
  970. '''
  971. rendered = render_jinja_tmpl('{{ \'abcdEfghhIjkLmnoP\' | to_snake_case }}',
  972. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  973. self.assertEqual(rendered, 'abcd_efghh_ijk_lmno_p')
  974. def test_snake_to_camel_case(self):
  975. '''
  976. Test the `to_camelcase` Jinja filter.
  977. '''
  978. rendered = render_jinja_tmpl('{{ \'the_fox_jumped_over_the_lazy_dog\' | to_camelcase }}',
  979. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  980. self.assertEqual(rendered, 'theFoxJumpedOverTheLazyDog')
  981. rendered = render_jinja_tmpl('{{ \'the_fox_jumped_over_the_lazy_dog\' | to_camelcase(uppercamel=True) }}',
  982. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  983. self.assertEqual(rendered, 'TheFoxJumpedOverTheLazyDog')
  984. def test_is_ip(self):
  985. '''
  986. Test the `is_ip` Jinja filter.
  987. '''
  988. rendered = render_jinja_tmpl("{{ '192.168.0.1' | is_ip }}",
  989. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  990. self.assertEqual(rendered, 'True')
  991. rendered = render_jinja_tmpl("{{ 'FE80::' | is_ip }}",
  992. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  993. self.assertEqual(rendered, 'True')
  994. rendered = render_jinja_tmpl("{{ 'random' | is_ip }}",
  995. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  996. self.assertEqual(rendered, 'False')
  997. def test_is_ipv4(self):
  998. '''
  999. Test the `is_ipv4` Jinja filter.
  1000. '''
  1001. rendered = render_jinja_tmpl("{{ '192.168.0.1' | is_ipv4 }}",
  1002. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1003. self.assertEqual(rendered, 'True')
  1004. rendered = render_jinja_tmpl("{{ 'FE80::' | is_ipv4 }}",
  1005. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1006. self.assertEqual(rendered, 'False')
  1007. rendered = render_jinja_tmpl("{{ 'random' | is_ipv4 }}",
  1008. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1009. self.assertEqual(rendered, 'False')
  1010. def test_is_ipv6(self):
  1011. '''
  1012. Test the `is_ipv6` Jinja filter.
  1013. '''
  1014. rendered = render_jinja_tmpl("{{ '192.168.0.1' | is_ipv6 }}",
  1015. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1016. self.assertEqual(rendered, 'False')
  1017. rendered = render_jinja_tmpl("{{ 'fe80::20d:b9ff:fe01:ea8%eth0' | is_ipv6 }}",
  1018. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1019. self.assertEqual(rendered, 'True')
  1020. rendered = render_jinja_tmpl("{{ 'FE80::' | is_ipv6 }}",
  1021. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1022. self.assertEqual(rendered, 'True')
  1023. rendered = render_jinja_tmpl("{{ 'random' | is_ipv6 }}",
  1024. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1025. self.assertEqual(rendered, 'False')
  1026. def test_ipaddr(self):
  1027. '''
  1028. Test the `ipaddr` Jinja filter.
  1029. '''
  1030. rendered = render_jinja_tmpl("{{ '::' | ipaddr }}",
  1031. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1032. self.assertEqual(rendered, '::')
  1033. rendered = render_jinja_tmpl("{{ '192.168.0.1' | ipaddr }}",
  1034. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1035. self.assertEqual(rendered, '192.168.0.1')
  1036. # provides a list with valid IP addresses only
  1037. rendered = render_jinja_tmpl("{{ ['192.168.0.1', '172.17.17.1', 'foo', 'bar', '::'] | ipaddr | join(', ') }}",
  1038. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1039. self.assertEqual(rendered, '192.168.0.1, 172.17.17.1, ::')
  1040. # return only multicast addresses
  1041. rendered = render_jinja_tmpl("{{ ['224.0.0.1', 'FF01::1', '::'] | ipaddr(options='multicast') | join(', ') }}",
  1042. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1043. self.assertEqual(rendered, '224.0.0.1, ff01::1')
  1044. def test_ipv4(self):
  1045. '''
  1046. Test the `ipv4` Jinja filter.
  1047. '''
  1048. rendered = render_jinja_tmpl("{{ '192.168.0.1' | ipv4 }}",
  1049. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1050. self.assertEqual(rendered, '192.168.0.1')
  1051. rendered = render_jinja_tmpl("{{ ['192.168.0.1', '172.17.17.1'] | ipv4 | join(', ')}}",
  1052. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1053. self.assertEqual(rendered, '192.168.0.1, 172.17.17.1')
  1054. rendered = render_jinja_tmpl("{{ 'fe80::' | ipv4 }}",
  1055. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1056. self.assertEqual(rendered, 'None')
  1057. rendered = render_jinja_tmpl("{{ 'random' | ipv4 }}",
  1058. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1059. self.assertEqual(rendered, 'None')
  1060. rendered = render_jinja_tmpl("{{ '192.168.0.1' | ipv4(options='lo') }}",
  1061. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1062. self.assertEqual(rendered, 'None')
  1063. rendered = render_jinja_tmpl("{{ '127.0.0.1' | ipv4(options='lo') }}",
  1064. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1065. self.assertEqual(rendered, '127.0.0.1')
  1066. def test_ipv6(self):
  1067. '''
  1068. Test the `ipv6` Jinja filter.
  1069. '''
  1070. rendered = render_jinja_tmpl("{{ '192.168.0.1' | ipv6 }}",
  1071. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1072. self.assertEqual(rendered, 'None')
  1073. rendered = render_jinja_tmpl("{{ 'random' | ipv6 }}",
  1074. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1075. self.assertEqual(rendered, 'None')
  1076. # returns the standard format value
  1077. rendered = render_jinja_tmpl("{{ 'FE80:0:0::0' | ipv6 }}",
  1078. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1079. self.assertEqual(rendered, 'fe80::')
  1080. # fe80:: is link local therefore will be returned
  1081. rendered = render_jinja_tmpl("{{ 'fe80::' | ipv6(options='ll') }}",
  1082. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1083. self.assertEqual(rendered, 'fe80::')
  1084. # fe80:: is not loopback
  1085. rendered = render_jinja_tmpl("{{ 'fe80::' | ipv6(options='lo') }}",
  1086. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1087. self.assertEqual(rendered, 'None')
  1088. # returns only IPv6 addresses in the list
  1089. rendered = render_jinja_tmpl("{{ ['fe80::', '192.168.0.1'] | ipv6 | join(', ') }}",
  1090. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1091. self.assertEqual(rendered, 'fe80::')
  1092. rendered = render_jinja_tmpl("{{ ['fe80::', '::'] | ipv6 | join(', ') }}",
  1093. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1094. self.assertEqual(rendered, 'fe80::, ::')
  1095. def test_network_hosts(self):
  1096. '''
  1097. Test the `network_hosts` Jinja filter.
  1098. '''
  1099. rendered = render_jinja_tmpl("{{ '192.168.0.1/30' | network_hosts | join(', ') }}",
  1100. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1101. self.assertEqual(rendered, '192.168.0.1, 192.168.0.2')
  1102. def test_network_size(self):
  1103. '''
  1104. Test the `network_size` Jinja filter.
  1105. '''
  1106. rendered = render_jinja_tmpl("{{ '192.168.0.1' | network_size }}",
  1107. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1108. self.assertEqual(rendered, '1')
  1109. rendered = render_jinja_tmpl("{{ '192.168.0.1/8' | network_size }}",
  1110. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1111. self.assertEqual(rendered, '16777216')
  1112. @flaky
  1113. def test_http_query(self):
  1114. '''
  1115. Test the `http_query` Jinja filter.
  1116. '''
  1117. for backend in ('requests', 'tornado', 'urllib2'):
  1118. rendered = render_jinja_tmpl("{{ 'http://icanhazip.com' | http_query(backend='" + backend + "') }}",
  1119. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1120. self.assertIsInstance(rendered, six.text_type, 'Failed with backend: {}'.format(backend))
  1121. dict_reply = ast.literal_eval(rendered)
  1122. self.assertIsInstance(dict_reply, dict, 'Failed with backend: {}'.format(backend))
  1123. self.assertIsInstance(dict_reply['body'], six.string_types, 'Failed with backend: {}'.format(backend))
  1124. def test_to_bool(self):
  1125. '''
  1126. Test the `to_bool` Jinja filter.
  1127. '''
  1128. rendered = render_jinja_tmpl("{{ 1 | to_bool }}",
  1129. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1130. self.assertEqual(rendered, 'True')
  1131. rendered = render_jinja_tmpl("{{ 'True' | to_bool }}",
  1132. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1133. self.assertEqual(rendered, 'True')
  1134. rendered = render_jinja_tmpl("{{ 0 | to_bool }}",
  1135. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1136. self.assertEqual(rendered, 'False')
  1137. rendered = render_jinja_tmpl("{{ 'Yes' | to_bool }}",
  1138. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1139. self.assertEqual(rendered, 'True')
  1140. def test_quote(self):
  1141. '''
  1142. Test the `quote` Jinja filter.
  1143. '''
  1144. rendered = render_jinja_tmpl("{{ 'random' | quote }}",
  1145. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1146. self.assertEqual(rendered, 'random')
  1147. def test_regex_search(self):
  1148. '''
  1149. Test the `regex_search` Jinja filter.
  1150. '''
  1151. rendered = render_jinja_tmpl("{{ 'abcdefabcdef' | regex_search('BC(.*)', ignorecase=True) }}",
  1152. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1153. self.assertEqual(rendered, "('defabcdef',)") # because search looks only at the beginning
  1154. def test_regex_match(self):
  1155. '''
  1156. Test the `regex_match` Jinja filter.
  1157. '''
  1158. rendered = render_jinja_tmpl("{{ 'abcdefabcdef' | regex_match('BC(.*)', ignorecase=True)}}",
  1159. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1160. self.assertEqual(rendered, "None")
  1161. def test_regex_replace(self):
  1162. '''
  1163. Test the `regex_replace` Jinja filter.
  1164. '''
  1165. rendered = render_jinja_tmpl(r"{{ 'lets replace spaces' | regex_replace('\s+', '__') }}",
  1166. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1167. self.assertEqual(rendered, 'lets__replace__spaces')
  1168. def test_uuid(self):
  1169. '''
  1170. Test the `uuid` Jinja filter.
  1171. '''
  1172. rendered = render_jinja_tmpl("{{ 'random' | uuid }}",
  1173. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1174. self.assertEqual(rendered, '3652b285-26ad-588e-a5dc-c2ee65edc804')
  1175. def test_min(self):
  1176. '''
  1177. Test the `min` Jinja filter.
  1178. '''
  1179. rendered = render_jinja_tmpl("{{ [1, 2, 3] | min }}",
  1180. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1181. self.assertEqual(rendered, '1')
  1182. def test_max(self):
  1183. '''
  1184. Test the `max` Jinja filter.
  1185. '''
  1186. rendered = render_jinja_tmpl("{{ [1, 2, 3] | max }}",
  1187. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1188. self.assertEqual(rendered, '3')
  1189. def test_avg(self):
  1190. '''
  1191. Test the `avg` Jinja filter.
  1192. '''
  1193. rendered = render_jinja_tmpl("{{ [1, 2, 3] | avg }}",
  1194. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1195. self.assertEqual(rendered, '2.0')
  1196. def test_union(self):
  1197. '''
  1198. Test the `union` Jinja filter.
  1199. '''
  1200. rendered = render_jinja_tmpl("{{ [1, 2, 3] | union([2, 3, 4]) | join(', ') }}",
  1201. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1202. self.assertEqual(rendered, '1, 2, 3, 4')
  1203. def test_intersect(self):
  1204. '''
  1205. Test the `intersect` Jinja filter.
  1206. '''
  1207. rendered = render_jinja_tmpl("{{ [1, 2, 3] | intersect([2, 3, 4]) | join(', ') }}",
  1208. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1209. self.assertEqual(rendered, '2, 3')
  1210. def test_difference(self):
  1211. '''
  1212. Test the `difference` Jinja filter.
  1213. '''
  1214. rendered = render_jinja_tmpl("{{ [1, 2, 3] | difference([2, 3, 4]) | join(', ') }}",
  1215. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1216. self.assertEqual(rendered, '1')
  1217. def test_symmetric_difference(self):
  1218. '''
  1219. Test the `symmetric_difference` Jinja filter.
  1220. '''
  1221. rendered = render_jinja_tmpl("{{ [1, 2, 3] | symmetric_difference([2, 3, 4]) | join(', ') }}",
  1222. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1223. self.assertEqual(rendered, '1, 4')
  1224. def test_md5(self):
  1225. '''
  1226. Test the `md5` Jinja filter.
  1227. '''
  1228. rendered = render_jinja_tmpl("{{ 'random' | md5 }}",
  1229. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1230. self.assertEqual(rendered, '7ddf32e17a6ac5ce04a8ecbf782ca509')
  1231. def test_sha256(self):
  1232. '''
  1233. Test the `sha256` Jinja filter.
  1234. '''
  1235. rendered = render_jinja_tmpl("{{ 'random' | sha256 }}",
  1236. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1237. self.assertEqual(rendered, 'a441b15fe9a3cf56661190a0b93b9dec7d04127288cc87250967cf3b52894d11')
  1238. def test_sha512(self):
  1239. '''
  1240. Test the `sha512` Jinja filter.
  1241. '''
  1242. rendered = render_jinja_tmpl("{{ 'random' | sha512 }}",
  1243. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1244. self.assertEqual(rendered, six.text_type(('811a90e1c8e86c7b4c0eef5b2c0bf0ec1b19c4b1b5a242e6455be93787cb473cb7bc'
  1245. '9b0fdeb960d00d5c6881c2094dd63c5c900ce9057255e2a4e271fc25fef1')))
  1246. def test_hmac(self):
  1247. '''
  1248. Test the `hmac` Jinja filter.
  1249. '''
  1250. rendered = render_jinja_tmpl("{{ 'random' | hmac('secret', 'blah') }}",
  1251. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1252. self.assertEqual(rendered, 'False')
  1253. rendered = render_jinja_tmpl(("{{ 'get salted' | "
  1254. "hmac('shared secret', 'eBWf9bstXg+NiP5AOwppB5HMvZiYMPzEM9W5YMm/AmQ=') }}"),
  1255. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1256. self.assertEqual(rendered, 'True')
  1257. def test_base64_encode(self):
  1258. '''
  1259. Test the `base64_encode` Jinja filter.
  1260. '''
  1261. rendered = render_jinja_tmpl("{{ 'random' | base64_encode }}",
  1262. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1263. self.assertEqual(rendered, 'cmFuZG9t')
  1264. def test_base64_decode(self):
  1265. '''
  1266. Test the `base64_decode` Jinja filter.
  1267. '''
  1268. rendered = render_jinja_tmpl("{{ 'cmFuZG9t' | base64_decode }}",
  1269. dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
  1270. self.assertEqual(rendered, 'random')
  1271. # def test_print(self):
  1272. # env = Environment(extensions=[SerializerExtension])
  1273. # source = '{% import_yaml "toto.foo" as docu %}'
  1274. # name, filename = None, '<filename>'
  1275. # parsed = env._parse(source, name, filename)
  1276. # print parsed
  1277. # print
  1278. # compiled = env._generate(parsed, name, filename)
  1279. # print compiled
  1280. # return
  1281. class TestDotNotationLookup(ModuleCase):
  1282. '''
  1283. Tests to call Salt functions via Jinja with various lookup syntaxes
  1284. '''
  1285. def setUp(self, *args, **kwargs):
  1286. functions = {
  1287. 'mocktest.ping': lambda: True,
  1288. 'mockgrains.get': lambda x: 'jerry',
  1289. }
  1290. minion_opts = salt.config.minion_config(os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'minion'))
  1291. render = salt.loader.render(minion_opts, functions)
  1292. self.jinja = render.get('jinja')
  1293. def tearDown(self):
  1294. del self.jinja
  1295. def render(self, tmpl_str, context=None):
  1296. return self.jinja(tmpl_str, context=context or {}, from_str=True).read()
  1297. def test_normlookup(self):
  1298. '''
  1299. Sanity-check the normal dictionary-lookup syntax for our stub function
  1300. '''
  1301. tmpl_str = '''Hello, {{ salt['mocktest.ping']() }}.'''
  1302. with patch.object(SaltCacheLoader, 'file_client', Mock()):
  1303. ret = self.render(tmpl_str)
  1304. self.assertEqual(ret, 'Hello, True.')
  1305. def test_dotlookup(self):
  1306. '''
  1307. Check calling a stub function using awesome dot-notation
  1308. '''
  1309. tmpl_str = '''Hello, {{ salt.mocktest.ping() }}.'''
  1310. with patch.object(SaltCacheLoader, 'file_client', Mock()):
  1311. ret = self.render(tmpl_str)
  1312. self.assertEqual(ret, 'Hello, True.')
  1313. def test_shadowed_dict_method(self):
  1314. '''
  1315. Check calling a stub function with a name that shadows a ``dict``
  1316. method name
  1317. '''
  1318. tmpl_str = '''Hello, {{ salt.mockgrains.get('id') }}.'''
  1319. with patch.object(SaltCacheLoader, 'file_client', Mock()):
  1320. ret = self.render(tmpl_str)
  1321. self.assertEqual(ret, 'Hello, jerry.')