test_format.py 24 KB

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