test_utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. @pytest.mark.parametrize(
  217. "bun_version,is_valid, prompt_input",
  218. [
  219. (V055, False, "yes"),
  220. (V059, True, None),
  221. (VMAXPLUS1, False, "yes"),
  222. ],
  223. )
  224. def test_initialize_bun(mocker, bun_version, is_valid, prompt_input):
  225. """Test that the bun version on host system is validated properly. Also test that
  226. the required bun version is installed should the user opt for it.
  227. Args:
  228. mocker: Pytest mocker object.
  229. bun_version: The bun version.
  230. is_valid: Whether bun version is valid for running reflex.
  231. prompt_input: The input from user on whether to install bun.
  232. """
  233. mocker.patch("reflex.utils.prerequisites.get_bun_version", return_value=bun_version)
  234. mocker.patch("reflex.utils.prerequisites.IS_WINDOWS", False)
  235. bun_install = mocker.patch("reflex.utils.prerequisites.install_bun")
  236. remove_existing_bun_installation = mocker.patch(
  237. "reflex.utils.prerequisites.remove_existing_bun_installation"
  238. )
  239. prerequisites.initialize_bun()
  240. if not is_valid:
  241. remove_existing_bun_installation.assert_called_once()
  242. bun_install.assert_called_once()
  243. def test_remove_existing_bun_installation(mocker):
  244. """Test that existing bun installation is removed.
  245. Args:
  246. mocker: Pytest mocker.
  247. """
  248. mocker.patch("reflex.utils.prerequisites.os.path.exists", return_value=True)
  249. rm = mocker.patch("reflex.utils.prerequisites.path_ops.rm", mocker.Mock())
  250. prerequisites.remove_existing_bun_installation()
  251. rm.assert_called_once()
  252. def test_setup_frontend(tmp_path, mocker):
  253. """Test checking if assets content have been
  254. copied into the .web/public folder.
  255. Args:
  256. tmp_path: root path of test case data directory
  257. mocker: mocker object to allow mocking
  258. """
  259. web_public_folder = tmp_path / ".web" / "public"
  260. assets = tmp_path / "assets"
  261. assets.mkdir()
  262. (assets / "favicon.ico").touch()
  263. mocker.patch("reflex.utils.prerequisites.install_frontend_packages")
  264. mocker.patch("reflex.utils.build.set_environment_variables")
  265. build.setup_frontend(tmp_path, disable_telemetry=False)
  266. assert web_public_folder.exists()
  267. assert (web_public_folder / "favicon.ico").exists()
  268. @pytest.mark.parametrize(
  269. "input, output",
  270. [
  271. ("_hidden", True),
  272. ("not_hidden", False),
  273. ("__dundermethod__", False),
  274. ],
  275. )
  276. def test_is_backend_variable(input, output):
  277. assert types.is_backend_variable(input) == output
  278. @pytest.mark.parametrize(
  279. "cls, cls_check, expected",
  280. [
  281. (int, int, True),
  282. (int, float, False),
  283. (int, Union[int, float], True),
  284. (float, Union[int, float], True),
  285. (str, Union[int, float], False),
  286. (List[int], List[int], True),
  287. (List[int], List[float], True),
  288. (Union[int, float], Union[int, float], False),
  289. (Union[int, Var[int]], Var[int], False),
  290. (int, Any, True),
  291. (Any, Any, True),
  292. (Union[int, float], Any, True),
  293. ],
  294. )
  295. def test_issubclass(cls: type, cls_check: type, expected: bool):
  296. assert types._issubclass(cls, cls_check) == expected
  297. @pytest.mark.parametrize(
  298. "app_name,expected_config_name",
  299. [
  300. ("appname", "AppnameConfig"),
  301. ("app_name", "AppnameConfig"),
  302. ("app-name", "AppnameConfig"),
  303. ("appname2.io", "AppnameioConfig"),
  304. ],
  305. )
  306. def test_create_config(app_name, expected_config_name, mocker):
  307. """Test templates.RXCONFIG is formatted with correct app name and config class name.
  308. Args:
  309. app_name: App name.
  310. expected_config_name: Expected config name.
  311. mocker: Mocker object.
  312. """
  313. mocker.patch("builtins.open")
  314. tmpl_mock = mocker.patch("reflex.compiler.templates.RXCONFIG")
  315. prerequisites.create_config(app_name)
  316. tmpl_mock.render.assert_called_with(
  317. app_name=app_name, config_name=expected_config_name
  318. )
  319. @pytest.fixture
  320. def tmp_working_dir(tmp_path):
  321. """Create a temporary directory and chdir to it.
  322. After the test executes, chdir back to the original working directory.
  323. Args:
  324. tmp_path: pytest tmp_path fixture creates per-test temp dir
  325. Yields:
  326. subdirectory of tmp_path which is now the current working directory.
  327. """
  328. old_pwd = Path(".").resolve()
  329. working_dir = tmp_path / "working_dir"
  330. working_dir.mkdir()
  331. os.chdir(working_dir)
  332. yield working_dir
  333. os.chdir(old_pwd)
  334. def test_create_config_e2e(tmp_working_dir):
  335. """Create a new config file, exec it, and make assertions about the config.
  336. Args:
  337. tmp_working_dir: a new directory that is the current working directory
  338. for the duration of the test.
  339. """
  340. app_name = "e2e"
  341. prerequisites.create_config(app_name)
  342. eval_globals = {}
  343. exec((tmp_working_dir / constants.CONFIG_FILE).read_text(), eval_globals)
  344. config = eval_globals["config"]
  345. assert config.app_name == app_name
  346. assert config.db_url == constants.DB_URL
  347. assert config.env == Env.DEV
  348. @pytest.mark.parametrize(
  349. "name,expected",
  350. [
  351. ("input1", "ref_input1"),
  352. ("input 1", "ref_input_1"),
  353. ("input-1", "ref_input_1"),
  354. ("input_1", "ref_input_1"),
  355. ("a long test?1! name", "ref_a_long_test_1_name"),
  356. ],
  357. )
  358. def test_format_ref(name, expected):
  359. """Test formatting a ref.
  360. Args:
  361. name: The name to format.
  362. expected: The expected formatted name.
  363. """
  364. assert format.format_ref(name) == expected
  365. class DataFrame:
  366. """A Fake pandas DataFrame class."""
  367. pass
  368. @pytest.mark.parametrize(
  369. "class_type,expected",
  370. [
  371. (list, False),
  372. (int, False),
  373. (dict, False),
  374. (DataFrame, True),
  375. (typing.Any, False),
  376. (typing.List, False),
  377. ],
  378. )
  379. def test_is_dataframe(class_type, expected):
  380. """Test that a type name is DataFrame.
  381. Args:
  382. class_type: the class type.
  383. expected: whether type name is DataFrame
  384. """
  385. assert types.is_dataframe(class_type) == expected
  386. @pytest.mark.parametrize("gitignore_exists", [True, False])
  387. def test_initialize_non_existent_gitignore(tmp_path, mocker, gitignore_exists):
  388. """Test that the generated .gitignore_file file on reflex init contains the correct file
  389. names with correct formatting.
  390. Args:
  391. tmp_path: The root test path.
  392. mocker: The mock object.
  393. gitignore_exists: Whether a gitignore file exists in the root dir.
  394. """
  395. expected = constants.DEFAULT_GITIGNORE.copy()
  396. mocker.patch("reflex.constants.GITIGNORE_FILE", tmp_path / ".gitignore")
  397. gitignore_file = tmp_path / ".gitignore"
  398. if gitignore_exists:
  399. gitignore_file.touch()
  400. gitignore_file.write_text(
  401. """reflex.db
  402. __pycache__/
  403. """
  404. )
  405. prerequisites.initialize_gitignore()
  406. assert gitignore_file.exists()
  407. file_content = [
  408. line.strip() for line in gitignore_file.open().read().splitlines() if line
  409. ]
  410. assert set(file_content) - expected == set()
  411. def test_app_default_name(tmp_path, mocker):
  412. """Test that an error is raised if the app name is reflex.
  413. Args:
  414. tmp_path: Test working dir.
  415. mocker: Pytest mocker object.
  416. """
  417. reflex = tmp_path / "reflex"
  418. reflex.mkdir()
  419. mocker.patch("reflex.utils.prerequisites.os.getcwd", return_value=str(reflex))
  420. with pytest.raises(typer.Exit):
  421. prerequisites.get_default_app_name()
  422. def test_node_install_windows(mocker):
  423. """Require user to install node manually for windows if node is not installed.
  424. Args:
  425. mocker: Pytest mocker object.
  426. """
  427. mocker.patch("reflex.utils.prerequisites.IS_WINDOWS", True)
  428. mocker.patch("reflex.utils.prerequisites.check_node_version", return_value=False)
  429. with pytest.raises(typer.Exit):
  430. prerequisites.initialize_node()
  431. def test_node_install_unix(tmp_path, mocker):
  432. nvm_root_path = tmp_path / ".reflex" / ".nvm"
  433. mocker.patch("reflex.utils.prerequisites.constants.NVM_DIR", nvm_root_path)
  434. mocker.patch("reflex.utils.prerequisites.IS_WINDOWS", False)
  435. class Resp(Base):
  436. status_code = 200
  437. text = "test"
  438. mocker.patch("httpx.get", return_value=Resp())
  439. download = mocker.patch("reflex.utils.prerequisites.download_and_run")
  440. mocker.patch("reflex.utils.prerequisites.new_process")
  441. mocker.patch("reflex.utils.prerequisites.show_logs")
  442. prerequisites.install_node()
  443. assert nvm_root_path.exists()
  444. download.assert_called()
  445. download.call_count = 2
  446. def test_bun_install_without_unzip(mocker):
  447. """Test that an error is thrown when installing bun with unzip not installed.
  448. Args:
  449. mocker: Pytest mocker object.
  450. """
  451. mocker.patch("reflex.utils.path_ops.which", return_value=None)
  452. mocker.patch("os.path.exists", return_value=False)
  453. mocker.patch("reflex.utils.prerequisites.IS_WINDOWS", False)
  454. with pytest.raises(FileNotFoundError):
  455. prerequisites.install_bun()