1
0

test_jinja.py 62 KB

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