test_format.py 25 KB

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