test_utils.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. import os
  2. import typing
  3. from pathlib import Path
  4. from typing import Any, List, Union
  5. import pytest
  6. import typer
  7. from packaging import version
  8. from reflex import constants
  9. from reflex.base import Base
  10. from reflex.components.tags import Tag
  11. from reflex.event import EVENT_ARG, EventChain, EventHandler, EventSpec
  12. from reflex.state import State
  13. from reflex.style import Style
  14. from reflex.utils import (
  15. build,
  16. format,
  17. imports,
  18. prerequisites,
  19. types,
  20. )
  21. from reflex.utils import exec as utils_exec
  22. from reflex.vars import BaseVar, Var
  23. def mock_event(arg):
  24. pass
  25. def get_above_max_version():
  26. """Get the 1 version above the max required bun version.
  27. Returns:
  28. max bun version plus one.
  29. """
  30. semantic_version_list = constants.BUN_VERSION.split(".")
  31. semantic_version_list[-1] = str(int(semantic_version_list[-1]) + 1) # type: ignore
  32. return ".".join(semantic_version_list)
  33. V055 = version.parse("0.5.5")
  34. V059 = version.parse("0.5.9")
  35. V056 = version.parse("0.5.6")
  36. VMAXPLUS1 = version.parse(get_above_max_version())
  37. class ExampleTestState(State):
  38. """Test state class."""
  39. def test_event_handler(self):
  40. """Test event handler."""
  41. pass
  42. def test_func():
  43. pass
  44. @pytest.mark.parametrize(
  45. "input,output",
  46. [
  47. ("", ""),
  48. ("hello", "hello"),
  49. ("Hello", "hello"),
  50. ("camelCase", "camel_case"),
  51. ("camelTwoHumps", "camel_two_humps"),
  52. ("_start_with_underscore", "_start_with_underscore"),
  53. ("__start_with_double_underscore", "__start_with_double_underscore"),
  54. ],
  55. )
  56. def test_to_snake_case(input: str, output: str):
  57. """Test converting strings to snake case.
  58. Args:
  59. input: The input string.
  60. output: The expected output string.
  61. """
  62. assert format.to_snake_case(input) == output
  63. @pytest.mark.parametrize(
  64. "input,output",
  65. [
  66. ("", ""),
  67. ("hello", "hello"),
  68. ("Hello", "Hello"),
  69. ("snake_case", "snakeCase"),
  70. ("snake_case_two", "snakeCaseTwo"),
  71. ],
  72. )
  73. def test_to_camel_case(input: str, output: str):
  74. """Test converting strings to camel case.
  75. Args:
  76. input: The input string.
  77. output: The expected output string.
  78. """
  79. assert format.to_camel_case(input) == output
  80. @pytest.mark.parametrize(
  81. "input,output",
  82. [
  83. ("", ""),
  84. ("hello", "Hello"),
  85. ("Hello", "Hello"),
  86. ("snake_case", "SnakeCase"),
  87. ("snake_case_two", "SnakeCaseTwo"),
  88. ],
  89. )
  90. def test_to_title_case(input: str, output: str):
  91. """Test converting strings to title case.
  92. Args:
  93. input: The input string.
  94. output: The expected output string.
  95. """
  96. assert format.to_title_case(input) == output
  97. @pytest.mark.parametrize(
  98. "input,output",
  99. [
  100. ("{", "}"),
  101. ("(", ")"),
  102. ("[", "]"),
  103. ("<", ">"),
  104. ('"', '"'),
  105. ("'", "'"),
  106. ],
  107. )
  108. def test_get_close_char(input: str, output: str):
  109. """Test getting the close character for a given open character.
  110. Args:
  111. input: The open character.
  112. output: The expected close character.
  113. """
  114. assert format.get_close_char(input) == output
  115. @pytest.mark.parametrize(
  116. "text,open,expected",
  117. [
  118. ("", "{", False),
  119. ("{wrap}", "{", True),
  120. ("{wrap", "{", False),
  121. ("{wrap}", "(", False),
  122. ("(wrap)", "(", True),
  123. ],
  124. )
  125. def test_is_wrapped(text: str, open: str, expected: bool):
  126. """Test checking if a string is wrapped in the given open and close characters.
  127. Args:
  128. text: The text to check.
  129. open: The open character.
  130. expected: Whether the text is wrapped.
  131. """
  132. assert format.is_wrapped(text, open) == expected
  133. @pytest.mark.parametrize(
  134. "text,open,check_first,num,expected",
  135. [
  136. ("", "{", True, 1, "{}"),
  137. ("wrap", "{", True, 1, "{wrap}"),
  138. ("wrap", "(", True, 1, "(wrap)"),
  139. ("wrap", "(", True, 2, "((wrap))"),
  140. ("(wrap)", "(", True, 1, "(wrap)"),
  141. ("{wrap}", "{", True, 2, "{wrap}"),
  142. ("(wrap)", "{", True, 1, "{(wrap)}"),
  143. ("(wrap)", "(", False, 1, "((wrap))"),
  144. ],
  145. )
  146. def test_wrap(text: str, open: str, expected: str, check_first: bool, num: int):
  147. """Test wrapping a string.
  148. Args:
  149. text: The text to wrap.
  150. open: The open character.
  151. expected: The expected output string.
  152. check_first: Whether to check if the text is already wrapped.
  153. num: The number of times to wrap the text.
  154. """
  155. assert format.wrap(text, open, check_first=check_first, num=num) == expected
  156. @pytest.mark.parametrize(
  157. "text,indent_level,expected",
  158. [
  159. ("", 2, ""),
  160. ("hello", 2, "hello"),
  161. ("hello\nworld", 2, " hello\n world\n"),
  162. ("hello\nworld", 4, " hello\n world\n"),
  163. (" hello\n world", 2, " hello\n world\n"),
  164. ],
  165. )
  166. def test_indent(text: str, indent_level: int, expected: str, windows_platform: bool):
  167. """Test indenting a string.
  168. Args:
  169. text: The text to indent.
  170. indent_level: The number of spaces to indent by.
  171. expected: The expected output string.
  172. windows_platform: Whether the system is windows.
  173. """
  174. assert format.indent(text, indent_level) == (
  175. expected.replace("\n", "\r\n") if windows_platform else expected
  176. )
  177. @pytest.mark.parametrize(
  178. "condition,true_value,false_value,expected",
  179. [
  180. ("cond", "<C1>", '""', '{isTrue(cond) ? <C1> : ""}'),
  181. ("cond", "<C1>", "<C2>", "{isTrue(cond) ? <C1> : <C2>}"),
  182. ],
  183. )
  184. def test_format_cond(condition: str, true_value: str, false_value: str, expected: str):
  185. """Test formatting a cond.
  186. Args:
  187. condition: The condition to check.
  188. true_value: The value to return if the condition is true.
  189. false_value: The value to return if the condition is false.
  190. expected: The expected output string.
  191. """
  192. assert format.format_cond(condition, true_value, false_value) == expected
  193. def test_merge_imports():
  194. """Test that imports are merged correctly."""
  195. d1 = {"react": {"Component"}}
  196. d2 = {"react": {"Component"}, "react-dom": {"render"}}
  197. d = imports.merge_imports(d1, d2)
  198. assert set(d.keys()) == {"react", "react-dom"}
  199. assert set(d["react"]) == {"Component"}
  200. assert set(d["react-dom"]) == {"render"}
  201. @pytest.mark.parametrize(
  202. "cls,expected",
  203. [
  204. (str, False),
  205. (int, False),
  206. (float, False),
  207. (bool, False),
  208. (List, True),
  209. (List[int], True),
  210. ],
  211. )
  212. def test_is_generic_alias(cls: type, expected: bool):
  213. """Test checking if a class is a GenericAlias.
  214. Args:
  215. cls: The class to check.
  216. expected: Whether the class is a GenericAlias.
  217. """
  218. assert types.is_generic_alias(cls) == expected
  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. "prop,formatted",
  246. [
  247. ("string", '"string"'),
  248. ("{wrapped_string}", "{wrapped_string}"),
  249. (True, "{true}"),
  250. (False, "{false}"),
  251. (123, "{123}"),
  252. (3.14, "{3.14}"),
  253. ([1, 2, 3], "{[1, 2, 3]}"),
  254. (["a", "b", "c"], '{["a", "b", "c"]}'),
  255. ({"a": 1, "b": 2, "c": 3}, '{{"a": 1, "b": 2, "c": 3}}'),
  256. ({"a": 'foo "bar" baz'}, r'{{"a": "foo \"bar\" baz"}}'),
  257. (
  258. {
  259. "a": 'foo "{ "bar" }" baz',
  260. "b": BaseVar(name="val", type_="str"),
  261. },
  262. r'{{"a": "foo \"{ \"bar\" }\" baz", "b": val}}',
  263. ),
  264. (
  265. EventChain(events=[EventSpec(handler=EventHandler(fn=mock_event))]),
  266. '{_e => Event([E("mock_event", {})], _e)}',
  267. ),
  268. (
  269. EventChain(
  270. events=[
  271. EventSpec(
  272. handler=EventHandler(fn=mock_event),
  273. args=((Var.create_safe("arg"), EVENT_ARG.target.value),),
  274. )
  275. ]
  276. ),
  277. '{_e => Event([E("mock_event", {arg:_e.target.value})], _e)}',
  278. ),
  279. ({"a": "red", "b": "blue"}, '{{"a": "red", "b": "blue"}}'),
  280. (BaseVar(name="var", type_="int"), "{var}"),
  281. (
  282. BaseVar(
  283. name="_",
  284. type_=Any,
  285. state="",
  286. is_local=True,
  287. is_string=False,
  288. ),
  289. "{_}",
  290. ),
  291. (BaseVar(name='state.colors["a"]', type_="str"), '{state.colors["a"]}'),
  292. ({"a": BaseVar(name="val", type_="str")}, '{{"a": val}}'),
  293. ({"a": BaseVar(name='"val"', type_="str")}, '{{"a": "val"}}'),
  294. (
  295. {"a": BaseVar(name='state.colors["val"]', type_="str")},
  296. '{{"a": state.colors["val"]}}',
  297. ),
  298. # tricky real-world case from markdown component
  299. (
  300. {
  301. "h1": f"{{({{node, ...props}}) => <Heading {{...props}} {''.join(Tag(name='', props=Style({'as_': 'h1'})).format_props())} />}}"
  302. },
  303. '{{"h1": ({node, ...props}) => <Heading {...props} as={`h1`} />}}',
  304. ),
  305. ],
  306. )
  307. def test_format_prop(prop: Var, formatted: str):
  308. """Test that the formatted value of an prop is correct.
  309. Args:
  310. prop: The prop to test.
  311. formatted: The expected formatted value.
  312. """
  313. assert format.format_prop(prop) == formatted
  314. def test_validate_invalid_bun_path(mocker):
  315. """Test that an error is thrown when a custom specified bun path is not valid
  316. or does not exist.
  317. Args:
  318. mocker: Pytest mocker object.
  319. """
  320. mock = mocker.Mock()
  321. mocker.patch.object(mock, "bun_path", return_value="/mock/path")
  322. mocker.patch("reflex.utils.prerequisites.get_config", mock)
  323. mocker.patch("reflex.utils.prerequisites.get_bun_version", return_value=None)
  324. with pytest.raises(typer.Exit):
  325. prerequisites.validate_bun()
  326. def test_validate_bun_path_incompatible_version(mocker):
  327. """Test that an error is thrown when the bun version does not meet minimum requirements.
  328. Args:
  329. mocker: Pytest mocker object.
  330. """
  331. mock = mocker.Mock()
  332. mocker.patch.object(mock, "bun_path", return_value="/mock/path")
  333. mocker.patch("reflex.utils.prerequisites.get_config", mock)
  334. mocker.patch(
  335. "reflex.utils.prerequisites.get_bun_version",
  336. return_value=version.parse("0.6.5"),
  337. )
  338. with pytest.raises(typer.Exit):
  339. prerequisites.validate_bun()
  340. def test_remove_existing_bun_installation(mocker):
  341. """Test that existing bun installation is removed.
  342. Args:
  343. mocker: Pytest mocker.
  344. """
  345. mocker.patch("reflex.utils.prerequisites.os.path.exists", return_value=True)
  346. rm = mocker.patch("reflex.utils.prerequisites.path_ops.rm", mocker.Mock())
  347. prerequisites.remove_existing_bun_installation()
  348. rm.assert_called_once()
  349. def test_setup_frontend(tmp_path, mocker):
  350. """Test checking if assets content have been
  351. copied into the .web/public folder.
  352. Args:
  353. tmp_path: root path of test case data directory
  354. mocker: mocker object to allow mocking
  355. """
  356. web_public_folder = tmp_path / ".web" / "public"
  357. assets = tmp_path / "assets"
  358. assets.mkdir()
  359. (assets / "favicon.ico").touch()
  360. mocker.patch("reflex.utils.prerequisites.install_frontend_packages")
  361. mocker.patch("reflex.utils.build.set_env_json")
  362. build.setup_frontend(tmp_path, disable_telemetry=False)
  363. assert web_public_folder.exists()
  364. assert (web_public_folder / "favicon.ico").exists()
  365. @pytest.mark.parametrize(
  366. "input, output",
  367. [
  368. ("_hidden", True),
  369. ("not_hidden", False),
  370. ("__dundermethod__", False),
  371. ],
  372. )
  373. def test_is_backend_variable(input, output):
  374. assert types.is_backend_variable(input) == output
  375. @pytest.mark.parametrize(
  376. "cls, cls_check, expected",
  377. [
  378. (int, int, True),
  379. (int, float, False),
  380. (int, Union[int, float], True),
  381. (float, Union[int, float], True),
  382. (str, Union[int, float], False),
  383. (List[int], List[int], True),
  384. (List[int], List[float], True),
  385. (Union[int, float], Union[int, float], False),
  386. (Union[int, Var[int]], Var[int], False),
  387. (int, Any, True),
  388. (Any, Any, True),
  389. (Union[int, float], Any, True),
  390. ],
  391. )
  392. def test_issubclass(cls: type, cls_check: type, expected: bool):
  393. assert types._issubclass(cls, cls_check) == expected
  394. @pytest.mark.parametrize(
  395. "app_name,expected_config_name",
  396. [
  397. ("appname", "AppnameConfig"),
  398. ("app_name", "AppnameConfig"),
  399. ("app-name", "AppnameConfig"),
  400. ("appname2.io", "AppnameioConfig"),
  401. ],
  402. )
  403. def test_create_config(app_name, expected_config_name, mocker):
  404. """Test templates.RXCONFIG is formatted with correct app name and config class name.
  405. Args:
  406. app_name: App name.
  407. expected_config_name: Expected config name.
  408. mocker: Mocker object.
  409. """
  410. mocker.patch("builtins.open")
  411. tmpl_mock = mocker.patch("reflex.compiler.templates.RXCONFIG")
  412. prerequisites.create_config(app_name)
  413. tmpl_mock.render.assert_called_with(
  414. app_name=app_name, config_name=expected_config_name
  415. )
  416. @pytest.fixture
  417. def tmp_working_dir(tmp_path):
  418. """Create a temporary directory and chdir to it.
  419. After the test executes, chdir back to the original working directory.
  420. Args:
  421. tmp_path: pytest tmp_path fixture creates per-test temp dir
  422. Yields:
  423. subdirectory of tmp_path which is now the current working directory.
  424. """
  425. old_pwd = Path(".").resolve()
  426. working_dir = tmp_path / "working_dir"
  427. working_dir.mkdir()
  428. os.chdir(working_dir)
  429. yield working_dir
  430. os.chdir(old_pwd)
  431. def test_create_config_e2e(tmp_working_dir):
  432. """Create a new config file, exec it, and make assertions about the config.
  433. Args:
  434. tmp_working_dir: a new directory that is the current working directory
  435. for the duration of the test.
  436. """
  437. app_name = "e2e"
  438. prerequisites.create_config(app_name)
  439. eval_globals = {}
  440. exec((tmp_working_dir / constants.CONFIG_FILE).read_text(), eval_globals)
  441. config = eval_globals["config"]
  442. assert config.app_name == app_name
  443. @pytest.mark.parametrize(
  444. "name,expected",
  445. [
  446. ("input1", "ref_input1"),
  447. ("input 1", "ref_input_1"),
  448. ("input-1", "ref_input_1"),
  449. ("input_1", "ref_input_1"),
  450. ("a long test?1! name", "ref_a_long_test_1_name"),
  451. ],
  452. )
  453. def test_format_ref(name, expected):
  454. """Test formatting a ref.
  455. Args:
  456. name: The name to format.
  457. expected: The expected formatted name.
  458. """
  459. assert format.format_ref(name) == expected
  460. class DataFrame:
  461. """A Fake pandas DataFrame class."""
  462. pass
  463. @pytest.mark.parametrize(
  464. "class_type,expected",
  465. [
  466. (list, False),
  467. (int, False),
  468. (dict, False),
  469. (DataFrame, True),
  470. (typing.Any, False),
  471. (typing.List, False),
  472. ],
  473. )
  474. def test_is_dataframe(class_type, expected):
  475. """Test that a type name is DataFrame.
  476. Args:
  477. class_type: the class type.
  478. expected: whether type name is DataFrame
  479. """
  480. assert types.is_dataframe(class_type) == expected
  481. @pytest.mark.parametrize("gitignore_exists", [True, False])
  482. def test_initialize_non_existent_gitignore(tmp_path, mocker, gitignore_exists):
  483. """Test that the generated .gitignore_file file on reflex init contains the correct file
  484. names with correct formatting.
  485. Args:
  486. tmp_path: The root test path.
  487. mocker: The mock object.
  488. gitignore_exists: Whether a gitignore file exists in the root dir.
  489. """
  490. expected = constants.DEFAULT_GITIGNORE.copy()
  491. mocker.patch("reflex.constants.GITIGNORE_FILE", tmp_path / ".gitignore")
  492. gitignore_file = tmp_path / ".gitignore"
  493. if gitignore_exists:
  494. gitignore_file.touch()
  495. gitignore_file.write_text(
  496. """*.db
  497. __pycache__/
  498. """
  499. )
  500. prerequisites.initialize_gitignore()
  501. assert gitignore_file.exists()
  502. file_content = [
  503. line.strip() for line in gitignore_file.open().read().splitlines() if line
  504. ]
  505. assert set(file_content) - expected == set()
  506. def test_app_default_name(tmp_path, mocker):
  507. """Test that an error is raised if the app name is reflex.
  508. Args:
  509. tmp_path: Test working dir.
  510. mocker: Pytest mocker object.
  511. """
  512. reflex = tmp_path / "reflex"
  513. reflex.mkdir()
  514. mocker.patch("reflex.utils.prerequisites.os.getcwd", return_value=str(reflex))
  515. with pytest.raises(typer.Exit):
  516. prerequisites.get_default_app_name()
  517. def test_node_install_windows(tmp_path, mocker):
  518. """Require user to install node manually for windows if node is not installed.
  519. Args:
  520. tmp_path: Test working dir.
  521. mocker: Pytest mocker object.
  522. """
  523. fnm_root_path = tmp_path / "reflex" / "fnm"
  524. fnm_exe = fnm_root_path / "fnm.exe"
  525. mocker.patch("reflex.utils.prerequisites.constants.FNM_DIR", fnm_root_path)
  526. mocker.patch("reflex.utils.prerequisites.constants.FNM_EXE", fnm_exe)
  527. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", True)
  528. mocker.patch("reflex.utils.processes.new_process")
  529. mocker.patch("reflex.utils.processes.stream_logs")
  530. class Resp(Base):
  531. status_code = 200
  532. text = "test"
  533. mocker.patch("httpx.stream", return_value=Resp())
  534. download = mocker.patch("reflex.utils.prerequisites.download_and_extract_fnm_zip")
  535. mocker.patch("reflex.utils.prerequisites.zipfile.ZipFile")
  536. mocker.patch("reflex.utils.prerequisites.path_ops.rm")
  537. prerequisites.install_node()
  538. assert fnm_root_path.exists()
  539. download.assert_called_once()
  540. @pytest.mark.parametrize(
  541. "machine, system",
  542. [
  543. ("x64", "Darwin"),
  544. ("arm64", "Darwin"),
  545. ("x64", "Windows"),
  546. ("arm64", "Windows"),
  547. ("armv7", "Linux"),
  548. ("armv8-a", "Linux"),
  549. ("armv8.1-a", "Linux"),
  550. ("armv8.2-a", "Linux"),
  551. ("armv8.3-a", "Linux"),
  552. ("armv8.4-a", "Linux"),
  553. ("aarch64", "Linux"),
  554. ("aarch32", "Linux"),
  555. ],
  556. )
  557. def test_node_install_unix(tmp_path, mocker, machine, system):
  558. fnm_root_path = tmp_path / "reflex" / "fnm"
  559. fnm_exe = fnm_root_path / "fnm"
  560. mocker.patch("reflex.utils.prerequisites.constants.FNM_DIR", fnm_root_path)
  561. mocker.patch("reflex.utils.prerequisites.constants.FNM_EXE", fnm_exe)
  562. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
  563. mocker.patch("reflex.utils.prerequisites.platform.machine", return_value=machine)
  564. mocker.patch("reflex.utils.prerequisites.platform.system", return_value=system)
  565. class Resp(Base):
  566. status_code = 200
  567. text = "test"
  568. mocker.patch("httpx.stream", return_value=Resp())
  569. download = mocker.patch("reflex.utils.prerequisites.download_and_extract_fnm_zip")
  570. process = mocker.patch("reflex.utils.processes.new_process")
  571. chmod = mocker.patch("reflex.utils.prerequisites.os.chmod")
  572. mocker.patch("reflex.utils.processes.stream_logs")
  573. prerequisites.install_node()
  574. assert fnm_root_path.exists()
  575. download.assert_called_once()
  576. if system == "Darwin" and machine == "arm64":
  577. process.assert_called_with(
  578. [
  579. fnm_exe,
  580. "install",
  581. "--arch=arm64",
  582. constants.NODE_VERSION,
  583. "--fnm-dir",
  584. fnm_root_path,
  585. ]
  586. )
  587. else:
  588. process.assert_called_with(
  589. [fnm_exe, "install", constants.NODE_VERSION, "--fnm-dir", fnm_root_path]
  590. )
  591. chmod.assert_called_once()
  592. def test_bun_install_without_unzip(mocker):
  593. """Test that an error is thrown when installing bun with unzip not installed.
  594. Args:
  595. mocker: Pytest mocker object.
  596. """
  597. mocker.patch("reflex.utils.path_ops.which", return_value=None)
  598. mocker.patch("os.path.exists", return_value=False)
  599. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
  600. with pytest.raises(FileNotFoundError):
  601. prerequisites.install_bun()
  602. @pytest.mark.parametrize("is_windows", [True, False])
  603. def test_create_reflex_dir(mocker, is_windows):
  604. """Test that a reflex directory is created on initializing frontend
  605. dependencies.
  606. Args:
  607. mocker: Pytest mocker object.
  608. is_windows: Whether platform is windows.
  609. """
  610. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", is_windows)
  611. mocker.patch("reflex.utils.prerequisites.processes.run_concurrently", mocker.Mock())
  612. mocker.patch("reflex.utils.prerequisites.initialize_web_directory", mocker.Mock())
  613. mocker.patch("reflex.utils.processes.run_concurrently")
  614. mocker.patch("reflex.utils.prerequisites.validate_bun")
  615. create_cmd = mocker.patch(
  616. "reflex.utils.prerequisites.path_ops.mkdir", mocker.Mock()
  617. )
  618. prerequisites.initialize_frontend_dependencies()
  619. assert create_cmd.called
  620. def test_output_system_info(mocker):
  621. """Make sure reflex does not crash dumping system info.
  622. Args:
  623. mocker: Pytest mocker object.
  624. This test makes no assertions about the output, other than it executes
  625. without crashing.
  626. """
  627. mocker.patch("reflex.utils.console.LOG_LEVEL", constants.LogLevel.DEBUG)
  628. utils_exec.output_system_info()
  629. @pytest.mark.parametrize(
  630. "callable", [ExampleTestState.test_event_handler, test_func, lambda x: x]
  631. )
  632. def test_style_prop_with_event_handler_value(callable):
  633. """Test that a type error is thrown when a style prop has a
  634. callable as value.
  635. Args:
  636. callable: The callable function or event handler.
  637. """
  638. style = {
  639. "color": EventHandler(fn=callable)
  640. if type(callable) != EventHandler
  641. else callable
  642. }
  643. with pytest.raises(TypeError):
  644. format.format_dict(style) # type: ignore