test_utils.py 16 KB

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