test-jinja.cpp 43 KB

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