test-jinja.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  1. #include <string>
  2. #include <iostream>
  3. #include <random>
  4. #include <cstdlib>
  5. #include <nlohmann/json.hpp>
  6. #include <sheredom/subprocess.h>
  7. #include "jinja/runtime.h"
  8. #include "jinja/parser.h"
  9. #include "jinja/lexer.h"
  10. #include "testing.h"
  11. using json = nlohmann::ordered_json;
  12. static void test_template(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect);
  13. static void test_whitespace_control(testing & t);
  14. static void test_conditionals(testing & t);
  15. static void test_loops(testing & t);
  16. static void test_expressions(testing & t);
  17. static void test_set_statement(testing & t);
  18. static void test_filters(testing & t);
  19. static void test_literals(testing & t);
  20. static void test_comments(testing & t);
  21. static void test_macros(testing & t);
  22. static void test_namespace(testing & t);
  23. static void test_tests(testing & t);
  24. static void test_string_methods(testing & t);
  25. static void test_array_methods(testing & t);
  26. static void test_object_methods(testing & t);
  27. static void test_fuzzing(testing & t);
  28. static bool g_python_mode = false;
  29. int main(int argc, char *argv[]) {
  30. testing t(std::cout);
  31. t.verbose = true;
  32. // usage: test-jinja [-py] [filter_regex]
  33. // -py : enable python mode (use python jinja2 for rendering expected output)
  34. // only use this for cross-checking, not for correctness
  35. // note: the implementation of this flag is basic, only intented to be used by maintainers
  36. for (int i = 1; i < argc; i++) {
  37. std::string arg = argv[i];
  38. if (arg == "-py") {
  39. g_python_mode = true;
  40. } else {
  41. t.set_filter(arg);
  42. }
  43. }
  44. t.test("whitespace control", test_whitespace_control);
  45. t.test("conditionals", test_conditionals);
  46. t.test("loops", test_loops);
  47. t.test("expressions", test_expressions);
  48. t.test("set statement", test_set_statement);
  49. t.test("filters", test_filters);
  50. t.test("literals", test_literals);
  51. t.test("comments", test_comments);
  52. t.test("macros", test_macros);
  53. t.test("namespace", test_namespace);
  54. t.test("tests", test_tests);
  55. t.test("string methods", test_string_methods);
  56. t.test("array methods", test_array_methods);
  57. t.test("object methods", test_object_methods);
  58. if (!g_python_mode) {
  59. t.test("fuzzing", test_fuzzing);
  60. }
  61. return t.summary();
  62. }
  63. static void test_whitespace_control(testing & t) {
  64. test_template(t, "trim_blocks removes newline after tag",
  65. "{% if true %}\n"
  66. "hello\n"
  67. "{% endif %}\n",
  68. json::object(),
  69. "hello\n"
  70. );
  71. test_template(t, "lstrip_blocks removes leading whitespace",
  72. " {% if true %}\n"
  73. " hello\n"
  74. " {% endif %}\n",
  75. json::object(),
  76. " hello\n"
  77. );
  78. test_template(t, "for loop with trim_blocks",
  79. "{% for i in items %}\n"
  80. "{{ i }}\n"
  81. "{% endfor %}\n",
  82. {{"items", json::array({1, 2, 3})}},
  83. "1\n2\n3\n"
  84. );
  85. test_template(t, "explicit strip both",
  86. " {%- if true -%} \n"
  87. "hello\n"
  88. " {%- endif -%} \n",
  89. json::object(),
  90. "hello"
  91. );
  92. test_template(t, "expression whitespace control",
  93. " {{- 'hello' -}} \n",
  94. json::object(),
  95. "hello"
  96. );
  97. test_template(t, "inline block no newline",
  98. "{% if true %}yes{% endif %}",
  99. json::object(),
  100. "yes"
  101. );
  102. }
  103. static void test_conditionals(testing & t) {
  104. test_template(t, "if true",
  105. "{% if cond %}yes{% endif %}",
  106. {{"cond", true}},
  107. "yes"
  108. );
  109. test_template(t, "if false",
  110. "{% if cond %}yes{% endif %}",
  111. {{"cond", false}},
  112. ""
  113. );
  114. test_template(t, "if else",
  115. "{% if cond %}yes{% else %}no{% endif %}",
  116. {{"cond", false}},
  117. "no"
  118. );
  119. test_template(t, "if elif else",
  120. "{% if a %}A{% elif b %}B{% else %}C{% endif %}",
  121. {{"a", false}, {"b", true}},
  122. "B"
  123. );
  124. test_template(t, "nested if",
  125. "{% if outer %}{% if inner %}both{% endif %}{% endif %}",
  126. {{"outer", true}, {"inner", true}},
  127. "both"
  128. );
  129. test_template(t, "comparison operators",
  130. "{% if x > 5 %}big{% endif %}",
  131. {{"x", 10}},
  132. "big"
  133. );
  134. test_template(t, "logical and",
  135. "{% if a and b %}both{% endif %}",
  136. {{"a", true}, {"b", true}},
  137. "both"
  138. );
  139. test_template(t, "logical or",
  140. "{% if a or b %}either{% endif %}",
  141. {{"a", false}, {"b", true}},
  142. "either"
  143. );
  144. test_template(t, "logical not",
  145. "{% if not a %}negated{% endif %}",
  146. {{"a", false}},
  147. "negated"
  148. );
  149. test_template(t, "in operator",
  150. "{% if 'x' in items %}found{% endif %}",
  151. {{"items", json::array({"x", "y"})}},
  152. "found"
  153. );
  154. test_template(t, "is defined",
  155. "{% if x is defined %}yes{% else %}no{% endif %}",
  156. {{"x", 1}},
  157. "yes"
  158. );
  159. test_template(t, "is not defined",
  160. "{% if y is not defined %}yes{% else %}no{% endif %}",
  161. json::object(),
  162. "yes"
  163. );
  164. }
  165. static void test_loops(testing & t) {
  166. test_template(t, "simple for",
  167. "{% for i in items %}{{ i }}{% endfor %}",
  168. {{"items", json::array({1, 2, 3})}},
  169. "123"
  170. );
  171. test_template(t, "loop.index",
  172. "{% for i in items %}{{ loop.index }}{% endfor %}",
  173. {{"items", json::array({"a", "b", "c"})}},
  174. "123"
  175. );
  176. test_template(t, "loop.index0",
  177. "{% for i in items %}{{ loop.index0 }}{% endfor %}",
  178. {{"items", json::array({"a", "b", "c"})}},
  179. "012"
  180. );
  181. test_template(t, "loop.first and loop.last",
  182. "{% for i in items %}{% if loop.first %}[{% endif %}{{ i }}{% if loop.last %}]{% endif %}{% endfor %}",
  183. {{"items", json::array({1, 2, 3})}},
  184. "[123]"
  185. );
  186. test_template(t, "loop.length",
  187. "{% for i in items %}{{ loop.length }}{% endfor %}",
  188. {{"items", json::array({"a", "b"})}},
  189. "22"
  190. );
  191. test_template(t, "for over dict items",
  192. "{% for k, v in data.items() %}{{ k }}={{ v }} {% endfor %}",
  193. {{"data", {{"x", 1}, {"y", 2}}}},
  194. "x=1 y=2 "
  195. );
  196. test_template(t, "for else empty",
  197. "{% for i in items %}{{ i }}{% else %}empty{% endfor %}",
  198. {{"items", json::array()}},
  199. "empty"
  200. );
  201. test_template(t, "nested for",
  202. "{% for i in a %}{% for j in b %}{{ i }}{{ j }}{% endfor %}{% endfor %}",
  203. {{"a", json::array({1, 2})}, {"b", json::array({"x", "y"})}},
  204. "1x1y2x2y"
  205. );
  206. test_template(t, "for with range",
  207. "{% for i in range(3) %}{{ i }}{% endfor %}",
  208. json::object(),
  209. "012"
  210. );
  211. }
  212. static void test_expressions(testing & t) {
  213. test_template(t, "simple variable",
  214. "{{ x }}",
  215. {{"x", 42}},
  216. "42"
  217. );
  218. test_template(t, "dot notation",
  219. "{{ user.name }}",
  220. {{"user", {{"name", "Bob"}}}},
  221. "Bob"
  222. );
  223. test_template(t, "negative float (not dot notation)",
  224. "{{ -1.0 }}",
  225. json::object(),
  226. "-1.0"
  227. );
  228. test_template(t, "bracket notation",
  229. "{{ user['name'] }}",
  230. {{"user", {{"name", "Bob"}}}},
  231. "Bob"
  232. );
  233. test_template(t, "array access",
  234. "{{ items[1] }}",
  235. {{"items", json::array({"a", "b", "c"})}},
  236. "b"
  237. );
  238. test_template(t, "arithmetic",
  239. "{{ (a + b) * c }}",
  240. {{"a", 2}, {"b", 3}, {"c", 4}},
  241. "20"
  242. );
  243. test_template(t, "string concat ~",
  244. "{{ 'hello' ~ ' ' ~ 'world' }}",
  245. json::object(),
  246. "hello world"
  247. );
  248. test_template(t, "ternary",
  249. "{{ 'yes' if cond else 'no' }}",
  250. {{"cond", true}},
  251. "yes"
  252. );
  253. }
  254. static void test_set_statement(testing & t) {
  255. test_template(t, "simple set",
  256. "{% set x = 5 %}{{ x }}",
  257. json::object(),
  258. "5"
  259. );
  260. test_template(t, "set with expression",
  261. "{% set x = a + b %}{{ x }}",
  262. {{"a", 10}, {"b", 20}},
  263. "30"
  264. );
  265. test_template(t, "set list",
  266. "{% set items = [1, 2, 3] %}{{ items|length }}",
  267. json::object(),
  268. "3"
  269. );
  270. test_template(t, "set dict",
  271. "{% set d = {'a': 1} %}{{ d.a }}",
  272. json::object(),
  273. "1"
  274. );
  275. }
  276. static void test_filters(testing & t) {
  277. test_template(t, "upper",
  278. "{{ 'hello'|upper }}",
  279. json::object(),
  280. "HELLO"
  281. );
  282. test_template(t, "lower",
  283. "{{ 'HELLO'|lower }}",
  284. json::object(),
  285. "hello"
  286. );
  287. test_template(t, "capitalize",
  288. "{{ 'heLlo World'|capitalize }}",
  289. json::object(),
  290. "Hello world"
  291. );
  292. test_template(t, "title",
  293. "{{ 'hello world'|title }}",
  294. json::object(),
  295. "Hello World"
  296. );
  297. test_template(t, "trim",
  298. "{{ ' \r\n\thello\t\n\r '|trim }}",
  299. json::object(),
  300. "hello"
  301. );
  302. test_template(t, "trim chars",
  303. "{{ 'xyxhelloxyx'|trim('xy') }}",
  304. json::object(),
  305. "hello"
  306. );
  307. test_template(t, "length string",
  308. "{{ 'hello'|length }}",
  309. json::object(),
  310. "5"
  311. );
  312. test_template(t, "replace",
  313. "{{ 'hello world'|replace('world', 'jinja') }}",
  314. json::object(),
  315. "hello jinja"
  316. );
  317. test_template(t, "length list",
  318. "{{ items|length }}",
  319. {{"items", json::array({1, 2, 3})}},
  320. "3"
  321. );
  322. test_template(t, "first",
  323. "{{ items|first }}",
  324. {{"items", json::array({10, 20, 30})}},
  325. "10"
  326. );
  327. test_template(t, "last",
  328. "{{ items|last }}",
  329. {{"items", json::array({10, 20, 30})}},
  330. "30"
  331. );
  332. test_template(t, "reverse",
  333. "{% for i in items|reverse %}{{ i }}{% endfor %}",
  334. {{"items", json::array({1, 2, 3})}},
  335. "321"
  336. );
  337. test_template(t, "sort",
  338. "{% for i in items|sort %}{{ i }}{% endfor %}",
  339. {{"items", json::array({3, 1, 2})}},
  340. "123"
  341. );
  342. test_template(t, "sort reverse",
  343. "{% for i in items|sort(true) %}{{ i }}{% endfor %}",
  344. {{"items", json::array({3, 1, 2})}},
  345. "321"
  346. );
  347. test_template(t, "sort with attribute",
  348. "{{ items|sort(attribute='name')|join(attribute='age') }}",
  349. {{"items", json::array({
  350. json({{"name", "c"}, {"age", 3}}),
  351. json({{"name", "a"}, {"age", 1}}),
  352. json({{"name", "b"}, {"age", 2}}),
  353. })}},
  354. "123"
  355. );
  356. test_template(t, "sort with numeric attribute",
  357. "{{ items|sort(attribute=0)|join(attribute=1) }}",
  358. {{"items", json::array({
  359. json::array({3, "z"}),
  360. json::array({1, "x"}),
  361. json::array({2, "y"}),
  362. })}},
  363. "xyz"
  364. );
  365. test_template(t, "join",
  366. "{{ items|join(', ') }}",
  367. {{"items", json::array({"a", "b", "c"})}},
  368. "a, b, c"
  369. );
  370. test_template(t, "join default separator",
  371. "{{ items|join }}",
  372. {{"items", json::array({"x", "y", "z"})}},
  373. "xyz"
  374. );
  375. test_template(t, "abs",
  376. "{{ -5|abs }}",
  377. json::object(),
  378. "5"
  379. );
  380. test_template(t, "int from string",
  381. "{{ '42'|int }}",
  382. json::object(),
  383. "42"
  384. );
  385. test_template(t, "int from string with default",
  386. "{{ ''|int(1) }}",
  387. json::object(),
  388. "1"
  389. );
  390. test_template(t, "int from string with base",
  391. "{{ '11'|int(base=2) }}",
  392. json::object(),
  393. "3"
  394. );
  395. test_template(t, "float from string",
  396. "{{ '3.14'|float }}",
  397. json::object(),
  398. "3.14"
  399. );
  400. test_template(t, "default with value",
  401. "{{ x|default('fallback') }}",
  402. {{"x", "actual"}},
  403. "actual"
  404. );
  405. test_template(t, "default without value",
  406. "{{ y|default('fallback') }}",
  407. json::object(),
  408. "fallback"
  409. );
  410. test_template(t, "default with falsy value",
  411. "{{ ''|default('fallback', true) }}",
  412. json::object(),
  413. "fallback"
  414. );
  415. test_template(t, "tojson ensure_ascii=true",
  416. "{{ data|tojson(ensure_ascii=true) }}",
  417. {{"data", "\u2713"}},
  418. "\"\\u2713\""
  419. );
  420. test_template(t, "tojson sort_keys=true",
  421. "{{ data|tojson(sort_keys=true) }}",
  422. {{"data", {{"b", 2}, {"a", 1}}}},
  423. "{\"a\": 1, \"b\": 2}"
  424. );
  425. test_template(t, "tojson",
  426. "{{ data|tojson }}",
  427. {{"data", {{"a", 1}, {"b", json::array({1, 2})}}}},
  428. "{\"a\": 1, \"b\": [1, 2]}"
  429. );
  430. test_template(t, "tojson indent=4",
  431. "{{ data|tojson(indent=4) }}",
  432. {{"data", {{"a", 1}, {"b", json::array({1, 2})}}}},
  433. "{\n \"a\": 1,\n \"b\": [\n 1,\n 2\n ]\n}"
  434. );
  435. test_template(t, "tojson separators=(',',':')",
  436. "{{ data|tojson(separators=(',',':')) }}",
  437. {{"data", {{"a", 1}, {"b", json::array({1, 2})}}}},
  438. "{\"a\":1,\"b\":[1,2]}"
  439. );
  440. test_template(t, "tojson separators=(',',': ') indent=2",
  441. "{{ data|tojson(separators=(',',': '), indent=2) }}",
  442. {{"data", {{"a", 1}, {"b", json::array({1, 2})}}}},
  443. "{\n \"a\": 1,\n \"b\": [\n 1,\n 2\n ]\n}"
  444. );
  445. test_template(t, "chained filters",
  446. "{{ ' HELLO '|trim|lower }}",
  447. json::object(),
  448. "hello"
  449. );
  450. }
  451. static void test_literals(testing & t) {
  452. test_template(t, "integer",
  453. "{{ 42 }}",
  454. json::object(),
  455. "42"
  456. );
  457. test_template(t, "float",
  458. "{{ 3.14 }}",
  459. json::object(),
  460. "3.14"
  461. );
  462. test_template(t, "string",
  463. "{{ 'hello' }}",
  464. json::object(),
  465. "hello"
  466. );
  467. test_template(t, "boolean true",
  468. "{{ true }}",
  469. json::object(),
  470. "True"
  471. );
  472. test_template(t, "boolean false",
  473. "{{ false }}",
  474. json::object(),
  475. "False"
  476. );
  477. test_template(t, "none",
  478. "{% if x is none %}null{% endif %}",
  479. {{"x", nullptr}},
  480. "null"
  481. );
  482. test_template(t, "list literal",
  483. "{% for i in [1, 2, 3] %}{{ i }}{% endfor %}",
  484. json::object(),
  485. "123"
  486. );
  487. test_template(t, "dict literal",
  488. "{% set d = {'a': 1} %}{{ d.a }}",
  489. json::object(),
  490. "1"
  491. );
  492. test_template(t, "integer|abs",
  493. "{{ -42 | abs }}",
  494. json::object(),
  495. "42"
  496. );
  497. test_template(t, "integer|float",
  498. "{{ 42 | float }}",
  499. json::object(),
  500. "42.0"
  501. );
  502. test_template(t, "integer|tojson",
  503. "{{ 42 | tojson }}",
  504. json::object(),
  505. "42"
  506. );
  507. test_template(t, "float|abs",
  508. "{{ -3.14 | abs }}",
  509. json::object(),
  510. "3.14"
  511. );
  512. test_template(t, "float|int",
  513. "{{ 3.14 | int }}",
  514. json::object(),
  515. "3"
  516. );
  517. test_template(t, "float|tojson",
  518. "{{ 3.14 | tojson }}",
  519. json::object(),
  520. "3.14"
  521. );
  522. test_template(t, "string|tojson",
  523. "{{ 'hello' | tojson }}",
  524. json::object(),
  525. "\"hello\""
  526. );
  527. test_template(t, "boolean|int",
  528. "{{ true | int }}",
  529. json::object(),
  530. "1"
  531. );
  532. test_template(t, "boolean|float",
  533. "{{ true | float }}",
  534. json::object(),
  535. "1.0"
  536. );
  537. test_template(t, "boolean|tojson",
  538. "{{ true | tojson }}",
  539. json::object(),
  540. "true"
  541. );
  542. }
  543. static void test_comments(testing & t) {
  544. test_template(t, "inline comment",
  545. "before{# comment #}after",
  546. json::object(),
  547. "beforeafter"
  548. );
  549. test_template(t, "comment ignores code",
  550. "{% set x = 1 %}{# {% set x = 999 %} #}{{ x }}",
  551. json::object(),
  552. "1"
  553. );
  554. }
  555. static void test_macros(testing & t) {
  556. test_template(t, "simple macro",
  557. "{% macro greet(name) %}Hello {{ name }}{% endmacro %}{{ greet('World') }}",
  558. json::object(),
  559. "Hello World"
  560. );
  561. test_template(t, "macro default arg",
  562. "{% macro greet(name='Guest') %}Hi {{ name }}{% endmacro %}{{ greet() }}",
  563. json::object(),
  564. "Hi Guest"
  565. );
  566. }
  567. static void test_namespace(testing & t) {
  568. test_template(t, "namespace counter",
  569. "{% set ns = namespace(count=0) %}{% for i in range(3) %}{% set ns.count = ns.count + 1 %}{% endfor %}{{ ns.count }}",
  570. json::object(),
  571. "3"
  572. );
  573. }
  574. static void test_tests(testing & t) {
  575. test_template(t, "is odd",
  576. "{% if 3 is odd %}yes{% endif %}",
  577. json::object(),
  578. "yes"
  579. );
  580. test_template(t, "is even",
  581. "{% if 4 is even %}yes{% endif %}",
  582. json::object(),
  583. "yes"
  584. );
  585. test_template(t, "is false",
  586. "{{ 'yes' if x is false }}",
  587. {{"x", false}},
  588. "yes"
  589. );
  590. test_template(t, "is true",
  591. "{{ 'yes' if x is true }}",
  592. {{"x", true}},
  593. "yes"
  594. );
  595. test_template(t, "string is false",
  596. "{{ 'yes' if x is false else 'no' }}",
  597. {{"x", ""}},
  598. "no"
  599. );
  600. test_template(t, "is divisibleby",
  601. "{{ 'yes' if x is divisibleby(2) }}",
  602. {{"x", 2}},
  603. "yes"
  604. );
  605. test_template(t, "is eq",
  606. "{{ 'yes' if 3 is eq(3) }}",
  607. json::object(),
  608. "yes"
  609. );
  610. test_template(t, "is not equalto",
  611. "{{ 'yes' if 3 is not equalto(4) }}",
  612. json::object(),
  613. "yes"
  614. );
  615. test_template(t, "is ge",
  616. "{{ 'yes' if 3 is ge(3) }}",
  617. json::object(),
  618. "yes"
  619. );
  620. test_template(t, "is gt",
  621. "{{ 'yes' if 3 is gt(2) }}",
  622. json::object(),
  623. "yes"
  624. );
  625. test_template(t, "is greaterthan",
  626. "{{ 'yes' if 3 is greaterthan(2) }}",
  627. json::object(),
  628. "yes"
  629. );
  630. test_template(t, "is lt",
  631. "{{ 'yes' if 2 is lt(3) }}",
  632. json::object(),
  633. "yes"
  634. );
  635. test_template(t, "is lessthan",
  636. "{{ 'yes' if 2 is lessthan(3) }}",
  637. json::object(),
  638. "yes"
  639. );
  640. test_template(t, "is ne",
  641. "{{ 'yes' if 2 is ne(3) }}",
  642. json::object(),
  643. "yes"
  644. );
  645. test_template(t, "is lower",
  646. "{{ 'yes' if 'lowercase' is lower }}",
  647. json::object(),
  648. "yes"
  649. );
  650. test_template(t, "is upper",
  651. "{{ 'yes' if 'UPPERCASE' is upper }}",
  652. json::object(),
  653. "yes"
  654. );
  655. test_template(t, "is sameas",
  656. "{{ 'yes' if x is sameas(false) }}",
  657. {{"x", false}},
  658. "yes"
  659. );
  660. test_template(t, "is boolean",
  661. "{{ 'yes' if x is boolean }}",
  662. {{"x", true}},
  663. "yes"
  664. );
  665. test_template(t, "is callable",
  666. "{{ 'yes' if ''.strip is callable }}",
  667. json::object(),
  668. "yes"
  669. );
  670. test_template(t, "is escaped",
  671. "{{ 'yes' if 'foo'|safe is escaped }}",
  672. json::object(),
  673. "yes"
  674. );
  675. test_template(t, "is filter",
  676. "{{ 'yes' if 'trim' is filter }}",
  677. json::object(),
  678. "yes"
  679. );
  680. test_template(t, "is float",
  681. "{{ 'yes' if x is float }}",
  682. {{"x", 1.1}},
  683. "yes"
  684. );
  685. test_template(t, "is integer",
  686. "{{ 'yes' if x is integer }}",
  687. {{"x", 1}},
  688. "yes"
  689. );
  690. test_template(t, "is sequence",
  691. "{{ 'yes' if x is sequence }}",
  692. {{"x", json::array({1, 2, 3})}},
  693. "yes"
  694. );
  695. test_template(t, "is test",
  696. "{{ 'yes' if 'sequence' is test }}",
  697. json::object(),
  698. "yes"
  699. );
  700. test_template(t, "is undefined",
  701. "{{ 'yes' if x is undefined }}",
  702. json::object(),
  703. "yes"
  704. );
  705. test_template(t, "is none",
  706. "{% if x is none %}yes{% endif %}",
  707. {{"x", nullptr}},
  708. "yes"
  709. );
  710. test_template(t, "is string",
  711. "{% if x is string %}yes{% endif %}",
  712. {{"x", "hello"}},
  713. "yes"
  714. );
  715. test_template(t, "is number",
  716. "{% if x is number %}yes{% endif %}",
  717. {{"x", 42}},
  718. "yes"
  719. );
  720. test_template(t, "is iterable",
  721. "{% if x is iterable %}yes{% endif %}",
  722. {{"x", json::array({1, 2, 3})}},
  723. "yes"
  724. );
  725. test_template(t, "is mapping",
  726. "{% if x is mapping %}yes{% endif %}",
  727. {{"x", {{"a", 1}}}},
  728. "yes"
  729. );
  730. }
  731. static void test_string_methods(testing & t) {
  732. test_template(t, "string.upper()",
  733. "{{ s.upper() }}",
  734. {{"s", "hello"}},
  735. "HELLO"
  736. );
  737. test_template(t, "string.lower()",
  738. "{{ s.lower() }}",
  739. {{"s", "HELLO"}},
  740. "hello"
  741. );
  742. test_template(t, "string.strip()",
  743. "[{{ s.strip() }}]",
  744. {{"s", " hello "}},
  745. "[hello]"
  746. );
  747. test_template(t, "string.lstrip()",
  748. "[{{ s.lstrip() }}]",
  749. {{"s", " hello"}},
  750. "[hello]"
  751. );
  752. test_template(t, "string.rstrip()",
  753. "[{{ s.rstrip() }}]",
  754. {{"s", "hello "}},
  755. "[hello]"
  756. );
  757. test_template(t, "string.title()",
  758. "{{ s.title() }}",
  759. {{"s", "hello world"}},
  760. "Hello World"
  761. );
  762. test_template(t, "string.capitalize()",
  763. "{{ s.capitalize() }}",
  764. {{"s", "heLlo World"}},
  765. "Hello world"
  766. );
  767. test_template(t, "string.startswith() true",
  768. "{% if s.startswith('hel') %}yes{% endif %}",
  769. {{"s", "hello"}},
  770. "yes"
  771. );
  772. test_template(t, "string.startswith() false",
  773. "{% if s.startswith('xyz') %}yes{% else %}no{% endif %}",
  774. {{"s", "hello"}},
  775. "no"
  776. );
  777. test_template(t, "string.endswith() true",
  778. "{% if s.endswith('lo') %}yes{% endif %}",
  779. {{"s", "hello"}},
  780. "yes"
  781. );
  782. test_template(t, "string.endswith() false",
  783. "{% if s.endswith('xyz') %}yes{% else %}no{% endif %}",
  784. {{"s", "hello"}},
  785. "no"
  786. );
  787. test_template(t, "string.split() with sep",
  788. "{{ s.split(',')|join('-') }}",
  789. {{"s", "a,b,c"}},
  790. "a-b-c"
  791. );
  792. test_template(t, "string.split() with maxsplit",
  793. "{{ s.split(',', 1)|join('-') }}",
  794. {{"s", "a,b,c"}},
  795. "a-b,c"
  796. );
  797. test_template(t, "string.rsplit() with sep",
  798. "{{ s.rsplit(',')|join('-') }}",
  799. {{"s", "a,b,c"}},
  800. "a-b-c"
  801. );
  802. test_template(t, "string.rsplit() with maxsplit",
  803. "{{ s.rsplit(',', 1)|join('-') }}",
  804. {{"s", "a,b,c"}},
  805. "a,b-c"
  806. );
  807. test_template(t, "string.replace() basic",
  808. "{{ s.replace('world', 'jinja') }}",
  809. {{"s", "hello world"}},
  810. "hello jinja"
  811. );
  812. test_template(t, "string.replace() with count",
  813. "{{ s.replace('a', 'X', 2) }}",
  814. {{"s", "banana"}},
  815. "bXnXna"
  816. );
  817. }
  818. static void test_array_methods(testing & t) {
  819. test_template(t, "array|selectattr by attribute",
  820. "{% for item in items|selectattr('active') %}{{ item.name }} {% endfor %}",
  821. {{"items", json::array({
  822. {{"name", "a"}, {"active", true}},
  823. {{"name", "b"}, {"active", false}},
  824. {{"name", "c"}, {"active", true}}
  825. })}},
  826. "a c "
  827. );
  828. test_template(t, "array|selectattr with operator",
  829. "{% for item in items|selectattr('value', 'equalto', 5) %}{{ item.name }} {% endfor %}",
  830. {{"items", json::array({
  831. {{"name", "a"}, {"value", 3}},
  832. {{"name", "b"}, {"value", 5}},
  833. {{"name", "c"}, {"value", 5}}
  834. })}},
  835. "b c "
  836. );
  837. test_template(t, "array|tojson",
  838. "{{ arr|tojson }}",
  839. {{"arr", json::array({1, 2, 3})}},
  840. "[1, 2, 3]"
  841. );
  842. test_template(t, "array|tojson with strings",
  843. "{{ arr|tojson }}",
  844. {{"arr", json::array({"a", "b", "c"})}},
  845. "[\"a\", \"b\", \"c\"]"
  846. );
  847. test_template(t, "array|tojson nested",
  848. "{{ arr|tojson }}",
  849. {{"arr", json::array({json::array({1, 2}), json::array({3, 4})})}},
  850. "[[1, 2], [3, 4]]"
  851. );
  852. test_template(t, "array|last",
  853. "{{ arr|last }}",
  854. {{"arr", json::array({10, 20, 30})}},
  855. "30"
  856. );
  857. test_template(t, "array|last single element",
  858. "{{ arr|last }}",
  859. {{"arr", json::array({42})}},
  860. "42"
  861. );
  862. test_template(t, "array|join with separator",
  863. "{{ arr|join(', ') }}",
  864. {{"arr", json::array({"a", "b", "c"})}},
  865. "a, b, c"
  866. );
  867. test_template(t, "array|join with custom separator",
  868. "{{ arr|join(' | ') }}",
  869. {{"arr", json::array({1, 2, 3})}},
  870. "1 | 2 | 3"
  871. );
  872. test_template(t, "array|join default separator",
  873. "{{ arr|join }}",
  874. {{"arr", json::array({"x", "y", "z"})}},
  875. "xyz"
  876. );
  877. test_template(t, "array|join attribute",
  878. "{{ arr|join(attribute='age') }}",
  879. {{"arr", json::array({
  880. json({{"name", "a"}, {"age", 1}}),
  881. json({{"name", "b"}, {"age", 2}}),
  882. json({{"name", "c"}, {"age", 3}}),
  883. })}},
  884. "123"
  885. );
  886. test_template(t, "array|join numeric attribute",
  887. "{{ arr|join(attribute=-1) }}",
  888. {{"arr", json::array({json::array({1}), json::array({2}), json::array({3})})}},
  889. "123"
  890. );
  891. test_template(t, "array.pop() last",
  892. "{{ arr.pop() }}-{{ arr|join(',') }}",
  893. {{"arr", json::array({"a", "b", "c"})}},
  894. "c-a,b"
  895. );
  896. test_template(t, "array.pop() with index",
  897. "{{ arr.pop(0) }}-{{ arr|join(',') }}",
  898. {{"arr", json::array({"a", "b", "c"})}},
  899. "a-b,c"
  900. );
  901. test_template(t, "array.append()",
  902. "{% set _ = arr.append('d') %}{{ arr|join(',') }}",
  903. {{"arr", json::array({"a", "b", "c"})}},
  904. "a,b,c,d"
  905. );
  906. test_template(t, "array|map with attribute",
  907. "{% for v in arr|map(attribute='age') %}{{ v }} {% endfor %}",
  908. {{"arr", json::array({
  909. json({{"name", "a"}, {"age", 1}}),
  910. json({{"name", "b"}, {"age", 2}}),
  911. json({{"name", "c"}, {"age", 3}}),
  912. })}},
  913. "1 2 3 "
  914. );
  915. test_template(t, "array|map with attribute default",
  916. "{% for v in arr|map(attribute='age', default=3) %}{{ v }} {% endfor %}",
  917. {{"arr", json::array({
  918. json({{"name", "a"}, {"age", 1}}),
  919. json({{"name", "b"}, {"age", 2}}),
  920. json({{"name", "c"}}),
  921. })}},
  922. "1 2 3 "
  923. );
  924. test_template(t, "array|map without attribute default",
  925. "{% for v in arr|map(attribute='age') %}{{ v }} {% endfor %}",
  926. {{"arr", json::array({
  927. json({{"name", "a"}, {"age", 1}}),
  928. json({{"name", "b"}, {"age", 2}}),
  929. json({{"name", "c"}}),
  930. })}},
  931. "1 2 "
  932. );
  933. test_template(t, "array|map with numeric attribute",
  934. "{% for v in arr|map(attribute=0) %}{{ v }} {% endfor %}",
  935. {{"arr", json::array({
  936. json::array({10, "x"}),
  937. json::array({20, "y"}),
  938. json::array({30, "z"}),
  939. })}},
  940. "10 20 30 "
  941. );
  942. test_template(t, "array|map with negative attribute",
  943. "{% for v in arr|map(attribute=-1) %}{{ v }} {% endfor %}",
  944. {{"arr", json::array({
  945. json::array({10, "x"}),
  946. json::array({20, "y"}),
  947. json::array({30, "z"}),
  948. })}},
  949. "x y z "
  950. );
  951. test_template(t, "array|map with filter",
  952. "{{ arr|map('int')|sum }}",
  953. {{"arr", json::array({"1", "2", "3"})}},
  954. "6"
  955. );
  956. // not used by any chat templates
  957. // test_template(t, "array.insert()",
  958. // "{% set _ = arr.insert(1, 'x') %}{{ arr|join(',') }}",
  959. // {{"arr", json::array({"a", "b", "c"})}},
  960. // "a,x,b,c"
  961. // );
  962. }
  963. static void test_object_methods(testing & t) {
  964. test_template(t, "object.get() existing key",
  965. "{{ obj.get('a') }}",
  966. {{"obj", {{"a", 1}, {"b", 2}}}},
  967. "1"
  968. );
  969. test_template(t, "object.get() missing key",
  970. "[{{ obj.get('c') is none }}]",
  971. {{"obj", {{"a", 1}}}},
  972. "[True]"
  973. );
  974. test_template(t, "object.get() missing key with default",
  975. "{{ obj.get('c', 'default') }}",
  976. {{"obj", {{"a", 1}}}},
  977. "default"
  978. );
  979. test_template(t, "object.items()",
  980. "{% for k, v in obj.items() %}{{ k }}={{ v }} {% endfor %}",
  981. {{"obj", {{"x", 1}, {"y", 2}}}},
  982. "x=1 y=2 "
  983. );
  984. test_template(t, "object.keys()",
  985. "{% for k in obj.keys() %}{{ k }} {% endfor %}",
  986. {{"obj", {{"a", 1}, {"b", 2}}}},
  987. "a b "
  988. );
  989. test_template(t, "object.values()",
  990. "{% for v in obj.values() %}{{ v }} {% endfor %}",
  991. {{"obj", {{"a", 1}, {"b", 2}}}},
  992. "1 2 "
  993. );
  994. test_template(t, "dictsort ascending by key",
  995. "{% for k, v in obj|dictsort %}{{ k }}={{ v }} {% endfor %}",
  996. {{"obj", {{"z", 2}, {"a", 3}, {"m", 1}}}},
  997. "a=3 m=1 z=2 "
  998. );
  999. test_template(t, "dictsort descending by key",
  1000. "{% for k, v in obj|dictsort(reverse=true) %}{{ k }}={{ v }} {% endfor %}",
  1001. {{"obj", {{"a", 1}, {"b", 2}, {"c", 3}}}},
  1002. "c=3 b=2 a=1 "
  1003. );
  1004. test_template(t, "dictsort by value",
  1005. "{% for k, v in obj|dictsort(by='value') %}{{ k }}={{ v }} {% endfor %}",
  1006. {{"obj", {{"a", 3}, {"b", 1}, {"c", 2}}}},
  1007. "b=1 c=2 a=3 "
  1008. );
  1009. test_template(t, "dictsort case sensitive",
  1010. "{% for k, v in obj|dictsort(case_sensitive=true) %}{{ k }}={{ v }} {% endfor %}",
  1011. {{"obj", {{"a", 1}, {"A", 1}, {"b", 2}, {"B", 2}, {"c", 3}}}},
  1012. "A=1 B=2 a=1 b=2 c=3 "
  1013. );
  1014. test_template(t, "object|tojson",
  1015. "{{ obj|tojson }}",
  1016. {{"obj", {{"name", "test"}, {"value", 42}}}},
  1017. "{\"name\": \"test\", \"value\": 42}"
  1018. );
  1019. test_template(t, "nested object|tojson",
  1020. "{{ obj|tojson }}",
  1021. {{"obj", {{"outer", {{"inner", "value"}}}}}},
  1022. "{\"outer\": {\"inner\": \"value\"}}"
  1023. );
  1024. test_template(t, "array in object|tojson",
  1025. "{{ obj|tojson }}",
  1026. {{"obj", {{"items", json::array({1, 2, 3})}}}},
  1027. "{\"items\": [1, 2, 3]}"
  1028. );
  1029. test_template(t, "object attribute and key access",
  1030. "{{ obj.keys()|join(',') }} vs {{ obj['keys'] }} vs {{ obj.test }}",
  1031. {{"obj", {{"keys", "value"}, {"test", "attr_value"}}}},
  1032. "keys,test vs value vs attr_value"
  1033. );
  1034. test_template(t, "env should not have object methods",
  1035. "{{ keys is undefined }} {{ obj.keys is defined }}",
  1036. {{"obj", {{"a", "b"}}}},
  1037. "True True"
  1038. );
  1039. }
  1040. static void test_template_cpp(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect) {
  1041. t.test(name, [&tmpl, &vars, &expect](testing & t) {
  1042. jinja::lexer lexer;
  1043. auto lexer_res = lexer.tokenize(tmpl);
  1044. jinja::program ast = jinja::parse_from_tokens(lexer_res);
  1045. jinja::context ctx(tmpl);
  1046. jinja::global_from_json(ctx, vars, true);
  1047. jinja::runtime runtime(ctx);
  1048. try {
  1049. const jinja::value results = runtime.execute(ast);
  1050. auto parts = runtime.gather_string_parts(results);
  1051. std::string rendered;
  1052. for (const auto & part : parts->as_string().parts) {
  1053. rendered += part.val;
  1054. }
  1055. if (!t.assert_true("Template render mismatch", expect == rendered)) {
  1056. t.log("Template: " + json(tmpl).dump());
  1057. t.log("Expected: " + json(expect).dump());
  1058. t.log("Actual : " + json(rendered).dump());
  1059. }
  1060. } catch (const jinja::not_implemented_exception & e) {
  1061. // TODO @ngxson : remove this when the test framework supports skipping tests
  1062. t.log("Skipped: " + std::string(e.what()));
  1063. }
  1064. });
  1065. }
  1066. // keep this in-sync with https://github.com/huggingface/transformers/blob/main/src/transformers/utils/chat_template_utils.py
  1067. // note: we use SandboxedEnvironment instead of ImmutableSandboxedEnvironment to allow usage of in-place array methods like append() and pop()
  1068. static std::string py_script = R"(
  1069. import jinja2
  1070. import jinja2.ext as jinja2_ext
  1071. import json
  1072. import sys
  1073. from datetime import datetime
  1074. from jinja2.sandbox import SandboxedEnvironment
  1075. tmpl = json.loads(sys.argv[1])
  1076. vars_json = json.loads(sys.argv[2])
  1077. env = SandboxedEnvironment(
  1078. trim_blocks=True,
  1079. lstrip_blocks=True,
  1080. extensions=[jinja2_ext.loopcontrols],
  1081. )
  1082. def raise_exception(message):
  1083. raise jinja2.exceptions.TemplateError(message)
  1084. env.filters["tojson"] = lambda x, ensure_ascii=False, indent=None, separators=None, sort_keys=False: json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys)
  1085. env.globals["strftime_now"] = lambda format: datetime.now().strftime(format)
  1086. env.globals["raise_exception"] = raise_exception
  1087. template = env.from_string(tmpl)
  1088. result = template.render(**vars_json)
  1089. print(result, end='')
  1090. )";
  1091. static void test_template_py(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect) {
  1092. t.test(name, [&tmpl, &vars, &expect](testing & t) {
  1093. // Prepare arguments
  1094. std::string tmpl_json = json(tmpl).dump();
  1095. std::string vars_json = vars.dump();
  1096. #ifdef _WIN32
  1097. const char * python_executable = "python.exe";
  1098. #else
  1099. const char * python_executable = "python3";
  1100. #endif
  1101. const char * command_line[] = {python_executable, "-c", py_script.c_str(), tmpl_json.c_str(), vars_json.c_str(), NULL};
  1102. struct subprocess_s subprocess;
  1103. int options = subprocess_option_combined_stdout_stderr
  1104. | subprocess_option_no_window
  1105. | subprocess_option_inherit_environment
  1106. | subprocess_option_search_user_path;
  1107. int result = subprocess_create(command_line, options, &subprocess);
  1108. if (result != 0) {
  1109. t.log("Failed to create subprocess, error code: " + std::to_string(result));
  1110. t.assert_true("subprocess creation", false);
  1111. return;
  1112. }
  1113. // Read output
  1114. std::string output;
  1115. char buffer[1024];
  1116. FILE * p_stdout = subprocess_stdout(&subprocess);
  1117. while (fgets(buffer, sizeof(buffer), p_stdout)) {
  1118. output += buffer;
  1119. }
  1120. int process_return;
  1121. subprocess_join(&subprocess, &process_return);
  1122. subprocess_destroy(&subprocess);
  1123. if (process_return != 0) {
  1124. t.log("Python script failed with exit code: " + std::to_string(process_return));
  1125. t.log("Output: " + output);
  1126. t.assert_true("python execution", false);
  1127. return;
  1128. }
  1129. if (!t.assert_true("Template render mismatch", expect == output)) {
  1130. t.log("Template: " + json(tmpl).dump());
  1131. t.log("Expected: " + json(expect).dump());
  1132. t.log("Python : " + json(output).dump());
  1133. }
  1134. });
  1135. }
  1136. static void test_template(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect) {
  1137. if (g_python_mode) {
  1138. test_template_py(t, name, tmpl, vars, expect);
  1139. } else {
  1140. test_template_cpp(t, name, tmpl, vars, expect);
  1141. }
  1142. }
  1143. //
  1144. // fuzz tests to ensure no crashes occur on malformed inputs
  1145. //
  1146. constexpr int JINJA_FUZZ_ITERATIONS = 100;
  1147. // Helper to generate random string
  1148. static std::string random_string(std::mt19937 & rng, size_t max_len) {
  1149. static const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
  1150. std::uniform_int_distribution<size_t> len_dist(0, max_len);
  1151. std::uniform_int_distribution<size_t> char_dist(0, sizeof(charset) - 2);
  1152. size_t len = len_dist(rng);
  1153. std::string result;
  1154. result.reserve(len);
  1155. for (size_t i = 0; i < len; ++i) {
  1156. result += charset[char_dist(rng)];
  1157. }
  1158. return result;
  1159. }
  1160. // Helper to execute a fuzz test case - returns true if no crash occurred
  1161. static bool fuzz_test_template(const std::string & tmpl, const json & vars) {
  1162. try {
  1163. // printf("Fuzz testing template: %s\n", tmpl.c_str());
  1164. jinja::lexer lexer;
  1165. auto lexer_res = lexer.tokenize(tmpl);
  1166. jinja::program ast = jinja::parse_from_tokens(lexer_res);
  1167. jinja::context ctx(tmpl);
  1168. jinja::global_from_json(ctx, vars, true);
  1169. jinja::runtime runtime(ctx);
  1170. const jinja::value results = runtime.execute(ast);
  1171. runtime.gather_string_parts(results);
  1172. return true; // success
  1173. } catch (const std::exception &) {
  1174. return true; // exception is acceptable, not a crash
  1175. } catch (...) {
  1176. return true; // any exception is acceptable, not a crash
  1177. }
  1178. }
  1179. static void test_fuzzing(testing & t) {
  1180. const int num_iterations = JINJA_FUZZ_ITERATIONS;
  1181. const unsigned int seed = 42; // fixed seed for reproducibility
  1182. std::mt19937 rng(seed);
  1183. // Distribution helpers
  1184. std::uniform_int_distribution<int> choice_dist(0, 100);
  1185. std::uniform_int_distribution<int> int_dist(-1000, 1000);
  1186. std::uniform_int_distribution<size_t> idx_dist(0, 1000);
  1187. // Template fragments for fuzzing
  1188. const std::vector<std::string> var_names = {
  1189. "x", "y", "z", "arr", "obj", "items", "foo", "bar", "undefined_var",
  1190. "none", "true", "false", "None", "True", "False"
  1191. };
  1192. const std::vector<std::string> filters = {
  1193. "length", "first", "last", "reverse", "sort", "unique", "join", "upper", "lower",
  1194. "trim", "default", "tojson", "string", "int", "float", "abs", "list", "dictsort"
  1195. };
  1196. const std::vector<std::string> builtins = {
  1197. "range", "len", "dict", "list", "join", "str", "int", "float", "namespace"
  1198. };
  1199. t.test("out of bound array access", [&](testing & t) {
  1200. for (int i = 0; i < num_iterations; ++i) {
  1201. int idx = int_dist(rng);
  1202. std::string tmpl = "{{ arr[" + std::to_string(idx) + "] }}";
  1203. json vars = {{"arr", json::array({1, 2, 3})}};
  1204. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1205. }
  1206. });
  1207. t.test("non-existing variables", [&](testing & t) {
  1208. for (int i = 0; i < num_iterations; ++i) {
  1209. std::string var = random_string(rng, 20);
  1210. std::string tmpl = "{{ " + var + " }}";
  1211. json vars = json::object(); // empty context
  1212. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1213. }
  1214. });
  1215. t.test("non-existing nested attributes", [&](testing & t) {
  1216. for (int i = 0; i < num_iterations; ++i) {
  1217. std::string var1 = var_names[choice_dist(rng) % var_names.size()];
  1218. std::string var2 = random_string(rng, 10);
  1219. std::string var3 = random_string(rng, 10);
  1220. std::string tmpl = "{{ " + var1 + "." + var2 + "." + var3 + " }}";
  1221. json vars = {{var1, {{"other", 123}}}};
  1222. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1223. }
  1224. });
  1225. t.test("invalid filter arguments", [&](testing & t) {
  1226. for (int i = 0; i < num_iterations; ++i) {
  1227. std::string filter = filters[choice_dist(rng) % filters.size()];
  1228. int val = int_dist(rng);
  1229. std::string tmpl = "{{ " + std::to_string(val) + " | " + filter + " }}";
  1230. json vars = json::object();
  1231. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1232. }
  1233. });
  1234. t.test("chained filters on various types", [&](testing & t) {
  1235. for (int i = 0; i < num_iterations; ++i) {
  1236. std::string f1 = filters[choice_dist(rng) % filters.size()];
  1237. std::string f2 = filters[choice_dist(rng) % filters.size()];
  1238. std::string var = var_names[choice_dist(rng) % var_names.size()];
  1239. std::string tmpl = "{{ " + var + " | " + f1 + " | " + f2 + " }}";
  1240. json vars = {
  1241. {"x", 42},
  1242. {"y", "hello"},
  1243. {"arr", json::array({1, 2, 3})},
  1244. {"obj", {{"a", 1}, {"b", 2}}},
  1245. {"items", json::array({"a", "b", "c"})}
  1246. };
  1247. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1248. }
  1249. });
  1250. t.test("invalid builtin calls", [&](testing & t) {
  1251. for (int i = 0; i < num_iterations; ++i) {
  1252. std::string builtin = builtins[choice_dist(rng) % builtins.size()];
  1253. std::string arg;
  1254. int arg_type = choice_dist(rng) % 4;
  1255. switch (arg_type) {
  1256. case 0: arg = "\"not a number\""; break;
  1257. case 1: arg = "none"; break;
  1258. case 2: arg = std::to_string(int_dist(rng)); break;
  1259. case 3: arg = "[]"; break;
  1260. }
  1261. std::string tmpl = "{{ " + builtin + "(" + arg + ") }}";
  1262. json vars = json::object();
  1263. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1264. }
  1265. });
  1266. t.test("macro edge cases", [&](testing & t) {
  1267. // Macro with no args called with args
  1268. t.assert_true("macro no args with args", fuzz_test_template(
  1269. "{% macro foo() %}hello{% endmacro %}{{ foo(1, 2, 3) }}",
  1270. json::object()
  1271. ));
  1272. // Macro with args called with no args
  1273. t.assert_true("macro with args no args", fuzz_test_template(
  1274. "{% macro foo(a, b, c) %}{{ a }}{{ b }}{{ c }}{% endmacro %}{{ foo() }}",
  1275. json::object()
  1276. ));
  1277. // Recursive macro reference
  1278. t.assert_true("recursive macro", fuzz_test_template(
  1279. "{% macro foo(n) %}{% if n > 0 %}{{ foo(n - 1) }}{% endif %}{% endmacro %}{{ foo(5) }}",
  1280. json::object()
  1281. ));
  1282. // Nested macro definitions
  1283. for (int i = 0; i < num_iterations / 10; ++i) {
  1284. std::string tmpl = "{% macro outer() %}{% macro inner() %}x{% endmacro %}{{ inner() }}{% endmacro %}{{ outer() }}";
  1285. t.assert_true("nested macro", fuzz_test_template(tmpl, json::object()));
  1286. }
  1287. });
  1288. t.test("empty and none operations", [&](testing & t) {
  1289. const std::vector<std::string> empty_tests = {
  1290. "{{ \"\" | first }}",
  1291. "{{ \"\" | last }}",
  1292. "{{ [] | first }}",
  1293. "{{ [] | last }}",
  1294. "{{ none.attr }}",
  1295. "{{ none | length }}",
  1296. "{{ none | default('fallback') }}",
  1297. "{{ {} | first }}",
  1298. "{{ {} | dictsort }}",
  1299. };
  1300. for (const auto & tmpl : empty_tests) {
  1301. t.assert_true("empty/none: " + tmpl, fuzz_test_template(tmpl, json::object()));
  1302. }
  1303. });
  1304. t.test("arithmetic edge cases", [&](testing & t) {
  1305. const std::vector<std::string> arith_tests = {
  1306. "{{ 1 / 0 }}",
  1307. "{{ 1 // 0 }}",
  1308. "{{ 1 % 0 }}",
  1309. "{{ 999999999999999999 * 999999999999999999 }}",
  1310. "{{ -999999999999999999 - 999999999999999999 }}",
  1311. "{{ 1.0 / 0.0 }}",
  1312. "{{ 0.0 / 0.0 }}",
  1313. };
  1314. for (const auto & tmpl : arith_tests) {
  1315. t.assert_true("arith: " + tmpl, fuzz_test_template(tmpl, json::object()));
  1316. }
  1317. });
  1318. t.test("deeply nested structures", [&](testing & t) {
  1319. // Deeply nested loops
  1320. for (int depth = 1; depth <= 10; ++depth) {
  1321. std::string tmpl;
  1322. for (int d = 0; d < depth; ++d) {
  1323. tmpl += "{% for i" + std::to_string(d) + " in arr %}";
  1324. }
  1325. tmpl += "x";
  1326. for (int d = 0; d < depth; ++d) {
  1327. tmpl += "{% endfor %}";
  1328. }
  1329. json vars = {{"arr", json::array({1, 2})}};
  1330. t.assert_true("nested loops depth " + std::to_string(depth), fuzz_test_template(tmpl, vars));
  1331. }
  1332. // Deeply nested conditionals
  1333. for (int depth = 1; depth <= 10; ++depth) {
  1334. std::string tmpl;
  1335. for (int d = 0; d < depth; ++d) {
  1336. tmpl += "{% if true %}";
  1337. }
  1338. tmpl += "x";
  1339. for (int d = 0; d < depth; ++d) {
  1340. tmpl += "{% endif %}";
  1341. }
  1342. t.assert_true("nested ifs depth " + std::to_string(depth), fuzz_test_template(tmpl, json::object()));
  1343. }
  1344. });
  1345. t.test("special characters in strings", [&](testing & t) {
  1346. const std::vector<std::string> special_tests = {
  1347. "{{ \"}{%\" }}",
  1348. "{{ \"}}{{\" }}",
  1349. "{{ \"{%%}\" }}",
  1350. "{{ \"\\n\\t\\r\" }}",
  1351. "{{ \"'\\\"'\" }}",
  1352. "{{ \"hello\\x00world\" }}",
  1353. };
  1354. for (const auto & tmpl : special_tests) {
  1355. t.assert_true("special: " + tmpl, fuzz_test_template(tmpl, json::object()));
  1356. }
  1357. });
  1358. t.test("random template generation", [&](testing & t) {
  1359. const std::vector<std::string> fragments = {
  1360. "{{ x }}", "{{ y }}", "{{ arr }}", "{{ obj }}",
  1361. "{% if true %}a{% endif %}",
  1362. "{% if false %}b{% else %}c{% endif %}",
  1363. "{% for i in arr %}{{ i }}{% endfor %}",
  1364. "{{ x | length }}", "{{ x | first }}", "{{ x | default(0) }}",
  1365. "{{ x + y }}", "{{ x - y }}", "{{ x * y }}",
  1366. "{{ x == y }}", "{{ x != y }}", "{{ x > y }}",
  1367. "{{ range(3) }}", "{{ \"hello\" | upper }}",
  1368. "text", " ", "\n",
  1369. };
  1370. for (int i = 0; i < num_iterations; ++i) {
  1371. std::string tmpl;
  1372. int num_frags = choice_dist(rng) % 10 + 1;
  1373. for (int f = 0; f < num_frags; ++f) {
  1374. tmpl += fragments[choice_dist(rng) % fragments.size()];
  1375. }
  1376. json vars = {
  1377. {"x", int_dist(rng)},
  1378. {"y", int_dist(rng)},
  1379. {"arr", json::array({1, 2, 3})},
  1380. {"obj", {{"a", 1}, {"b", 2}}}
  1381. };
  1382. t.assert_true("random template #" + std::to_string(i), fuzz_test_template(tmpl, vars));
  1383. }
  1384. });
  1385. t.test("malformed templates (should error, not crash)", [&](testing & t) {
  1386. const std::vector<std::string> malformed = {
  1387. "{{ x",
  1388. "{% if %}",
  1389. "{% for %}",
  1390. "{% for x in %}",
  1391. "{% endfor %}",
  1392. "{% endif %}",
  1393. "{{ | filter }}",
  1394. "{% if x %}", // unclosed
  1395. "{% for i in x %}", // unclosed
  1396. "{{ x | }}",
  1397. "{% macro %}{% endmacro %}",
  1398. "{{{{",
  1399. "}}}}",
  1400. "{%%}",
  1401. "{% set %}",
  1402. "{% set x %}",
  1403. };
  1404. for (const auto & tmpl : malformed) {
  1405. t.assert_true("malformed: " + tmpl, fuzz_test_template(tmpl, json::object()));
  1406. }
  1407. });
  1408. t.test("type coercion edge cases", [&](testing & t) {
  1409. for (int i = 0; i < num_iterations; ++i) {
  1410. int op_choice = choice_dist(rng) % 6;
  1411. std::string op;
  1412. switch (op_choice) {
  1413. case 0: op = "+"; break;
  1414. case 1: op = "-"; break;
  1415. case 2: op = "*"; break;
  1416. case 3: op = "/"; break;
  1417. case 4: op = "=="; break;
  1418. case 5: op = "~"; break; // string concat
  1419. }
  1420. std::string left_var = var_names[choice_dist(rng) % var_names.size()];
  1421. std::string right_var = var_names[choice_dist(rng) % var_names.size()];
  1422. std::string tmpl = "{{ " + left_var + " " + op + " " + right_var + " }}";
  1423. json vars = {
  1424. {"x", 42},
  1425. {"y", "hello"},
  1426. {"z", 3.14},
  1427. {"arr", json::array({1, 2, 3})},
  1428. {"obj", {{"a", 1}}},
  1429. {"items", json::array()},
  1430. {"foo", nullptr},
  1431. {"bar", true}
  1432. };
  1433. t.assert_true("type coercion: " + tmpl, fuzz_test_template(tmpl, vars));
  1434. }
  1435. });
  1436. t.test("fuzz builtin functions", [&](testing & t) {
  1437. // pair of (type_name, builtin_name)
  1438. std::vector<std::pair<std::string, std::string>> builtins;
  1439. auto add_fns = [&](std::string type_name, const jinja::func_builtins & added) {
  1440. for (const auto & it : added) {
  1441. builtins.push_back({type_name, it.first});
  1442. }
  1443. };
  1444. add_fns("global", jinja::global_builtins());
  1445. add_fns("int", jinja::value_int_t(0).get_builtins());
  1446. add_fns("float", jinja::value_float_t(0.0f).get_builtins());
  1447. add_fns("string", jinja::value_string_t().get_builtins());
  1448. add_fns("array", jinja::value_array_t().get_builtins());
  1449. add_fns("object", jinja::value_object_t().get_builtins());
  1450. const int max_args = 5;
  1451. const std::vector<std::string> kwarg_names = {
  1452. "base", "attribute", "default", "reverse", "case_sensitive", "by", "safe", "chars", "separators", "sort_keys", "indent", "ensure_ascii",
  1453. };
  1454. // Generate random argument values
  1455. auto gen_random_arg = [&]() -> std::string {
  1456. int type = choice_dist(rng) % 8;
  1457. switch (type) {
  1458. case 0: return std::to_string(int_dist(rng)); // int
  1459. case 1: return std::to_string(int_dist(rng)) + ".5"; // float
  1460. case 2: return "\"" + random_string(rng, 10) + "\""; // string
  1461. case 3: return "true"; // bool true
  1462. case 4: return "false"; // bool false
  1463. case 5: return "none"; // none
  1464. case 6: return "[1, 2, 3]"; // array
  1465. case 7: return "{\"a\": 1}"; // object
  1466. default: return "0";
  1467. }
  1468. };
  1469. for (int i = 0; i < num_iterations; ++i) {
  1470. // Pick a random builtin
  1471. auto & [type_name, fn_name] = builtins[choice_dist(rng) % builtins.size()];
  1472. // Generate random number of args
  1473. int num_args = choice_dist(rng) % (max_args + 1);
  1474. std::string args_str;
  1475. for (int a = 0; a < num_args; ++a) {
  1476. if (a > 0) args_str += ", ";
  1477. // Sometimes use keyword args
  1478. if (choice_dist(rng) % 3 == 0 && !kwarg_names.empty()) {
  1479. std::string kwarg = kwarg_names[choice_dist(rng) % kwarg_names.size()];
  1480. args_str += kwarg + "=" + gen_random_arg();
  1481. } else {
  1482. args_str += gen_random_arg();
  1483. }
  1484. }
  1485. std::string tmpl;
  1486. if (type_name == "global") {
  1487. // Global function call
  1488. tmpl = "{{ " + fn_name + "(" + args_str + ") }}";
  1489. } else {
  1490. // Method call on a value
  1491. std::string base_val;
  1492. if (type_name == "int") {
  1493. base_val = std::to_string(int_dist(rng));
  1494. } else if (type_name == "float") {
  1495. base_val = std::to_string(int_dist(rng)) + ".5";
  1496. } else if (type_name == "string") {
  1497. base_val = "\"test_string\"";
  1498. } else if (type_name == "array") {
  1499. base_val = "[1, 2, 3, \"a\", \"b\"]";
  1500. } else if (type_name == "object") {
  1501. base_val = "{\"x\": 1, \"y\": 2}";
  1502. } else {
  1503. base_val = "x";
  1504. }
  1505. tmpl = "{{ " + base_val + "." + fn_name + "(" + args_str + ") }}";
  1506. }
  1507. json vars = {
  1508. {"x", 42},
  1509. {"y", "hello"},
  1510. {"arr", json::array({1, 2, 3})},
  1511. {"obj", {{"a", 1}, {"b", 2}}}
  1512. };
  1513. t.assert_true("builtin " + type_name + "." + fn_name + " #" + std::to_string(i), fuzz_test_template(tmpl, vars));
  1514. }
  1515. });
  1516. }