test_utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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.utils import (
  11. build,
  12. format,
  13. imports,
  14. prerequisites,
  15. types,
  16. )
  17. from reflex.utils import exec as utils_exec
  18. from reflex.vars import Var
  19. def get_above_max_version():
  20. """Get the 1 version above the max required bun version.
  21. Returns:
  22. max bun version plus one.
  23. """
  24. semantic_version_list = constants.BUN_VERSION.split(".")
  25. semantic_version_list[-1] = str(int(semantic_version_list[-1]) + 1) # type: ignore
  26. return ".".join(semantic_version_list)
  27. V055 = version.parse("0.5.5")
  28. V059 = version.parse("0.5.9")
  29. V056 = version.parse("0.5.6")
  30. VMAXPLUS1 = version.parse(get_above_max_version())
  31. @pytest.mark.parametrize(
  32. "input,output",
  33. [
  34. ("", ""),
  35. ("hello", "hello"),
  36. ("Hello", "hello"),
  37. ("camelCase", "camel_case"),
  38. ("camelTwoHumps", "camel_two_humps"),
  39. ("_start_with_underscore", "_start_with_underscore"),
  40. ("__start_with_double_underscore", "__start_with_double_underscore"),
  41. ],
  42. )
  43. def test_to_snake_case(input: str, output: str):
  44. """Test converting strings to snake case.
  45. Args:
  46. input: The input string.
  47. output: The expected output string.
  48. """
  49. assert format.to_snake_case(input) == output
  50. @pytest.mark.parametrize(
  51. "input,output",
  52. [
  53. ("", ""),
  54. ("hello", "hello"),
  55. ("Hello", "Hello"),
  56. ("snake_case", "snakeCase"),
  57. ("snake_case_two", "snakeCaseTwo"),
  58. ],
  59. )
  60. def test_to_camel_case(input: str, output: str):
  61. """Test converting strings to camel case.
  62. Args:
  63. input: The input string.
  64. output: The expected output string.
  65. """
  66. assert format.to_camel_case(input) == output
  67. @pytest.mark.parametrize(
  68. "input,output",
  69. [
  70. ("", ""),
  71. ("hello", "Hello"),
  72. ("Hello", "Hello"),
  73. ("snake_case", "SnakeCase"),
  74. ("snake_case_two", "SnakeCaseTwo"),
  75. ],
  76. )
  77. def test_to_title_case(input: str, output: str):
  78. """Test converting strings to title case.
  79. Args:
  80. input: The input string.
  81. output: The expected output string.
  82. """
  83. assert format.to_title_case(input) == output
  84. @pytest.mark.parametrize(
  85. "input,output",
  86. [
  87. ("{", "}"),
  88. ("(", ")"),
  89. ("[", "]"),
  90. ("<", ">"),
  91. ('"', '"'),
  92. ("'", "'"),
  93. ],
  94. )
  95. def test_get_close_char(input: str, output: str):
  96. """Test getting the close character for a given open character.
  97. Args:
  98. input: The open character.
  99. output: The expected close character.
  100. """
  101. assert format.get_close_char(input) == output
  102. @pytest.mark.parametrize(
  103. "text,open,expected",
  104. [
  105. ("", "{", False),
  106. ("{wrap}", "{", True),
  107. ("{wrap", "{", False),
  108. ("{wrap}", "(", False),
  109. ("(wrap)", "(", True),
  110. ],
  111. )
  112. def test_is_wrapped(text: str, open: str, expected: bool):
  113. """Test checking if a string is wrapped in the given open and close characters.
  114. Args:
  115. text: The text to check.
  116. open: The open character.
  117. expected: Whether the text is wrapped.
  118. """
  119. assert format.is_wrapped(text, open) == expected
  120. @pytest.mark.parametrize(
  121. "text,open,check_first,num,expected",
  122. [
  123. ("", "{", True, 1, "{}"),
  124. ("wrap", "{", True, 1, "{wrap}"),
  125. ("wrap", "(", True, 1, "(wrap)"),
  126. ("wrap", "(", True, 2, "((wrap))"),
  127. ("(wrap)", "(", True, 1, "(wrap)"),
  128. ("{wrap}", "{", True, 2, "{wrap}"),
  129. ("(wrap)", "{", True, 1, "{(wrap)}"),
  130. ("(wrap)", "(", False, 1, "((wrap))"),
  131. ],
  132. )
  133. def test_wrap(text: str, open: str, expected: str, check_first: bool, num: int):
  134. """Test wrapping a string.
  135. Args:
  136. text: The text to wrap.
  137. open: The open character.
  138. expected: The expected output string.
  139. check_first: Whether to check if the text is already wrapped.
  140. num: The number of times to wrap the text.
  141. """
  142. assert format.wrap(text, open, check_first=check_first, num=num) == expected
  143. @pytest.mark.parametrize(
  144. "text,indent_level,expected",
  145. [
  146. ("", 2, ""),
  147. ("hello", 2, "hello"),
  148. ("hello\nworld", 2, " hello\n world\n"),
  149. ("hello\nworld", 4, " hello\n world\n"),
  150. (" hello\n world", 2, " hello\n world\n"),
  151. ],
  152. )
  153. def test_indent(text: str, indent_level: int, expected: str, windows_platform: bool):
  154. """Test indenting a string.
  155. Args:
  156. text: The text to indent.
  157. indent_level: The number of spaces to indent by.
  158. expected: The expected output string.
  159. windows_platform: Whether the system is windows.
  160. """
  161. assert format.indent(text, indent_level) == (
  162. expected.replace("\n", "\r\n") if windows_platform else expected
  163. )
  164. @pytest.mark.parametrize(
  165. "condition,true_value,false_value,expected",
  166. [
  167. ("cond", "<C1>", '""', '{isTrue(cond) ? <C1> : ""}'),
  168. ("cond", "<C1>", "<C2>", "{isTrue(cond) ? <C1> : <C2>}"),
  169. ],
  170. )
  171. def test_format_cond(condition: str, true_value: str, false_value: str, expected: str):
  172. """Test formatting a cond.
  173. Args:
  174. condition: The condition to check.
  175. true_value: The value to return if the condition is true.
  176. false_value: The value to return if the condition is false.
  177. expected: The expected output string.
  178. """
  179. assert format.format_cond(condition, true_value, false_value) == expected
  180. def test_merge_imports():
  181. """Test that imports are merged correctly."""
  182. d1 = {"react": {"Component"}}
  183. d2 = {"react": {"Component"}, "react-dom": {"render"}}
  184. d = imports.merge_imports(d1, d2)
  185. assert set(d.keys()) == {"react", "react-dom"}
  186. assert set(d["react"]) == {"Component"}
  187. assert set(d["react-dom"]) == {"render"}
  188. @pytest.mark.parametrize(
  189. "cls,expected",
  190. [
  191. (str, False),
  192. (int, False),
  193. (float, False),
  194. (bool, False),
  195. (List, True),
  196. (List[int], True),
  197. ],
  198. )
  199. def test_is_generic_alias(cls: type, expected: bool):
  200. """Test checking if a class is a GenericAlias.
  201. Args:
  202. cls: The class to check.
  203. expected: Whether the class is a GenericAlias.
  204. """
  205. assert types.is_generic_alias(cls) == expected
  206. @pytest.mark.parametrize(
  207. "route,expected",
  208. [
  209. ("", "index"),
  210. ("/", "index"),
  211. ("custom-route", "custom-route"),
  212. ("custom-route/", "custom-route"),
  213. ("/custom-route", "custom-route"),
  214. ],
  215. )
  216. def test_format_route(route: str, expected: bool):
  217. """Test formatting a route.
  218. Args:
  219. route: The route to format.
  220. expected: The expected formatted route.
  221. """
  222. assert format.format_route(route) == expected
  223. def test_validate_invalid_bun_path(mocker):
  224. """Test that an error is thrown when a custom specified bun path is not valid
  225. or does not exist.
  226. Args:
  227. mocker: Pytest mocker object.
  228. """
  229. mock = mocker.Mock()
  230. mocker.patch.object(mock, "bun_path", return_value="/mock/path")
  231. mocker.patch("reflex.utils.prerequisites.get_config", mock)
  232. mocker.patch("reflex.utils.prerequisites.get_bun_version", return_value=None)
  233. with pytest.raises(typer.Exit):
  234. prerequisites.validate_bun()
  235. def test_validate_bun_path_incompatible_version(mocker):
  236. """Test that an error is thrown when the bun version does not meet minimum requirements.
  237. Args:
  238. mocker: Pytest mocker object.
  239. """
  240. mock = mocker.Mock()
  241. mocker.patch.object(mock, "bun_path", return_value="/mock/path")
  242. mocker.patch("reflex.utils.prerequisites.get_config", mock)
  243. mocker.patch(
  244. "reflex.utils.prerequisites.get_bun_version",
  245. return_value=version.parse("0.6.5"),
  246. )
  247. with pytest.raises(typer.Exit):
  248. prerequisites.validate_bun()
  249. def test_remove_existing_bun_installation(mocker):
  250. """Test that existing bun installation is removed.
  251. Args:
  252. mocker: Pytest mocker.
  253. """
  254. mocker.patch("reflex.utils.prerequisites.os.path.exists", return_value=True)
  255. rm = mocker.patch("reflex.utils.prerequisites.path_ops.rm", mocker.Mock())
  256. prerequisites.remove_existing_bun_installation()
  257. rm.assert_called_once()
  258. def test_setup_frontend(tmp_path, mocker):
  259. """Test checking if assets content have been
  260. copied into the .web/public folder.
  261. Args:
  262. tmp_path: root path of test case data directory
  263. mocker: mocker object to allow mocking
  264. """
  265. web_public_folder = tmp_path / ".web" / "public"
  266. assets = tmp_path / "assets"
  267. assets.mkdir()
  268. (assets / "favicon.ico").touch()
  269. mocker.patch("reflex.utils.prerequisites.install_frontend_packages")
  270. mocker.patch("reflex.utils.build.set_env_json")
  271. build.setup_frontend(tmp_path, disable_telemetry=False)
  272. assert web_public_folder.exists()
  273. assert (web_public_folder / "favicon.ico").exists()
  274. @pytest.mark.parametrize(
  275. "input, output",
  276. [
  277. ("_hidden", True),
  278. ("not_hidden", False),
  279. ("__dundermethod__", False),
  280. ],
  281. )
  282. def test_is_backend_variable(input, output):
  283. assert types.is_backend_variable(input) == output
  284. @pytest.mark.parametrize(
  285. "cls, cls_check, expected",
  286. [
  287. (int, int, True),
  288. (int, float, False),
  289. (int, Union[int, float], True),
  290. (float, Union[int, float], True),
  291. (str, Union[int, float], False),
  292. (List[int], List[int], True),
  293. (List[int], List[float], True),
  294. (Union[int, float], Union[int, float], False),
  295. (Union[int, Var[int]], Var[int], False),
  296. (int, Any, True),
  297. (Any, Any, True),
  298. (Union[int, float], Any, True),
  299. ],
  300. )
  301. def test_issubclass(cls: type, cls_check: type, expected: bool):
  302. assert types._issubclass(cls, cls_check) == expected
  303. @pytest.mark.parametrize(
  304. "app_name,expected_config_name",
  305. [
  306. ("appname", "AppnameConfig"),
  307. ("app_name", "AppnameConfig"),
  308. ("app-name", "AppnameConfig"),
  309. ("appname2.io", "AppnameioConfig"),
  310. ],
  311. )
  312. def test_create_config(app_name, expected_config_name, mocker):
  313. """Test templates.RXCONFIG is formatted with correct app name and config class name.
  314. Args:
  315. app_name: App name.
  316. expected_config_name: Expected config name.
  317. mocker: Mocker object.
  318. """
  319. mocker.patch("builtins.open")
  320. tmpl_mock = mocker.patch("reflex.compiler.templates.RXCONFIG")
  321. prerequisites.create_config(app_name)
  322. tmpl_mock.render.assert_called_with(
  323. app_name=app_name, config_name=expected_config_name
  324. )
  325. @pytest.fixture
  326. def tmp_working_dir(tmp_path):
  327. """Create a temporary directory and chdir to it.
  328. After the test executes, chdir back to the original working directory.
  329. Args:
  330. tmp_path: pytest tmp_path fixture creates per-test temp dir
  331. Yields:
  332. subdirectory of tmp_path which is now the current working directory.
  333. """
  334. old_pwd = Path(".").resolve()
  335. working_dir = tmp_path / "working_dir"
  336. working_dir.mkdir()
  337. os.chdir(working_dir)
  338. yield working_dir
  339. os.chdir(old_pwd)
  340. def test_create_config_e2e(tmp_working_dir):
  341. """Create a new config file, exec it, and make assertions about the config.
  342. Args:
  343. tmp_working_dir: a new directory that is the current working directory
  344. for the duration of the test.
  345. """
  346. app_name = "e2e"
  347. prerequisites.create_config(app_name)
  348. eval_globals = {}
  349. exec((tmp_working_dir / constants.CONFIG_FILE).read_text(), eval_globals)
  350. config = eval_globals["config"]
  351. assert config.app_name == app_name
  352. @pytest.mark.parametrize(
  353. "name,expected",
  354. [
  355. ("input1", "ref_input1"),
  356. ("input 1", "ref_input_1"),
  357. ("input-1", "ref_input_1"),
  358. ("input_1", "ref_input_1"),
  359. ("a long test?1! name", "ref_a_long_test_1_name"),
  360. ],
  361. )
  362. def test_format_ref(name, expected):
  363. """Test formatting a ref.
  364. Args:
  365. name: The name to format.
  366. expected: The expected formatted name.
  367. """
  368. assert format.format_ref(name) == expected
  369. class DataFrame:
  370. """A Fake pandas DataFrame class."""
  371. pass
  372. @pytest.mark.parametrize(
  373. "class_type,expected",
  374. [
  375. (list, False),
  376. (int, False),
  377. (dict, False),
  378. (DataFrame, True),
  379. (typing.Any, False),
  380. (typing.List, False),
  381. ],
  382. )
  383. def test_is_dataframe(class_type, expected):
  384. """Test that a type name is DataFrame.
  385. Args:
  386. class_type: the class type.
  387. expected: whether type name is DataFrame
  388. """
  389. assert types.is_dataframe(class_type) == expected
  390. @pytest.mark.parametrize("gitignore_exists", [True, False])
  391. def test_initialize_non_existent_gitignore(tmp_path, mocker, gitignore_exists):
  392. """Test that the generated .gitignore_file file on reflex init contains the correct file
  393. names with correct formatting.
  394. Args:
  395. tmp_path: The root test path.
  396. mocker: The mock object.
  397. gitignore_exists: Whether a gitignore file exists in the root dir.
  398. """
  399. expected = constants.DEFAULT_GITIGNORE.copy()
  400. mocker.patch("reflex.constants.GITIGNORE_FILE", tmp_path / ".gitignore")
  401. gitignore_file = tmp_path / ".gitignore"
  402. if gitignore_exists:
  403. gitignore_file.touch()
  404. gitignore_file.write_text(
  405. """*.db
  406. __pycache__/
  407. """
  408. )
  409. prerequisites.initialize_gitignore()
  410. assert gitignore_file.exists()
  411. file_content = [
  412. line.strip() for line in gitignore_file.open().read().splitlines() if line
  413. ]
  414. assert set(file_content) - expected == set()
  415. def test_app_default_name(tmp_path, mocker):
  416. """Test that an error is raised if the app name is reflex.
  417. Args:
  418. tmp_path: Test working dir.
  419. mocker: Pytest mocker object.
  420. """
  421. reflex = tmp_path / "reflex"
  422. reflex.mkdir()
  423. mocker.patch("reflex.utils.prerequisites.os.getcwd", return_value=str(reflex))
  424. with pytest.raises(typer.Exit):
  425. prerequisites.get_default_app_name()
  426. def test_node_install_windows(tmp_path, mocker):
  427. """Require user to install node manually for windows if node is not installed.
  428. Args:
  429. tmp_path: Test working dir.
  430. mocker: Pytest mocker object.
  431. """
  432. fnm_root_path = tmp_path / "reflex" / "fnm"
  433. fnm_exe = fnm_root_path / "fnm.exe"
  434. mocker.patch("reflex.utils.prerequisites.constants.FNM_DIR", fnm_root_path)
  435. mocker.patch("reflex.utils.prerequisites.constants.FNM_EXE", fnm_exe)
  436. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", True)
  437. mocker.patch("reflex.utils.processes.new_process")
  438. mocker.patch("reflex.utils.processes.stream_logs")
  439. class Resp(Base):
  440. status_code = 200
  441. text = "test"
  442. mocker.patch("httpx.stream", return_value=Resp())
  443. download = mocker.patch("reflex.utils.prerequisites.download_and_extract_fnm_zip")
  444. mocker.patch("reflex.utils.prerequisites.zipfile.ZipFile")
  445. mocker.patch("reflex.utils.prerequisites.path_ops.rm")
  446. prerequisites.install_node()
  447. assert fnm_root_path.exists()
  448. download.assert_called_once()
  449. def test_node_install_unix(tmp_path, mocker):
  450. fnm_root_path = tmp_path / "reflex" / "fnm"
  451. fnm_exe = fnm_root_path / "fnm"
  452. mocker.patch("reflex.utils.prerequisites.constants.FNM_DIR", fnm_root_path)
  453. mocker.patch("reflex.utils.prerequisites.constants.FNM_EXE", fnm_exe)
  454. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
  455. class Resp(Base):
  456. status_code = 200
  457. text = "test"
  458. mocker.patch("httpx.stream", return_value=Resp())
  459. download = mocker.patch("reflex.utils.prerequisites.download_and_extract_fnm_zip")
  460. process = mocker.patch("reflex.utils.processes.new_process")
  461. chmod = mocker.patch("reflex.utils.prerequisites.os.chmod")
  462. mocker.patch("reflex.utils.processes.stream_logs")
  463. prerequisites.install_node()
  464. assert fnm_root_path.exists()
  465. download.assert_called_once()
  466. process.assert_called_with(
  467. [fnm_exe, "install", constants.NODE_VERSION, "--fnm-dir", fnm_root_path]
  468. )
  469. chmod.assert_called_once()
  470. def test_bun_install_without_unzip(mocker):
  471. """Test that an error is thrown when installing bun with unzip not installed.
  472. Args:
  473. mocker: Pytest mocker object.
  474. """
  475. mocker.patch("reflex.utils.path_ops.which", return_value=None)
  476. mocker.patch("os.path.exists", return_value=False)
  477. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
  478. with pytest.raises(FileNotFoundError):
  479. prerequisites.install_bun()
  480. @pytest.mark.parametrize("is_windows", [True, False])
  481. def test_create_reflex_dir(mocker, is_windows):
  482. """Test that a reflex directory is created on initializing frontend
  483. dependencies.
  484. Args:
  485. mocker: Pytest mocker object.
  486. is_windows: Whether platform is windows.
  487. """
  488. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", is_windows)
  489. mocker.patch("reflex.utils.prerequisites.processes.run_concurrently", mocker.Mock())
  490. mocker.patch("reflex.utils.prerequisites.initialize_web_directory", mocker.Mock())
  491. mocker.patch("reflex.utils.processes.run_concurrently")
  492. mocker.patch("reflex.utils.prerequisites.validate_bun")
  493. create_cmd = mocker.patch(
  494. "reflex.utils.prerequisites.path_ops.mkdir", mocker.Mock()
  495. )
  496. prerequisites.initialize_frontend_dependencies()
  497. assert create_cmd.called
  498. def test_output_system_info(mocker):
  499. """Make sure reflex does not crash dumping system info.
  500. Args:
  501. mocker: Pytest mocker object.
  502. This test makes no assertions about the output, other than it executes
  503. without crashing.
  504. """
  505. mocker.patch("reflex.utils.console.LOG_LEVEL", constants.LogLevel.DEBUG)
  506. utils_exec.output_system_info()