test_format.py 21 KB

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