test_utils.py 16 KB

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