test-jinja.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  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. }
  457. static void test_comments(testing & t) {
  458. test_template(t, "inline comment",
  459. "before{# comment #}after",
  460. json::object(),
  461. "beforeafter"
  462. );
  463. test_template(t, "comment ignores code",
  464. "{% set x = 1 %}{# {% set x = 999 %} #}{{ x }}",
  465. json::object(),
  466. "1"
  467. );
  468. }
  469. static void test_macros(testing & t) {
  470. test_template(t, "simple macro",
  471. "{% macro greet(name) %}Hello {{ name }}{% endmacro %}{{ greet('World') }}",
  472. json::object(),
  473. "Hello World"
  474. );
  475. test_template(t, "macro default arg",
  476. "{% macro greet(name='Guest') %}Hi {{ name }}{% endmacro %}{{ greet() }}",
  477. json::object(),
  478. "Hi Guest"
  479. );
  480. }
  481. static void test_namespace(testing & t) {
  482. test_template(t, "namespace counter",
  483. "{% set ns = namespace(count=0) %}{% for i in range(3) %}{% set ns.count = ns.count + 1 %}{% endfor %}{{ ns.count }}",
  484. json::object(),
  485. "3"
  486. );
  487. }
  488. static void test_tests(testing & t) {
  489. test_template(t, "is odd",
  490. "{% if 3 is odd %}yes{% endif %}",
  491. json::object(),
  492. "yes"
  493. );
  494. test_template(t, "is even",
  495. "{% if 4 is even %}yes{% endif %}",
  496. json::object(),
  497. "yes"
  498. );
  499. test_template(t, "is false",
  500. "{{ 'yes' if x is false }}",
  501. {{"x", false}},
  502. "yes"
  503. );
  504. test_template(t, "is true",
  505. "{{ 'yes' if x is true }}",
  506. {{"x", true}},
  507. "yes"
  508. );
  509. test_template(t, "string is false",
  510. "{{ 'yes' if x is false else 'no' }}",
  511. {{"x", ""}},
  512. "no"
  513. );
  514. test_template(t, "is divisibleby",
  515. "{{ 'yes' if x is divisibleby(2) }}",
  516. {{"x", 2}},
  517. "yes"
  518. );
  519. test_template(t, "is eq",
  520. "{{ 'yes' if 3 is eq(3) }}",
  521. json::object(),
  522. "yes"
  523. );
  524. test_template(t, "is not equalto",
  525. "{{ 'yes' if 3 is not equalto(4) }}",
  526. json::object(),
  527. "yes"
  528. );
  529. test_template(t, "is ge",
  530. "{{ 'yes' if 3 is ge(3) }}",
  531. json::object(),
  532. "yes"
  533. );
  534. test_template(t, "is gt",
  535. "{{ 'yes' if 3 is gt(2) }}",
  536. json::object(),
  537. "yes"
  538. );
  539. test_template(t, "is greaterthan",
  540. "{{ 'yes' if 3 is greaterthan(2) }}",
  541. json::object(),
  542. "yes"
  543. );
  544. test_template(t, "is lt",
  545. "{{ 'yes' if 2 is lt(3) }}",
  546. json::object(),
  547. "yes"
  548. );
  549. test_template(t, "is lessthan",
  550. "{{ 'yes' if 2 is lessthan(3) }}",
  551. json::object(),
  552. "yes"
  553. );
  554. test_template(t, "is ne",
  555. "{{ 'yes' if 2 is ne(3) }}",
  556. json::object(),
  557. "yes"
  558. );
  559. test_template(t, "is lower",
  560. "{{ 'yes' if 'lowercase' is lower }}",
  561. json::object(),
  562. "yes"
  563. );
  564. test_template(t, "is upper",
  565. "{{ 'yes' if 'UPPERCASE' is upper }}",
  566. json::object(),
  567. "yes"
  568. );
  569. test_template(t, "is sameas",
  570. "{{ 'yes' if x is sameas(false) }}",
  571. {{"x", false}},
  572. "yes"
  573. );
  574. test_template(t, "is boolean",
  575. "{{ 'yes' if x is boolean }}",
  576. {{"x", true}},
  577. "yes"
  578. );
  579. test_template(t, "is callable",
  580. "{{ 'yes' if ''.strip is callable }}",
  581. json::object(),
  582. "yes"
  583. );
  584. test_template(t, "is escaped",
  585. "{{ 'yes' if 'foo'|safe is escaped }}",
  586. json::object(),
  587. "yes"
  588. );
  589. test_template(t, "is filter",
  590. "{{ 'yes' if 'trim' is filter }}",
  591. json::object(),
  592. "yes"
  593. );
  594. test_template(t, "is float",
  595. "{{ 'yes' if x is float }}",
  596. {{"x", 1.1}},
  597. "yes"
  598. );
  599. test_template(t, "is integer",
  600. "{{ 'yes' if x is integer }}",
  601. {{"x", 1}},
  602. "yes"
  603. );
  604. test_template(t, "is sequence",
  605. "{{ 'yes' if x is sequence }}",
  606. {{"x", json::array({1, 2, 3})}},
  607. "yes"
  608. );
  609. test_template(t, "is test",
  610. "{{ 'yes' if 'sequence' is test }}",
  611. json::object(),
  612. "yes"
  613. );
  614. test_template(t, "is undefined",
  615. "{{ 'yes' if x is undefined }}",
  616. json::object(),
  617. "yes"
  618. );
  619. test_template(t, "is none",
  620. "{% if x is none %}yes{% endif %}",
  621. {{"x", nullptr}},
  622. "yes"
  623. );
  624. test_template(t, "is string",
  625. "{% if x is string %}yes{% endif %}",
  626. {{"x", "hello"}},
  627. "yes"
  628. );
  629. test_template(t, "is number",
  630. "{% if x is number %}yes{% endif %}",
  631. {{"x", 42}},
  632. "yes"
  633. );
  634. test_template(t, "is iterable",
  635. "{% if x is iterable %}yes{% endif %}",
  636. {{"x", json::array({1, 2, 3})}},
  637. "yes"
  638. );
  639. test_template(t, "is mapping",
  640. "{% if x is mapping %}yes{% endif %}",
  641. {{"x", {{"a", 1}}}},
  642. "yes"
  643. );
  644. }
  645. static void test_string_methods(testing & t) {
  646. test_template(t, "string.upper()",
  647. "{{ s.upper() }}",
  648. {{"s", "hello"}},
  649. "HELLO"
  650. );
  651. test_template(t, "string.lower()",
  652. "{{ s.lower() }}",
  653. {{"s", "HELLO"}},
  654. "hello"
  655. );
  656. test_template(t, "string.strip()",
  657. "[{{ s.strip() }}]",
  658. {{"s", " hello "}},
  659. "[hello]"
  660. );
  661. test_template(t, "string.lstrip()",
  662. "[{{ s.lstrip() }}]",
  663. {{"s", " hello"}},
  664. "[hello]"
  665. );
  666. test_template(t, "string.rstrip()",
  667. "[{{ s.rstrip() }}]",
  668. {{"s", "hello "}},
  669. "[hello]"
  670. );
  671. test_template(t, "string.title()",
  672. "{{ s.title() }}",
  673. {{"s", "hello world"}},
  674. "Hello World"
  675. );
  676. test_template(t, "string.capitalize()",
  677. "{{ s.capitalize() }}",
  678. {{"s", "heLlo World"}},
  679. "Hello world"
  680. );
  681. test_template(t, "string.startswith() true",
  682. "{% if s.startswith('hel') %}yes{% endif %}",
  683. {{"s", "hello"}},
  684. "yes"
  685. );
  686. test_template(t, "string.startswith() false",
  687. "{% if s.startswith('xyz') %}yes{% else %}no{% endif %}",
  688. {{"s", "hello"}},
  689. "no"
  690. );
  691. test_template(t, "string.endswith() true",
  692. "{% if s.endswith('lo') %}yes{% endif %}",
  693. {{"s", "hello"}},
  694. "yes"
  695. );
  696. test_template(t, "string.endswith() false",
  697. "{% if s.endswith('xyz') %}yes{% else %}no{% endif %}",
  698. {{"s", "hello"}},
  699. "no"
  700. );
  701. test_template(t, "string.split() with sep",
  702. "{{ s.split(',')|join('-') }}",
  703. {{"s", "a,b,c"}},
  704. "a-b-c"
  705. );
  706. test_template(t, "string.split() with maxsplit",
  707. "{{ s.split(',', 1)|join('-') }}",
  708. {{"s", "a,b,c"}},
  709. "a-b,c"
  710. );
  711. test_template(t, "string.rsplit() with sep",
  712. "{{ s.rsplit(',')|join('-') }}",
  713. {{"s", "a,b,c"}},
  714. "a-b-c"
  715. );
  716. test_template(t, "string.rsplit() with maxsplit",
  717. "{{ s.rsplit(',', 1)|join('-') }}",
  718. {{"s", "a,b,c"}},
  719. "a,b-c"
  720. );
  721. test_template(t, "string.replace() basic",
  722. "{{ s.replace('world', 'jinja') }}",
  723. {{"s", "hello world"}},
  724. "hello jinja"
  725. );
  726. test_template(t, "string.replace() with count",
  727. "{{ s.replace('a', 'X', 2) }}",
  728. {{"s", "banana"}},
  729. "bXnXna"
  730. );
  731. }
  732. static void test_array_methods(testing & t) {
  733. test_template(t, "array|selectattr by attribute",
  734. "{% for item in items|selectattr('active') %}{{ item.name }} {% endfor %}",
  735. {{"items", json::array({
  736. {{"name", "a"}, {"active", true}},
  737. {{"name", "b"}, {"active", false}},
  738. {{"name", "c"}, {"active", true}}
  739. })}},
  740. "a c "
  741. );
  742. test_template(t, "array|selectattr with operator",
  743. "{% for item in items|selectattr('value', 'equalto', 5) %}{{ item.name }} {% endfor %}",
  744. {{"items", json::array({
  745. {{"name", "a"}, {"value", 3}},
  746. {{"name", "b"}, {"value", 5}},
  747. {{"name", "c"}, {"value", 5}}
  748. })}},
  749. "b c "
  750. );
  751. test_template(t, "array|tojson",
  752. "{{ arr|tojson }}",
  753. {{"arr", json::array({1, 2, 3})}},
  754. "[1, 2, 3]"
  755. );
  756. test_template(t, "array|tojson with strings",
  757. "{{ arr|tojson }}",
  758. {{"arr", json::array({"a", "b", "c"})}},
  759. "[\"a\", \"b\", \"c\"]"
  760. );
  761. test_template(t, "array|tojson nested",
  762. "{{ arr|tojson }}",
  763. {{"arr", json::array({json::array({1, 2}), json::array({3, 4})})}},
  764. "[[1, 2], [3, 4]]"
  765. );
  766. test_template(t, "array|last",
  767. "{{ arr|last }}",
  768. {{"arr", json::array({10, 20, 30})}},
  769. "30"
  770. );
  771. test_template(t, "array|last single element",
  772. "{{ arr|last }}",
  773. {{"arr", json::array({42})}},
  774. "42"
  775. );
  776. test_template(t, "array|join with separator",
  777. "{{ arr|join(', ') }}",
  778. {{"arr", json::array({"a", "b", "c"})}},
  779. "a, b, c"
  780. );
  781. test_template(t, "array|join with custom separator",
  782. "{{ arr|join(' | ') }}",
  783. {{"arr", json::array({1, 2, 3})}},
  784. "1 | 2 | 3"
  785. );
  786. test_template(t, "array|join default separator",
  787. "{{ arr|join }}",
  788. {{"arr", json::array({"x", "y", "z"})}},
  789. "xyz"
  790. );
  791. test_template(t, "array|join attribute",
  792. "{{ arr|join(attribute=0) }}",
  793. {{"arr", json::array({json::array({1}), json::array({2}), json::array({3})})}},
  794. "123"
  795. );
  796. test_template(t, "array.pop() last",
  797. "{{ arr.pop() }}-{{ arr|join(',') }}",
  798. {{"arr", json::array({"a", "b", "c"})}},
  799. "c-a,b"
  800. );
  801. test_template(t, "array.pop() with index",
  802. "{{ arr.pop(0) }}-{{ arr|join(',') }}",
  803. {{"arr", json::array({"a", "b", "c"})}},
  804. "a-b,c"
  805. );
  806. test_template(t, "array.append()",
  807. "{% set _ = arr.append('d') %}{{ arr|join(',') }}",
  808. {{"arr", json::array({"a", "b", "c"})}},
  809. "a,b,c,d"
  810. );
  811. test_template(t, "array.map() with attribute",
  812. "{% for v in arr.map('age') %}{{ v }} {% endfor %}",
  813. {{"arr", json::array({
  814. json({{"name", "a"}, {"age", 1}}),
  815. json({{"name", "b"}, {"age", 2}}),
  816. json({{"name", "c"}, {"age", 3}}),
  817. })}},
  818. "1 2 3 "
  819. );
  820. test_template(t, "array.map() with numeric attribute",
  821. "{% for v in arr.map(0) %}{{ v }} {% endfor %}",
  822. {{"arr", json::array({
  823. json::array({10, "x"}),
  824. json::array({20, "y"}),
  825. json::array({30, "z"}),
  826. })}},
  827. "10 20 30 "
  828. );
  829. // not used by any chat templates
  830. // test_template(t, "array.insert()",
  831. // "{% set _ = arr.insert(1, 'x') %}{{ arr|join(',') }}",
  832. // {{"arr", json::array({"a", "b", "c"})}},
  833. // "a,x,b,c"
  834. // );
  835. }
  836. static void test_object_methods(testing & t) {
  837. test_template(t, "object.get() existing key",
  838. "{{ obj.get('a') }}",
  839. {{"obj", {{"a", 1}, {"b", 2}}}},
  840. "1"
  841. );
  842. test_template(t, "object.get() missing key",
  843. "[{{ obj.get('c') is none }}]",
  844. {{"obj", {{"a", 1}}}},
  845. "[True]"
  846. );
  847. test_template(t, "object.get() missing key with default",
  848. "{{ obj.get('c', 'default') }}",
  849. {{"obj", {{"a", 1}}}},
  850. "default"
  851. );
  852. test_template(t, "object.items()",
  853. "{% for k, v in obj.items() %}{{ k }}={{ v }} {% endfor %}",
  854. {{"obj", {{"x", 1}, {"y", 2}}}},
  855. "x=1 y=2 "
  856. );
  857. test_template(t, "object.keys()",
  858. "{% for k in obj.keys() %}{{ k }} {% endfor %}",
  859. {{"obj", {{"a", 1}, {"b", 2}}}},
  860. "a b "
  861. );
  862. test_template(t, "object.values()",
  863. "{% for v in obj.values() %}{{ v }} {% endfor %}",
  864. {{"obj", {{"a", 1}, {"b", 2}}}},
  865. "1 2 "
  866. );
  867. test_template(t, "dictsort ascending by key",
  868. "{% for k, v in obj|dictsort %}{{ k }}={{ v }} {% endfor %}",
  869. {{"obj", {{"z", 2}, {"a", 3}, {"m", 1}}}},
  870. "a=3 m=1 z=2 "
  871. );
  872. test_template(t, "dictsort descending by key",
  873. "{% for k, v in obj|dictsort(reverse=true) %}{{ k }}={{ v }} {% endfor %}",
  874. {{"obj", {{"a", 1}, {"b", 2}, {"c", 3}}}},
  875. "c=3 b=2 a=1 "
  876. );
  877. test_template(t, "dictsort by value",
  878. "{% for k, v in obj|dictsort(by='value') %}{{ k }}={{ v }} {% endfor %}",
  879. {{"obj", {{"a", 3}, {"b", 1}, {"c", 2}}}},
  880. "b=1 c=2 a=3 "
  881. );
  882. test_template(t, "dictsort case sensitive",
  883. "{% for k, v in obj|dictsort(case_sensitive=true) %}{{ k }}={{ v }} {% endfor %}",
  884. {{"obj", {{"a", 1}, {"A", 1}, {"b", 2}, {"B", 2}, {"c", 3}}}},
  885. "A=1 B=2 a=1 b=2 c=3 "
  886. );
  887. test_template(t, "object|tojson",
  888. "{{ obj|tojson }}",
  889. {{"obj", {{"name", "test"}, {"value", 42}}}},
  890. "{\"name\": \"test\", \"value\": 42}"
  891. );
  892. test_template(t, "nested object|tojson",
  893. "{{ obj|tojson }}",
  894. {{"obj", {{"outer", {{"inner", "value"}}}}}},
  895. "{\"outer\": {\"inner\": \"value\"}}"
  896. );
  897. test_template(t, "array in object|tojson",
  898. "{{ obj|tojson }}",
  899. {{"obj", {{"items", json::array({1, 2, 3})}}}},
  900. "{\"items\": [1, 2, 3]}"
  901. );
  902. test_template(t, "object attribute and key access",
  903. "{{ obj.keys()|join(',') }} vs {{ obj['keys'] }} vs {{ obj.test }}",
  904. {{"obj", {{"keys", "value"}, {"test", "attr_value"}}}},
  905. "keys,test vs value vs attr_value"
  906. );
  907. test_template(t, "env should not have object methods",
  908. "{{ keys is undefined }} {{ obj.keys is defined }}",
  909. {{"obj", {{"a", "b"}}}},
  910. "True True"
  911. );
  912. }
  913. static void test_template(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect) {
  914. t.test(name, [&tmpl, &vars, &expect](testing & t) {
  915. jinja::lexer lexer;
  916. auto lexer_res = lexer.tokenize(tmpl);
  917. jinja::program ast = jinja::parse_from_tokens(lexer_res);
  918. jinja::context ctx(tmpl);
  919. jinja::global_from_json(ctx, vars, true);
  920. jinja::runtime runtime(ctx);
  921. try {
  922. const jinja::value results = runtime.execute(ast);
  923. auto parts = runtime.gather_string_parts(results);
  924. std::string rendered;
  925. for (const auto & part : parts->as_string().parts) {
  926. rendered += part.val;
  927. }
  928. if (!t.assert_true("Template render mismatch", expect == rendered)) {
  929. t.log("Template: " + json(tmpl).dump());
  930. t.log("Expected: " + json(expect).dump());
  931. t.log("Actual : " + json(rendered).dump());
  932. }
  933. } catch (const jinja::not_implemented_exception & e) {
  934. // TODO @ngxson : remove this when the test framework supports skipping tests
  935. t.log("Skipped: " + std::string(e.what()));
  936. }
  937. });
  938. }
  939. //
  940. // fuzz tests to ensure no crashes occur on malformed inputs
  941. //
  942. constexpr int JINJA_FUZZ_ITERATIONS = 100;
  943. // Helper to generate random string
  944. static std::string random_string(std::mt19937 & rng, size_t max_len) {
  945. static const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
  946. std::uniform_int_distribution<size_t> len_dist(0, max_len);
  947. std::uniform_int_distribution<size_t> char_dist(0, sizeof(charset) - 2);
  948. size_t len = len_dist(rng);
  949. std::string result;
  950. result.reserve(len);
  951. for (size_t i = 0; i < len; ++i) {
  952. result += charset[char_dist(rng)];
  953. }
  954. return result;
  955. }
  956. // Helper to execute a fuzz test case - returns true if no crash occurred
  957. static bool fuzz_test_template(const std::string & tmpl, const json & vars) {
  958. try {
  959. // printf("Fuzz testing template: %s\n", tmpl.c_str());
  960. jinja::lexer lexer;
  961. auto lexer_res = lexer.tokenize(tmpl);
  962. jinja::program ast = jinja::parse_from_tokens(lexer_res);
  963. jinja::context ctx(tmpl);
  964. jinja::global_from_json(ctx, vars, true);
  965. jinja::runtime runtime(ctx);
  966. const jinja::value results = runtime.execute(ast);
  967. runtime.gather_string_parts(results);
  968. return true; // success
  969. } catch (const std::exception &) {
  970. return true; // exception is acceptable, not a crash
  971. } catch (...) {
  972. return true; // any exception is acceptable, not a crash
  973. }
  974. }
  975. static void test_fuzzing(testing & t) {
  976. const int num_iterations = JINJA_FUZZ_ITERATIONS;
  977. const unsigned int seed = 42; // fixed seed for reproducibility
  978. std::mt19937 rng(seed);
  979. // Distribution helpers
  980. std::uniform_int_distribution<int> choice_dist(0, 100);
  981. std::uniform_int_distribution<int> int_dist(-1000, 1000);
  982. std::uniform_int_distribution<size_t> idx_dist(0, 1000);
  983. // Template fragments for fuzzing
  984. const std::vector<std::string> var_names = {
  985. "x", "y", "z", "arr", "obj", "items", "foo", "bar", "undefined_var",
  986. "none", "true", "false", "None", "True", "False"
  987. };
  988. const std::vector<std::string> filters = {
  989. "length", "first", "last", "reverse", "sort", "unique", "join", "upper", "lower",
  990. "trim", "default", "tojson", "string", "int", "float", "abs", "list", "dictsort"
  991. };
  992. const std::vector<std::string> builtins = {
  993. "range", "len", "dict", "list", "join", "str", "int", "float", "namespace"
  994. };
  995. t.test("out of bound array access", [&](testing & t) {
  996. for (int i = 0; i < num_iterations; ++i) {
  997. int idx = int_dist(rng);
  998. std::string tmpl = "{{ arr[" + std::to_string(idx) + "] }}";
  999. json vars = {{"arr", json::array({1, 2, 3})}};
  1000. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1001. }
  1002. });
  1003. t.test("non-existing variables", [&](testing & t) {
  1004. for (int i = 0; i < num_iterations; ++i) {
  1005. std::string var = random_string(rng, 20);
  1006. std::string tmpl = "{{ " + var + " }}";
  1007. json vars = json::object(); // empty context
  1008. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1009. }
  1010. });
  1011. t.test("non-existing nested attributes", [&](testing & t) {
  1012. for (int i = 0; i < num_iterations; ++i) {
  1013. std::string var1 = var_names[choice_dist(rng) % var_names.size()];
  1014. std::string var2 = random_string(rng, 10);
  1015. std::string var3 = random_string(rng, 10);
  1016. std::string tmpl = "{{ " + var1 + "." + var2 + "." + var3 + " }}";
  1017. json vars = {{var1, {{"other", 123}}}};
  1018. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1019. }
  1020. });
  1021. t.test("invalid filter arguments", [&](testing & t) {
  1022. for (int i = 0; i < num_iterations; ++i) {
  1023. std::string filter = filters[choice_dist(rng) % filters.size()];
  1024. int val = int_dist(rng);
  1025. std::string tmpl = "{{ " + std::to_string(val) + " | " + filter + " }}";
  1026. json vars = json::object();
  1027. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1028. }
  1029. });
  1030. t.test("chained filters on various types", [&](testing & t) {
  1031. for (int i = 0; i < num_iterations; ++i) {
  1032. std::string f1 = filters[choice_dist(rng) % filters.size()];
  1033. std::string f2 = filters[choice_dist(rng) % filters.size()];
  1034. std::string var = var_names[choice_dist(rng) % var_names.size()];
  1035. std::string tmpl = "{{ " + var + " | " + f1 + " | " + f2 + " }}";
  1036. json vars = {
  1037. {"x", 42},
  1038. {"y", "hello"},
  1039. {"arr", json::array({1, 2, 3})},
  1040. {"obj", {{"a", 1}, {"b", 2}}},
  1041. {"items", json::array({"a", "b", "c"})}
  1042. };
  1043. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1044. }
  1045. });
  1046. t.test("invalid builtin calls", [&](testing & t) {
  1047. for (int i = 0; i < num_iterations; ++i) {
  1048. std::string builtin = builtins[choice_dist(rng) % builtins.size()];
  1049. std::string arg;
  1050. int arg_type = choice_dist(rng) % 4;
  1051. switch (arg_type) {
  1052. case 0: arg = "\"not a number\""; break;
  1053. case 1: arg = "none"; break;
  1054. case 2: arg = std::to_string(int_dist(rng)); break;
  1055. case 3: arg = "[]"; break;
  1056. }
  1057. std::string tmpl = "{{ " + builtin + "(" + arg + ") }}";
  1058. json vars = json::object();
  1059. t.assert_true("should not crash", fuzz_test_template(tmpl, vars));
  1060. }
  1061. });
  1062. t.test("macro edge cases", [&](testing & t) {
  1063. // Macro with no args called with args
  1064. t.assert_true("macro no args with args", fuzz_test_template(
  1065. "{% macro foo() %}hello{% endmacro %}{{ foo(1, 2, 3) }}",
  1066. json::object()
  1067. ));
  1068. // Macro with args called with no args
  1069. t.assert_true("macro with args no args", fuzz_test_template(
  1070. "{% macro foo(a, b, c) %}{{ a }}{{ b }}{{ c }}{% endmacro %}{{ foo() }}",
  1071. json::object()
  1072. ));
  1073. // Recursive macro reference
  1074. t.assert_true("recursive macro", fuzz_test_template(
  1075. "{% macro foo(n) %}{% if n > 0 %}{{ foo(n - 1) }}{% endif %}{% endmacro %}{{ foo(5) }}",
  1076. json::object()
  1077. ));
  1078. // Nested macro definitions
  1079. for (int i = 0; i < num_iterations / 10; ++i) {
  1080. std::string tmpl = "{% macro outer() %}{% macro inner() %}x{% endmacro %}{{ inner() }}{% endmacro %}{{ outer() }}";
  1081. t.assert_true("nested macro", fuzz_test_template(tmpl, json::object()));
  1082. }
  1083. });
  1084. t.test("empty and none operations", [&](testing & t) {
  1085. const std::vector<std::string> empty_tests = {
  1086. "{{ \"\" | first }}",
  1087. "{{ \"\" | last }}",
  1088. "{{ [] | first }}",
  1089. "{{ [] | last }}",
  1090. "{{ none.attr }}",
  1091. "{{ none | length }}",
  1092. "{{ none | default('fallback') }}",
  1093. "{{ {} | first }}",
  1094. "{{ {} | dictsort }}",
  1095. };
  1096. for (const auto & tmpl : empty_tests) {
  1097. t.assert_true("empty/none: " + tmpl, fuzz_test_template(tmpl, json::object()));
  1098. }
  1099. });
  1100. t.test("arithmetic edge cases", [&](testing & t) {
  1101. const std::vector<std::string> arith_tests = {
  1102. "{{ 1 / 0 }}",
  1103. "{{ 1 // 0 }}",
  1104. "{{ 1 % 0 }}",
  1105. "{{ 999999999999999999 * 999999999999999999 }}",
  1106. "{{ -999999999999999999 - 999999999999999999 }}",
  1107. "{{ 1.0 / 0.0 }}",
  1108. "{{ 0.0 / 0.0 }}",
  1109. };
  1110. for (const auto & tmpl : arith_tests) {
  1111. t.assert_true("arith: " + tmpl, fuzz_test_template(tmpl, json::object()));
  1112. }
  1113. });
  1114. t.test("deeply nested structures", [&](testing & t) {
  1115. // Deeply nested loops
  1116. for (int depth = 1; depth <= 10; ++depth) {
  1117. std::string tmpl;
  1118. for (int d = 0; d < depth; ++d) {
  1119. tmpl += "{% for i" + std::to_string(d) + " in arr %}";
  1120. }
  1121. tmpl += "x";
  1122. for (int d = 0; d < depth; ++d) {
  1123. tmpl += "{% endfor %}";
  1124. }
  1125. json vars = {{"arr", json::array({1, 2})}};
  1126. t.assert_true("nested loops depth " + std::to_string(depth), fuzz_test_template(tmpl, vars));
  1127. }
  1128. // Deeply nested conditionals
  1129. for (int depth = 1; depth <= 10; ++depth) {
  1130. std::string tmpl;
  1131. for (int d = 0; d < depth; ++d) {
  1132. tmpl += "{% if true %}";
  1133. }
  1134. tmpl += "x";
  1135. for (int d = 0; d < depth; ++d) {
  1136. tmpl += "{% endif %}";
  1137. }
  1138. t.assert_true("nested ifs depth " + std::to_string(depth), fuzz_test_template(tmpl, json::object()));
  1139. }
  1140. });
  1141. t.test("special characters in strings", [&](testing & t) {
  1142. const std::vector<std::string> special_tests = {
  1143. "{{ \"}{%\" }}",
  1144. "{{ \"}}{{\" }}",
  1145. "{{ \"{%%}\" }}",
  1146. "{{ \"\\n\\t\\r\" }}",
  1147. "{{ \"'\\\"'\" }}",
  1148. "{{ \"hello\\x00world\" }}",
  1149. };
  1150. for (const auto & tmpl : special_tests) {
  1151. t.assert_true("special: " + tmpl, fuzz_test_template(tmpl, json::object()));
  1152. }
  1153. });
  1154. t.test("random template generation", [&](testing & t) {
  1155. const std::vector<std::string> fragments = {
  1156. "{{ x }}", "{{ y }}", "{{ arr }}", "{{ obj }}",
  1157. "{% if true %}a{% endif %}",
  1158. "{% if false %}b{% else %}c{% endif %}",
  1159. "{% for i in arr %}{{ i }}{% endfor %}",
  1160. "{{ x | length }}", "{{ x | first }}", "{{ x | default(0) }}",
  1161. "{{ x + y }}", "{{ x - y }}", "{{ x * y }}",
  1162. "{{ x == y }}", "{{ x != y }}", "{{ x > y }}",
  1163. "{{ range(3) }}", "{{ \"hello\" | upper }}",
  1164. "text", " ", "\n",
  1165. };
  1166. for (int i = 0; i < num_iterations; ++i) {
  1167. std::string tmpl;
  1168. int num_frags = choice_dist(rng) % 10 + 1;
  1169. for (int f = 0; f < num_frags; ++f) {
  1170. tmpl += fragments[choice_dist(rng) % fragments.size()];
  1171. }
  1172. json vars = {
  1173. {"x", int_dist(rng)},
  1174. {"y", int_dist(rng)},
  1175. {"arr", json::array({1, 2, 3})},
  1176. {"obj", {{"a", 1}, {"b", 2}}}
  1177. };
  1178. t.assert_true("random template #" + std::to_string(i), fuzz_test_template(tmpl, vars));
  1179. }
  1180. });
  1181. t.test("malformed templates (should error, not crash)", [&](testing & t) {
  1182. const std::vector<std::string> malformed = {
  1183. "{{ x",
  1184. "{% if %}",
  1185. "{% for %}",
  1186. "{% for x in %}",
  1187. "{% endfor %}",
  1188. "{% endif %}",
  1189. "{{ | filter }}",
  1190. "{% if x %}", // unclosed
  1191. "{% for i in x %}", // unclosed
  1192. "{{ x | }}",
  1193. "{% macro %}{% endmacro %}",
  1194. "{{{{",
  1195. "}}}}",
  1196. "{%%}",
  1197. "{% set %}",
  1198. "{% set x %}",
  1199. };
  1200. for (const auto & tmpl : malformed) {
  1201. t.assert_true("malformed: " + tmpl, fuzz_test_template(tmpl, json::object()));
  1202. }
  1203. });
  1204. t.test("type coercion edge cases", [&](testing & t) {
  1205. for (int i = 0; i < num_iterations; ++i) {
  1206. int op_choice = choice_dist(rng) % 6;
  1207. std::string op;
  1208. switch (op_choice) {
  1209. case 0: op = "+"; break;
  1210. case 1: op = "-"; break;
  1211. case 2: op = "*"; break;
  1212. case 3: op = "/"; break;
  1213. case 4: op = "=="; break;
  1214. case 5: op = "~"; break; // string concat
  1215. }
  1216. std::string left_var = var_names[choice_dist(rng) % var_names.size()];
  1217. std::string right_var = var_names[choice_dist(rng) % var_names.size()];
  1218. std::string tmpl = "{{ " + left_var + " " + op + " " + right_var + " }}";
  1219. json vars = {
  1220. {"x", 42},
  1221. {"y", "hello"},
  1222. {"z", 3.14},
  1223. {"arr", json::array({1, 2, 3})},
  1224. {"obj", {{"a", 1}}},
  1225. {"items", json::array()},
  1226. {"foo", nullptr},
  1227. {"bar", true}
  1228. };
  1229. t.assert_true("type coercion: " + tmpl, fuzz_test_template(tmpl, vars));
  1230. }
  1231. });
  1232. t.test("fuzz builtin functions", [&](testing & t) {
  1233. // pair of (type_name, builtin_name)
  1234. std::vector<std::pair<std::string, std::string>> builtins;
  1235. auto add_fns = [&](std::string type_name, const jinja::func_builtins & added) {
  1236. for (const auto & it : added) {
  1237. builtins.push_back({type_name, it.first});
  1238. }
  1239. };
  1240. add_fns("global", jinja::global_builtins());
  1241. add_fns("int", jinja::value_int_t(0).get_builtins());
  1242. add_fns("float", jinja::value_float_t(0.0f).get_builtins());
  1243. add_fns("string", jinja::value_string_t().get_builtins());
  1244. add_fns("array", jinja::value_array_t().get_builtins());
  1245. add_fns("object", jinja::value_object_t().get_builtins());
  1246. const int max_args = 5;
  1247. const std::vector<std::string> kwarg_names = {
  1248. "base", "attribute", "default", "reverse", "case_sensitive", "by", "safe", "chars", "separators", "sort_keys", "indent", "ensure_ascii",
  1249. };
  1250. // Generate random argument values
  1251. auto gen_random_arg = [&]() -> std::string {
  1252. int type = choice_dist(rng) % 8;
  1253. switch (type) {
  1254. case 0: return std::to_string(int_dist(rng)); // int
  1255. case 1: return std::to_string(int_dist(rng)) + ".5"; // float
  1256. case 2: return "\"" + random_string(rng, 10) + "\""; // string
  1257. case 3: return "true"; // bool true
  1258. case 4: return "false"; // bool false
  1259. case 5: return "none"; // none
  1260. case 6: return "[1, 2, 3]"; // array
  1261. case 7: return "{\"a\": 1}"; // object
  1262. default: return "0";
  1263. }
  1264. };
  1265. for (int i = 0; i < num_iterations; ++i) {
  1266. // Pick a random builtin
  1267. auto & [type_name, fn_name] = builtins[choice_dist(rng) % builtins.size()];
  1268. // Generate random number of args
  1269. int num_args = choice_dist(rng) % (max_args + 1);
  1270. std::string args_str;
  1271. for (int a = 0; a < num_args; ++a) {
  1272. if (a > 0) args_str += ", ";
  1273. // Sometimes use keyword args
  1274. if (choice_dist(rng) % 3 == 0 && !kwarg_names.empty()) {
  1275. std::string kwarg = kwarg_names[choice_dist(rng) % kwarg_names.size()];
  1276. args_str += kwarg + "=" + gen_random_arg();
  1277. } else {
  1278. args_str += gen_random_arg();
  1279. }
  1280. }
  1281. std::string tmpl;
  1282. if (type_name == "global") {
  1283. // Global function call
  1284. tmpl = "{{ " + fn_name + "(" + args_str + ") }}";
  1285. } else {
  1286. // Method call on a value
  1287. std::string base_val;
  1288. if (type_name == "int") {
  1289. base_val = std::to_string(int_dist(rng));
  1290. } else if (type_name == "float") {
  1291. base_val = std::to_string(int_dist(rng)) + ".5";
  1292. } else if (type_name == "string") {
  1293. base_val = "\"test_string\"";
  1294. } else if (type_name == "array") {
  1295. base_val = "[1, 2, 3, \"a\", \"b\"]";
  1296. } else if (type_name == "object") {
  1297. base_val = "{\"x\": 1, \"y\": 2}";
  1298. } else {
  1299. base_val = "x";
  1300. }
  1301. tmpl = "{{ " + base_val + "." + fn_name + "(" + args_str + ") }}";
  1302. }
  1303. json vars = {
  1304. {"x", 42},
  1305. {"y", "hello"},
  1306. {"arr", json::array({1, 2, 3})},
  1307. {"obj", {{"a", 1}, {"b", 2}}}
  1308. };
  1309. t.assert_true("builtin " + type_name + "." + fn_name + " #" + std::to_string(i), fuzz_test_template(tmpl, vars));
  1310. }
  1311. });
  1312. }