test_utils.py 22 KB

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