test_format.py 21 KB

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