test_jinja.py 63 KB

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