test_format.py 23 KB

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