test_format.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. import datetime
  2. from typing import Any
  3. import pytest
  4. from reflex.components.tags.tag import Tag
  5. from reflex.event import EventChain, EventHandler, EventSpec, FrontendEvent
  6. from reflex.style import Style
  7. from reflex.utils import format
  8. from reflex.vars import BaseVar, Var
  9. from tests.test_state import (
  10. ChildState,
  11. ChildState2,
  12. DateTimeState,
  13. GrandchildState,
  14. TestState,
  15. )
  16. def mock_event(arg):
  17. pass
  18. @pytest.mark.parametrize(
  19. "input,output",
  20. [
  21. ("{", "}"),
  22. ("(", ")"),
  23. ("[", "]"),
  24. ("<", ">"),
  25. ('"', '"'),
  26. ("'", "'"),
  27. ],
  28. )
  29. def test_get_close_char(input: str, output: str):
  30. """Test getting the close character for a given open character.
  31. Args:
  32. input: The open character.
  33. output: The expected close character.
  34. """
  35. assert format.get_close_char(input) == output
  36. @pytest.mark.parametrize(
  37. "text,open,expected",
  38. [
  39. ("", "{", False),
  40. ("{wrap}", "{", True),
  41. ("{wrap", "{", False),
  42. ("{wrap}", "(", False),
  43. ("(wrap)", "(", True),
  44. ],
  45. )
  46. def test_is_wrapped(text: str, open: str, expected: bool):
  47. """Test checking if a string is wrapped in the given open and close characters.
  48. Args:
  49. text: The text to check.
  50. open: The open character.
  51. expected: Whether the text is wrapped.
  52. """
  53. assert format.is_wrapped(text, open) == expected
  54. @pytest.mark.parametrize(
  55. "text,open,check_first,num,expected",
  56. [
  57. ("", "{", True, 1, "{}"),
  58. ("wrap", "{", True, 1, "{wrap}"),
  59. ("wrap", "(", True, 1, "(wrap)"),
  60. ("wrap", "(", True, 2, "((wrap))"),
  61. ("(wrap)", "(", True, 1, "(wrap)"),
  62. ("{wrap}", "{", True, 2, "{wrap}"),
  63. ("(wrap)", "{", True, 1, "{(wrap)}"),
  64. ("(wrap)", "(", False, 1, "((wrap))"),
  65. ],
  66. )
  67. def test_wrap(text: str, open: str, expected: str, check_first: bool, num: int):
  68. """Test wrapping a string.
  69. Args:
  70. text: The text to wrap.
  71. open: The open character.
  72. expected: The expected output string.
  73. check_first: Whether to check if the text is already wrapped.
  74. num: The number of times to wrap the text.
  75. """
  76. assert format.wrap(text, open, check_first=check_first, num=num) == expected
  77. @pytest.mark.parametrize(
  78. "text,indent_level,expected",
  79. [
  80. ("", 2, ""),
  81. ("hello", 2, "hello"),
  82. ("hello\nworld", 2, " hello\n world\n"),
  83. ("hello\nworld", 4, " hello\n world\n"),
  84. (" hello\n world", 2, " hello\n world\n"),
  85. ],
  86. )
  87. def test_indent(text: str, indent_level: int, expected: str, windows_platform: bool):
  88. """Test indenting a string.
  89. Args:
  90. text: The text to indent.
  91. indent_level: The number of spaces to indent by.
  92. expected: The expected output string.
  93. windows_platform: Whether the system is windows.
  94. """
  95. assert format.indent(text, indent_level) == (
  96. expected.replace("\n", "\r\n") if windows_platform else expected
  97. )
  98. @pytest.mark.parametrize(
  99. "input,output",
  100. [
  101. ("", ""),
  102. ("hello", "hello"),
  103. ("Hello", "hello"),
  104. ("camelCase", "camel_case"),
  105. ("camelTwoHumps", "camel_two_humps"),
  106. ("_start_with_underscore", "_start_with_underscore"),
  107. ("__start_with_double_underscore", "__start_with_double_underscore"),
  108. ("kebab-case", "kebab_case"),
  109. ("double-kebab-case", "double_kebab_case"),
  110. (":start-with-colon", ":start_with_colon"),
  111. (":-start-with-colon-dash", ":_start_with_colon_dash"),
  112. ],
  113. )
  114. def test_to_snake_case(input: str, output: str):
  115. """Test converting strings to snake case.
  116. Args:
  117. input: The input string.
  118. output: The expected output string.
  119. """
  120. assert format.to_snake_case(input) == output
  121. @pytest.mark.parametrize(
  122. "input,output",
  123. [
  124. ("", ""),
  125. ("hello", "hello"),
  126. ("Hello", "Hello"),
  127. ("snake_case", "snakeCase"),
  128. ("snake_case_two", "snakeCaseTwo"),
  129. ("kebab-case", "kebabCase"),
  130. ("kebab-case-two", "kebabCaseTwo"),
  131. ("snake_kebab-case", "snakeKebabCase"),
  132. ("_hover", "_hover"),
  133. ("-starts-with-hyphen", "-startsWithHyphen"),
  134. ("--starts-with-double-hyphen", "--startsWithDoubleHyphen"),
  135. ("_starts_with_underscore", "_startsWithUnderscore"),
  136. ("__starts_with_double_underscore", "__startsWithDoubleUnderscore"),
  137. (":start-with-colon", ":startWithColon"),
  138. (":-start-with-colon-dash", ":StartWithColonDash"),
  139. ],
  140. )
  141. def test_to_camel_case(input: str, output: str):
  142. """Test converting strings to camel case.
  143. Args:
  144. input: The input string.
  145. output: The expected output string.
  146. """
  147. assert format.to_camel_case(input) == output
  148. @pytest.mark.parametrize(
  149. "input,output",
  150. [
  151. ("", ""),
  152. ("hello", "Hello"),
  153. ("Hello", "Hello"),
  154. ("snake_case", "SnakeCase"),
  155. ("snake_case_two", "SnakeCaseTwo"),
  156. ],
  157. )
  158. def test_to_title_case(input: str, output: str):
  159. """Test converting strings to title case.
  160. Args:
  161. input: The input string.
  162. output: The expected output string.
  163. """
  164. assert format.to_title_case(input) == output
  165. @pytest.mark.parametrize(
  166. "input,output",
  167. [
  168. ("", ""),
  169. ("hello", "hello"),
  170. ("Hello", "hello"),
  171. ("snake_case", "snake-case"),
  172. ("snake_case_two", "snake-case-two"),
  173. (":startWithColon", ":start-with-colon"),
  174. (":StartWithColonDash", ":-start-with-colon-dash"),
  175. (":start_with_colon", ":start-with-colon"),
  176. (":_start_with_colon_dash", ":-start-with-colon-dash"),
  177. ],
  178. )
  179. def test_to_kebab_case(input: str, output: str):
  180. """Test converting strings to kebab case.
  181. Args:
  182. input: the input string.
  183. output: the output string.
  184. """
  185. assert format.to_kebab_case(input) == output
  186. @pytest.mark.parametrize(
  187. "input,output",
  188. [
  189. ("", "{``}"),
  190. ("hello", "{`hello`}"),
  191. ("hello world", "{`hello world`}"),
  192. ("hello=`world`", "{`hello=\\`world\\``}"),
  193. ],
  194. )
  195. def test_format_string(input: str, output: str):
  196. """Test formating the input as JS string literal.
  197. Args:
  198. input: the input string.
  199. output: the output string.
  200. """
  201. assert format.format_string(input) == output
  202. @pytest.mark.parametrize(
  203. "input,output",
  204. [
  205. (Var.create(value="test"), "{`test`}"),
  206. (Var.create(value="test", _var_is_local=True), "{`test`}"),
  207. (Var.create(value="test", _var_is_local=False), "{test}"),
  208. (Var.create(value="test", _var_is_string=True), "{`test`}"),
  209. (Var.create(value="test", _var_is_string=False), "{`test`}"),
  210. (Var.create(value="test", _var_is_local=False, _var_is_string=False), "{test}"),
  211. ],
  212. )
  213. def test_format_var(input: Var, output: str):
  214. assert format.format_var(input) == output
  215. @pytest.mark.parametrize(
  216. "route,format_case,expected",
  217. [
  218. ("", True, "index"),
  219. ("/", True, "index"),
  220. ("custom-route", True, "custom-route"),
  221. ("custom-route", False, "custom-route"),
  222. ("custom-route/", True, "custom-route"),
  223. ("custom-route/", False, "custom-route"),
  224. ("/custom-route", True, "custom-route"),
  225. ("/custom-route", False, "custom-route"),
  226. ("/custom_route", True, "custom-route"),
  227. ("/custom_route", False, "custom_route"),
  228. ("/CUSTOM_route", True, "custom-route"),
  229. ("/CUSTOM_route", False, "CUSTOM_route"),
  230. ],
  231. )
  232. def test_format_route(route: str, format_case: bool, expected: bool):
  233. """Test formatting a route.
  234. Args:
  235. route: The route to format.
  236. format_case: Whether to change casing to snake_case.
  237. expected: The expected formatted route.
  238. """
  239. assert format.format_route(route, format_case=format_case) == expected
  240. @pytest.mark.parametrize(
  241. "condition,true_value,false_value,expected",
  242. [
  243. ("cond", "<C1>", '""', '{isTrue(cond) ? <C1> : ""}'),
  244. ("cond", "<C1>", "<C2>", "{isTrue(cond) ? <C1> : <C2>}"),
  245. ],
  246. )
  247. def test_format_cond(condition: str, true_value: str, false_value: str, expected: str):
  248. """Test formatting a cond.
  249. Args:
  250. condition: The condition to check.
  251. true_value: The value to return if the condition is true.
  252. false_value: The value to return if the condition is false.
  253. expected: The expected output string.
  254. """
  255. assert format.format_cond(condition, true_value, false_value) == expected
  256. @pytest.mark.parametrize(
  257. "prop,formatted",
  258. [
  259. ("string", '"string"'),
  260. ("{wrapped_string}", "{wrapped_string}"),
  261. (True, "{true}"),
  262. (False, "{false}"),
  263. (123, "{123}"),
  264. (3.14, "{3.14}"),
  265. ([1, 2, 3], "{[1, 2, 3]}"),
  266. (["a", "b", "c"], '{["a", "b", "c"]}'),
  267. ({"a": 1, "b": 2, "c": 3}, '{{"a": 1, "b": 2, "c": 3}}'),
  268. ({"a": 'foo "bar" baz'}, r'{{"a": "foo \"bar\" baz"}}'),
  269. (
  270. {
  271. "a": 'foo "{ "bar" }" baz',
  272. "b": BaseVar(_var_name="val", _var_type="str"),
  273. },
  274. r'{{"a": "foo \"{ \"bar\" }\" baz", "b": val}}',
  275. ),
  276. (
  277. EventChain(
  278. events=[EventSpec(handler=EventHandler(fn=mock_event))],
  279. args_spec=lambda: [],
  280. ),
  281. '{(_e) => addEvents([Event("mock_event", {})], (_e), {})}',
  282. ),
  283. (
  284. EventChain(
  285. events=[
  286. EventSpec(
  287. handler=EventHandler(fn=mock_event),
  288. args=(
  289. (
  290. Var.create_safe("arg"),
  291. BaseVar(
  292. _var_name="_e",
  293. _var_type=FrontendEvent,
  294. ).target.value,
  295. ),
  296. ),
  297. )
  298. ],
  299. args_spec=lambda: [],
  300. ),
  301. '{(_e) => addEvents([Event("mock_event", {arg:_e.target.value})], (_e), {})}',
  302. ),
  303. (
  304. EventChain(
  305. events=[EventSpec(handler=EventHandler(fn=mock_event))],
  306. args_spec=lambda: [],
  307. event_actions={"stopPropagation": True},
  308. ),
  309. '{(_e) => addEvents([Event("mock_event", {})], (_e), {"stopPropagation": true})}',
  310. ),
  311. (
  312. EventChain(
  313. events=[EventSpec(handler=EventHandler(fn=mock_event))],
  314. args_spec=lambda: [],
  315. event_actions={"preventDefault": True},
  316. ),
  317. '{(_e) => addEvents([Event("mock_event", {})], (_e), {"preventDefault": true})}',
  318. ),
  319. ({"a": "red", "b": "blue"}, '{{"a": "red", "b": "blue"}}'),
  320. (BaseVar(_var_name="var", _var_type="int"), "{var}"),
  321. (
  322. BaseVar(
  323. _var_name="_",
  324. _var_type=Any,
  325. _var_is_local=True,
  326. _var_is_string=False,
  327. ),
  328. "{_}",
  329. ),
  330. (
  331. BaseVar(_var_name='state.colors["a"]', _var_type="str"),
  332. '{state.colors["a"]}',
  333. ),
  334. ({"a": BaseVar(_var_name="val", _var_type="str")}, '{{"a": val}}'),
  335. ({"a": BaseVar(_var_name='"val"', _var_type="str")}, '{{"a": "val"}}'),
  336. (
  337. {"a": BaseVar(_var_name='state.colors["val"]', _var_type="str")},
  338. '{{"a": state.colors["val"]}}',
  339. ),
  340. # tricky real-world case from markdown component
  341. (
  342. {
  343. "h1": f"{{({{node, ...props}}) => <Heading {{...props}} {''.join(Tag(name='', props=Style({'as_': 'h1'})).format_props())} />}}"
  344. },
  345. '{{"h1": ({node, ...props}) => <Heading {...props} as={`h1`} />}}',
  346. ),
  347. ],
  348. )
  349. def test_format_prop(prop: Var, formatted: str):
  350. """Test that the formatted value of an prop is correct.
  351. Args:
  352. prop: The prop to test.
  353. formatted: The expected formatted value.
  354. """
  355. assert format.format_prop(prop) == formatted
  356. @pytest.mark.parametrize(
  357. "single_props,key_value_props,output",
  358. [
  359. (["string"], {"key": 42}, ["key={42}", "string"]),
  360. ],
  361. )
  362. def test_format_props(single_props, key_value_props, output):
  363. """Test the result of formatting a set of props (both single and keyvalue).
  364. Args:
  365. single_props: the list of single props
  366. key_value_props: the dict of key value props
  367. output: the expected output
  368. """
  369. assert format.format_props(*single_props, **key_value_props) == output
  370. @pytest.mark.parametrize(
  371. "input,output",
  372. [
  373. (EventHandler(fn=mock_event), ("", "mock_event")),
  374. ],
  375. )
  376. def test_get_handler_parts(input, output):
  377. assert format.get_event_handler_parts(input) == output
  378. @pytest.mark.parametrize(
  379. "input,output",
  380. [
  381. (TestState.do_something, "test_state.do_something"),
  382. (ChildState.change_both, "test_state.child_state.change_both"),
  383. (
  384. GrandchildState.do_nothing,
  385. "test_state.child_state.grandchild_state.do_nothing",
  386. ),
  387. ],
  388. )
  389. def test_format_event_handler(input, output):
  390. """Test formatting an event handler.
  391. Args:
  392. input: The event handler input.
  393. output: The expected output.
  394. """
  395. assert format.format_event_handler(input) == output # type: ignore
  396. @pytest.mark.parametrize(
  397. "input,output",
  398. [
  399. (EventSpec(handler=EventHandler(fn=mock_event)), 'Event("mock_event", {})'),
  400. ],
  401. )
  402. def test_format_event(input, output):
  403. assert format.format_event(input) == output
  404. @pytest.mark.parametrize(
  405. "input,output",
  406. [
  407. (
  408. EventChain(
  409. events=[
  410. EventSpec(handler=EventHandler(fn=mock_event)),
  411. EventSpec(handler=EventHandler(fn=mock_event)),
  412. ],
  413. args_spec=None,
  414. ),
  415. 'addEvents([Event("mock_event", {}),Event("mock_event", {})])',
  416. ),
  417. (
  418. EventChain(
  419. events=[
  420. EventSpec(handler=EventHandler(fn=mock_event)),
  421. EventSpec(handler=EventHandler(fn=mock_event)),
  422. ],
  423. args_spec=lambda e0: [e0],
  424. ),
  425. 'addEvents([Event("mock_event", {}),Event("mock_event", {})])',
  426. ),
  427. ],
  428. )
  429. def test_format_event_chain(input, output):
  430. assert format.format_event_chain(input) == output
  431. @pytest.mark.parametrize(
  432. "input,output",
  433. [
  434. ({"query": {"k1": 1, "k2": 2}}, {"k1": 1, "k2": 2}),
  435. ({"query": {"k1": 1, "k-2": 2}}, {"k1": 1, "k_2": 2}),
  436. ],
  437. )
  438. def test_format_query_params(input, output):
  439. assert format.format_query_params(input) == output
  440. formatted_router = {
  441. "session": {"client_token": "", "client_ip": "", "session_id": ""},
  442. "headers": {
  443. "host": "",
  444. "origin": "",
  445. "upgrade": "",
  446. "connection": "",
  447. "pragma": "",
  448. "cache_control": "",
  449. "user_agent": "",
  450. "sec_websocket_version": "",
  451. "sec_websocket_key": "",
  452. "sec_websocket_extensions": "",
  453. "accept_encoding": "",
  454. "accept_language": "",
  455. },
  456. "page": {
  457. "host": "",
  458. "path": "",
  459. "raw_path": "",
  460. "full_path": "",
  461. "full_raw_path": "",
  462. "params": {},
  463. },
  464. }
  465. @pytest.mark.parametrize(
  466. "input, output",
  467. [
  468. (
  469. TestState().dict(), # type: ignore
  470. {
  471. TestState.get_full_name(): {
  472. "array": [1, 2, 3.14],
  473. "complex": {
  474. 1: {"prop1": 42, "prop2": "hello"},
  475. 2: {"prop1": 42, "prop2": "hello"},
  476. },
  477. "dt": "1989-11-09 18:53:00+01:00",
  478. "fig": [],
  479. "key": "",
  480. "map_key": "a",
  481. "mapping": {"a": [1, 2, 3], "b": [4, 5, 6]},
  482. "num1": 0,
  483. "num2": 3.14,
  484. "obj": {"prop1": 42, "prop2": "hello"},
  485. "sum": 3.14,
  486. "upper": "",
  487. "router": formatted_router,
  488. },
  489. ChildState.get_full_name(): {
  490. "count": 23,
  491. "value": "",
  492. },
  493. ChildState2.get_full_name(): {"value": ""},
  494. GrandchildState.get_full_name(): {"value2": ""},
  495. },
  496. ),
  497. (
  498. DateTimeState().dict(),
  499. {
  500. DateTimeState.get_full_name(): {
  501. "d": "1989-11-09",
  502. "dt": "1989-11-09 18:53:00+01:00",
  503. "t": "18:53:00+01:00",
  504. "td": "11 days, 0:11:00",
  505. "router": formatted_router,
  506. },
  507. },
  508. ),
  509. ],
  510. )
  511. def test_format_state(input, output):
  512. """Test that the format state is correct.
  513. Args:
  514. input: The state to format.
  515. output: The expected formatted state.
  516. """
  517. assert format.format_state(input) == output
  518. @pytest.mark.parametrize(
  519. "input,output",
  520. [
  521. ("input1", "ref_input1"),
  522. ("input 1", "ref_input_1"),
  523. ("input-1", "ref_input_1"),
  524. ("input_1", "ref_input_1"),
  525. ("a long test?1! name", "ref_a_long_test_1_name"),
  526. ],
  527. )
  528. def test_format_ref(input, output):
  529. """Test formatting a ref.
  530. Args:
  531. input: The name to format.
  532. output: The expected formatted name.
  533. """
  534. assert format.format_ref(input) == output
  535. @pytest.mark.parametrize(
  536. "input,output",
  537. [
  538. (("my_array", None), "refs_my_array"),
  539. (("my_array", Var.create(0)), "refs_my_array[0]"),
  540. (("my_array", Var.create(1)), "refs_my_array[1]"),
  541. ],
  542. )
  543. def test_format_array_ref(input, output):
  544. assert format.format_array_ref(input[0], input[1]) == output
  545. @pytest.mark.parametrize(
  546. "input,output",
  547. [
  548. ("/foo", [("foo", "/foo")]),
  549. ("/foo/bar", [("foo", "/foo"), ("bar", "/foo/bar")]),
  550. (
  551. "/foo/bar/baz",
  552. [("foo", "/foo"), ("bar", "/foo/bar"), ("baz", "/foo/bar/baz")],
  553. ),
  554. ],
  555. )
  556. def test_format_breadcrumbs(input, output):
  557. assert format.format_breadcrumbs(input) == output
  558. @pytest.mark.parametrize(
  559. "input, output",
  560. [
  561. ("library@^0.1.2", "library"),
  562. ("library", "library"),
  563. ("@library@^0.1.2", "@library"),
  564. ("@library", "@library"),
  565. ],
  566. )
  567. def test_format_library_name(input: str, output: str):
  568. """Test formating a library name to remove the @version part.
  569. Args:
  570. input: the input string.
  571. output: the output string.
  572. """
  573. assert format.format_library_name(input) == output
  574. @pytest.mark.parametrize(
  575. "input,output",
  576. [
  577. (None, "null"),
  578. (True, "true"),
  579. (1, "1"),
  580. (1.0, "1.0"),
  581. ([], "[]"),
  582. ([1, 2, 3], "[1, 2, 3]"),
  583. ({}, "{}"),
  584. ({"k1": False, "k2": True}, '{"k1": false, "k2": true}'),
  585. (
  586. [datetime.timedelta(1, 1, 1), datetime.timedelta(1, 1, 2)],
  587. '["1 day, 0:00:01.000001", "1 day, 0:00:01.000002"]',
  588. ),
  589. (
  590. {"key1": datetime.timedelta(1, 1, 1), "key2": datetime.timedelta(1, 1, 2)},
  591. '{"key1": "1 day, 0:00:01.000001", "key2": "1 day, 0:00:01.000002"}',
  592. ),
  593. ],
  594. )
  595. def test_json_dumps(input, output):
  596. assert format.json_dumps(input) == output