test_utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import os
  2. import typing
  3. from pathlib import Path
  4. from typing import Any, List, Literal, 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.event import EventHandler
  11. from reflex.state import State
  12. from reflex.utils import (
  13. build,
  14. imports,
  15. prerequisites,
  16. types,
  17. )
  18. from reflex.utils import exec as utils_exec
  19. from reflex.utils.serializers import serialize
  20. from reflex.vars import Var
  21. def mock_event(arg):
  22. pass
  23. def get_above_max_version():
  24. """Get the 1 version above the max required bun version.
  25. Returns:
  26. max bun version plus one.
  27. """
  28. semantic_version_list = constants.Bun.VERSION.split(".")
  29. semantic_version_list[-1] = str(int(semantic_version_list[-1]) + 1) # type: ignore
  30. return ".".join(semantic_version_list)
  31. V055 = version.parse("0.5.5")
  32. V059 = version.parse("0.5.9")
  33. V056 = version.parse("0.5.6")
  34. VMAXPLUS1 = version.parse(get_above_max_version())
  35. class ExampleTestState(State):
  36. """Test state class."""
  37. def test_event_handler(self):
  38. """Test event handler."""
  39. pass
  40. def test_func():
  41. pass
  42. def test_merge_imports():
  43. """Test that imports are merged correctly."""
  44. d1 = {"react": {"Component"}}
  45. d2 = {"react": {"Component"}, "react-dom": {"render"}}
  46. d = imports.merge_imports(d1, d2)
  47. assert set(d.keys()) == {"react", "react-dom"}
  48. assert set(d["react"]) == {"Component"}
  49. assert set(d["react-dom"]) == {"render"}
  50. @pytest.mark.parametrize(
  51. "cls,expected",
  52. [
  53. (str, False),
  54. (int, False),
  55. (float, False),
  56. (bool, False),
  57. (List, True),
  58. (List[int], True),
  59. ],
  60. )
  61. def test_is_generic_alias(cls: type, expected: bool):
  62. """Test checking if a class is a GenericAlias.
  63. Args:
  64. cls: The class to check.
  65. expected: Whether the class is a GenericAlias.
  66. """
  67. assert types.is_generic_alias(cls) == expected
  68. def test_validate_invalid_bun_path(mocker):
  69. """Test that an error is thrown when a custom specified bun path is not valid
  70. or does not exist.
  71. Args:
  72. mocker: Pytest mocker object.
  73. """
  74. mock = mocker.Mock()
  75. mocker.patch.object(mock, "bun_path", return_value="/mock/path")
  76. mocker.patch("reflex.utils.prerequisites.get_config", mock)
  77. mocker.patch("reflex.utils.prerequisites.get_bun_version", return_value=None)
  78. with pytest.raises(typer.Exit):
  79. prerequisites.validate_bun()
  80. def test_validate_bun_path_incompatible_version(mocker):
  81. """Test that an error is thrown when the bun version does not meet minimum requirements.
  82. Args:
  83. mocker: Pytest mocker object.
  84. """
  85. mock = mocker.Mock()
  86. mocker.patch.object(mock, "bun_path", return_value="/mock/path")
  87. mocker.patch("reflex.utils.prerequisites.get_config", mock)
  88. mocker.patch(
  89. "reflex.utils.prerequisites.get_bun_version",
  90. return_value=version.parse("0.6.5"),
  91. )
  92. with pytest.raises(typer.Exit):
  93. prerequisites.validate_bun()
  94. def test_remove_existing_bun_installation(mocker):
  95. """Test that existing bun installation is removed.
  96. Args:
  97. mocker: Pytest mocker.
  98. """
  99. mocker.patch("reflex.utils.prerequisites.os.path.exists", return_value=True)
  100. rm = mocker.patch("reflex.utils.prerequisites.path_ops.rm", mocker.Mock())
  101. prerequisites.remove_existing_bun_installation()
  102. rm.assert_called_once()
  103. def test_setup_frontend(tmp_path, mocker):
  104. """Test checking if assets content have been
  105. copied into the .web/public folder.
  106. Args:
  107. tmp_path: root path of test case data directory
  108. mocker: mocker object to allow mocking
  109. """
  110. web_public_folder = tmp_path / ".web" / "public"
  111. assets = tmp_path / "assets"
  112. assets.mkdir()
  113. (assets / "favicon.ico").touch()
  114. mocker.patch("reflex.utils.prerequisites.install_frontend_packages")
  115. mocker.patch("reflex.utils.build.set_env_json")
  116. build.setup_frontend(tmp_path, disable_telemetry=False)
  117. assert web_public_folder.exists()
  118. assert (web_public_folder / "favicon.ico").exists()
  119. @pytest.mark.parametrize(
  120. "input, output",
  121. [
  122. ("_hidden", True),
  123. ("not_hidden", False),
  124. ("__dundermethod__", False),
  125. ],
  126. )
  127. def test_is_backend_variable(input, output):
  128. assert types.is_backend_variable(input) == output
  129. @pytest.mark.parametrize(
  130. "cls, cls_check, expected",
  131. [
  132. (int, int, True),
  133. (int, float, False),
  134. (int, Union[int, float], True),
  135. (float, Union[int, float], True),
  136. (str, Union[int, float], False),
  137. (List[int], List[int], True),
  138. (List[int], List[float], True),
  139. (Union[int, float], Union[int, float], False),
  140. (Union[int, Var[int]], Var[int], False),
  141. (int, Any, True),
  142. (Any, Any, True),
  143. (Union[int, float], Any, True),
  144. (str, Union[Literal["test", "value"], int], True),
  145. (int, Union[Literal["test", "value"], int], True),
  146. (str, Literal["test", "value"], True),
  147. (int, Literal["test", "value"], False),
  148. ],
  149. )
  150. def test_issubclass(cls: type, cls_check: type, expected: bool):
  151. assert types._issubclass(cls, cls_check) == expected
  152. @pytest.mark.parametrize("cls", [Literal["test", 1], Literal[1, "test"]])
  153. def test_unsupported_literals(cls: type):
  154. with pytest.raises(TypeError):
  155. types.get_base_class(cls)
  156. @pytest.mark.parametrize(
  157. "app_name,expected_config_name",
  158. [
  159. ("appname", "AppnameConfig"),
  160. ("app_name", "AppnameConfig"),
  161. ("app-name", "AppnameConfig"),
  162. ("appname2.io", "AppnameioConfig"),
  163. ],
  164. )
  165. def test_create_config(app_name, expected_config_name, mocker):
  166. """Test templates.RXCONFIG is formatted with correct app name and config class name.
  167. Args:
  168. app_name: App name.
  169. expected_config_name: Expected config name.
  170. mocker: Mocker object.
  171. """
  172. mocker.patch("builtins.open")
  173. tmpl_mock = mocker.patch("reflex.compiler.templates.RXCONFIG")
  174. prerequisites.create_config(app_name)
  175. tmpl_mock.render.assert_called_with(
  176. app_name=app_name, config_name=expected_config_name
  177. )
  178. @pytest.fixture
  179. def tmp_working_dir(tmp_path):
  180. """Create a temporary directory and chdir to it.
  181. After the test executes, chdir back to the original working directory.
  182. Args:
  183. tmp_path: pytest tmp_path fixture creates per-test temp dir
  184. Yields:
  185. subdirectory of tmp_path which is now the current working directory.
  186. """
  187. old_pwd = Path(".").resolve()
  188. working_dir = tmp_path / "working_dir"
  189. working_dir.mkdir()
  190. os.chdir(working_dir)
  191. yield working_dir
  192. os.chdir(old_pwd)
  193. def test_create_config_e2e(tmp_working_dir):
  194. """Create a new config file, exec it, and make assertions about the config.
  195. Args:
  196. tmp_working_dir: a new directory that is the current working directory
  197. for the duration of the test.
  198. """
  199. app_name = "e2e"
  200. prerequisites.create_config(app_name)
  201. eval_globals = {}
  202. exec((tmp_working_dir / constants.Config.FILE).read_text(), eval_globals)
  203. config = eval_globals["config"]
  204. assert config.app_name == app_name
  205. class DataFrame:
  206. """A Fake pandas DataFrame class."""
  207. pass
  208. @pytest.mark.parametrize(
  209. "class_type,expected",
  210. [
  211. (list, False),
  212. (int, False),
  213. (dict, False),
  214. (DataFrame, True),
  215. (typing.Any, False),
  216. (typing.List, False),
  217. ],
  218. )
  219. def test_is_dataframe(class_type, expected):
  220. """Test that a type name is DataFrame.
  221. Args:
  222. class_type: the class type.
  223. expected: whether type name is DataFrame
  224. """
  225. assert types.is_dataframe(class_type) == expected
  226. @pytest.mark.parametrize("gitignore_exists", [True, False])
  227. def test_initialize_non_existent_gitignore(tmp_path, mocker, gitignore_exists):
  228. """Test that the generated .gitignore_file file on reflex init contains the correct file
  229. names with correct formatting.
  230. Args:
  231. tmp_path: The root test path.
  232. mocker: The mock object.
  233. gitignore_exists: Whether a gitignore file exists in the root dir.
  234. """
  235. expected = constants.GitIgnore.DEFAULTS.copy()
  236. mocker.patch("reflex.constants.GitIgnore.FILE", tmp_path / ".gitignore")
  237. gitignore_file = tmp_path / ".gitignore"
  238. if gitignore_exists:
  239. gitignore_file.touch()
  240. gitignore_file.write_text(
  241. """*.db
  242. __pycache__/
  243. """
  244. )
  245. prerequisites.initialize_gitignore()
  246. assert gitignore_file.exists()
  247. file_content = [
  248. line.strip() for line in gitignore_file.open().read().splitlines() if line
  249. ]
  250. assert set(file_content) - expected == set()
  251. def test_app_default_name(tmp_path, mocker):
  252. """Test that an error is raised if the app name is reflex.
  253. Args:
  254. tmp_path: Test working dir.
  255. mocker: Pytest mocker object.
  256. """
  257. reflex = tmp_path / "reflex"
  258. reflex.mkdir()
  259. mocker.patch("reflex.utils.prerequisites.os.getcwd", return_value=str(reflex))
  260. with pytest.raises(typer.Exit):
  261. prerequisites.get_default_app_name()
  262. def test_node_install_windows(tmp_path, mocker):
  263. """Require user to install node manually for windows if node is not installed.
  264. Args:
  265. tmp_path: Test working dir.
  266. mocker: Pytest mocker object.
  267. """
  268. fnm_root_path = tmp_path / "reflex" / "fnm"
  269. fnm_exe = fnm_root_path / "fnm.exe"
  270. mocker.patch("reflex.utils.prerequisites.constants.Fnm.DIR", fnm_root_path)
  271. mocker.patch("reflex.utils.prerequisites.constants.Fnm.EXE", fnm_exe)
  272. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", True)
  273. mocker.patch("reflex.utils.processes.new_process")
  274. mocker.patch("reflex.utils.processes.stream_logs")
  275. class Resp(Base):
  276. status_code = 200
  277. text = "test"
  278. mocker.patch("httpx.stream", return_value=Resp())
  279. download = mocker.patch("reflex.utils.prerequisites.download_and_extract_fnm_zip")
  280. mocker.patch("reflex.utils.prerequisites.zipfile.ZipFile")
  281. mocker.patch("reflex.utils.prerequisites.path_ops.rm")
  282. prerequisites.install_node()
  283. assert fnm_root_path.exists()
  284. download.assert_called_once()
  285. @pytest.mark.parametrize(
  286. "machine, system",
  287. [
  288. ("x64", "Darwin"),
  289. ("arm64", "Darwin"),
  290. ("x64", "Windows"),
  291. ("arm64", "Windows"),
  292. ("armv7", "Linux"),
  293. ("armv8-a", "Linux"),
  294. ("armv8.1-a", "Linux"),
  295. ("armv8.2-a", "Linux"),
  296. ("armv8.3-a", "Linux"),
  297. ("armv8.4-a", "Linux"),
  298. ("aarch64", "Linux"),
  299. ("aarch32", "Linux"),
  300. ],
  301. )
  302. def test_node_install_unix(tmp_path, mocker, machine, system):
  303. fnm_root_path = tmp_path / "reflex" / "fnm"
  304. fnm_exe = fnm_root_path / "fnm"
  305. mocker.patch("reflex.utils.prerequisites.constants.Fnm.DIR", fnm_root_path)
  306. mocker.patch("reflex.utils.prerequisites.constants.Fnm.EXE", fnm_exe)
  307. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
  308. mocker.patch("reflex.utils.prerequisites.platform.machine", return_value=machine)
  309. mocker.patch("reflex.utils.prerequisites.platform.system", return_value=system)
  310. class Resp(Base):
  311. status_code = 200
  312. text = "test"
  313. mocker.patch("httpx.stream", return_value=Resp())
  314. download = mocker.patch("reflex.utils.prerequisites.download_and_extract_fnm_zip")
  315. process = mocker.patch("reflex.utils.processes.new_process")
  316. chmod = mocker.patch("reflex.utils.prerequisites.os.chmod")
  317. mocker.patch("reflex.utils.processes.stream_logs")
  318. prerequisites.install_node()
  319. assert fnm_root_path.exists()
  320. download.assert_called_once()
  321. if system == "Darwin" and machine == "arm64":
  322. process.assert_called_with(
  323. [
  324. fnm_exe,
  325. "install",
  326. "--arch=arm64",
  327. constants.Node.VERSION,
  328. "--fnm-dir",
  329. fnm_root_path,
  330. ]
  331. )
  332. else:
  333. process.assert_called_with(
  334. [fnm_exe, "install", constants.Node.VERSION, "--fnm-dir", fnm_root_path]
  335. )
  336. chmod.assert_called_once()
  337. def test_bun_install_without_unzip(mocker):
  338. """Test that an error is thrown when installing bun with unzip not installed.
  339. Args:
  340. mocker: Pytest mocker object.
  341. """
  342. mocker.patch("reflex.utils.path_ops.which", return_value=None)
  343. mocker.patch("os.path.exists", return_value=False)
  344. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
  345. with pytest.raises(FileNotFoundError):
  346. prerequisites.install_bun()
  347. @pytest.mark.parametrize("is_windows", [True, False])
  348. def test_create_reflex_dir(mocker, is_windows):
  349. """Test that a reflex directory is created on initializing frontend
  350. dependencies.
  351. Args:
  352. mocker: Pytest mocker object.
  353. is_windows: Whether platform is windows.
  354. """
  355. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", is_windows)
  356. mocker.patch("reflex.utils.prerequisites.processes.run_concurrently", mocker.Mock())
  357. mocker.patch("reflex.utils.prerequisites.initialize_web_directory", mocker.Mock())
  358. mocker.patch("reflex.utils.processes.run_concurrently")
  359. mocker.patch("reflex.utils.prerequisites.validate_bun")
  360. create_cmd = mocker.patch(
  361. "reflex.utils.prerequisites.path_ops.mkdir", mocker.Mock()
  362. )
  363. prerequisites.initialize_frontend_dependencies()
  364. assert create_cmd.called
  365. def test_output_system_info(mocker):
  366. """Make sure reflex does not crash dumping system info.
  367. Args:
  368. mocker: Pytest mocker object.
  369. This test makes no assertions about the output, other than it executes
  370. without crashing.
  371. """
  372. mocker.patch("reflex.utils.console._LOG_LEVEL", constants.LogLevel.DEBUG)
  373. utils_exec.output_system_info()
  374. @pytest.mark.parametrize(
  375. "callable", [ExampleTestState.test_event_handler, test_func, lambda x: x]
  376. )
  377. def test_style_prop_with_event_handler_value(callable):
  378. """Test that a type error is thrown when a style prop has a
  379. callable as value.
  380. Args:
  381. callable: The callable function or event handler.
  382. """
  383. style = {
  384. "color": EventHandler(fn=callable)
  385. if type(callable) != EventHandler
  386. else callable
  387. }
  388. with pytest.raises(TypeError):
  389. serialize(style) # type: ignore