test_utils.py 15 KB

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