test_format.py 17 KB

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