test-jinja.cpp 45 KB

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