test_utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. import os
  2. import typing
  3. from pathlib import Path
  4. from typing import Any, ClassVar, 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.fixture
  111. def test_backend_variable_cls():
  112. class TestBackendVariable:
  113. """Test backend variable."""
  114. _classvar: ClassVar[int] = 0
  115. _hidden: int = 0
  116. not_hidden: int = 0
  117. __dunderattr__: int = 0
  118. return TestBackendVariable
  119. @pytest.mark.parametrize(
  120. "input, output",
  121. [
  122. ("_classvar", False),
  123. ("_hidden", True),
  124. ("not_hidden", False),
  125. ("__dundermethod__", False),
  126. ],
  127. )
  128. def test_is_backend_variable(test_backend_variable_cls, input, output):
  129. assert types.is_backend_variable(input, test_backend_variable_cls) == output
  130. @pytest.mark.parametrize(
  131. "cls, cls_check, expected",
  132. [
  133. (int, int, True),
  134. (int, float, False),
  135. (int, Union[int, float], True),
  136. (float, Union[int, float], True),
  137. (str, Union[int, float], False),
  138. (List[int], List[int], True),
  139. (List[int], List[float], True),
  140. (Union[int, float], Union[int, float], False),
  141. (Union[int, Var[int]], Var[int], False),
  142. (int, Any, True),
  143. (Any, Any, True),
  144. (Union[int, float], Any, True),
  145. (str, Union[Literal["test", "value"], int], True),
  146. (int, Union[Literal["test", "value"], int], True),
  147. (str, Literal["test", "value"], True),
  148. (int, Literal["test", "value"], False),
  149. ],
  150. )
  151. def test_issubclass(cls: type, cls_check: type, expected: bool):
  152. assert types._issubclass(cls, cls_check) == expected
  153. @pytest.mark.parametrize("cls", [Literal["test", 1], Literal[1, "test"]])
  154. def test_unsupported_literals(cls: type):
  155. with pytest.raises(TypeError):
  156. types.get_base_class(cls)
  157. @pytest.mark.parametrize(
  158. "app_name,expected_config_name",
  159. [
  160. ("appname", "AppnameConfig"),
  161. ("app_name", "AppnameConfig"),
  162. ("app-name", "AppnameConfig"),
  163. ("appname2.io", "AppnameioConfig"),
  164. ],
  165. )
  166. def test_create_config(app_name, expected_config_name, mocker):
  167. """Test templates.RXCONFIG is formatted with correct app name and config class name.
  168. Args:
  169. app_name: App name.
  170. expected_config_name: Expected config name.
  171. mocker: Mocker object.
  172. """
  173. mocker.patch("builtins.open")
  174. tmpl_mock = mocker.patch("reflex.compiler.templates.RXCONFIG")
  175. prerequisites.create_config(app_name)
  176. tmpl_mock.render.assert_called_with(
  177. app_name=app_name, config_name=expected_config_name
  178. )
  179. @pytest.fixture
  180. def tmp_working_dir(tmp_path):
  181. """Create a temporary directory and chdir to it.
  182. After the test executes, chdir back to the original working directory.
  183. Args:
  184. tmp_path: pytest tmp_path fixture creates per-test temp dir
  185. Yields:
  186. subdirectory of tmp_path which is now the current working directory.
  187. """
  188. old_pwd = Path(".").resolve()
  189. working_dir = tmp_path / "working_dir"
  190. working_dir.mkdir()
  191. os.chdir(working_dir)
  192. yield working_dir
  193. os.chdir(old_pwd)
  194. def test_create_config_e2e(tmp_working_dir):
  195. """Create a new config file, exec it, and make assertions about the config.
  196. Args:
  197. tmp_working_dir: a new directory that is the current working directory
  198. for the duration of the test.
  199. """
  200. app_name = "e2e"
  201. prerequisites.create_config(app_name)
  202. eval_globals = {}
  203. exec((tmp_working_dir / constants.Config.FILE).read_text(), eval_globals)
  204. config = eval_globals["config"]
  205. assert config.app_name == app_name
  206. class DataFrame:
  207. """A Fake pandas DataFrame class."""
  208. pass
  209. @pytest.mark.parametrize(
  210. "class_type,expected",
  211. [
  212. (list, False),
  213. (int, False),
  214. (dict, False),
  215. (DataFrame, True),
  216. (typing.Any, False),
  217. (typing.List, False),
  218. ],
  219. )
  220. def test_is_dataframe(class_type, expected):
  221. """Test that a type name is DataFrame.
  222. Args:
  223. class_type: the class type.
  224. expected: whether type name is DataFrame
  225. """
  226. assert types.is_dataframe(class_type) == expected
  227. @pytest.mark.parametrize("gitignore_exists", [True, False])
  228. def test_initialize_non_existent_gitignore(tmp_path, mocker, gitignore_exists):
  229. """Test that the generated .gitignore_file file on reflex init contains the correct file
  230. names with correct formatting.
  231. Args:
  232. tmp_path: The root test path.
  233. mocker: The mock object.
  234. gitignore_exists: Whether a gitignore file exists in the root dir.
  235. """
  236. expected = constants.GitIgnore.DEFAULTS.copy()
  237. mocker.patch("reflex.constants.GitIgnore.FILE", tmp_path / ".gitignore")
  238. gitignore_file = tmp_path / ".gitignore"
  239. if gitignore_exists:
  240. gitignore_file.touch()
  241. gitignore_file.write_text(
  242. """*.db
  243. __pycache__/
  244. """
  245. )
  246. prerequisites.initialize_gitignore(gitignore_file=gitignore_file)
  247. assert gitignore_file.exists()
  248. file_content = [
  249. line.strip() for line in gitignore_file.open().read().splitlines() if line
  250. ]
  251. assert set(file_content) - expected == set()
  252. def test_validate_app_name(tmp_path, mocker):
  253. """Test that an error is raised if the app name is reflex or if the name is not according to python package naming conventions.
  254. Args:
  255. tmp_path: Test working dir.
  256. mocker: Pytest mocker object.
  257. """
  258. reflex = tmp_path / "reflex"
  259. reflex.mkdir()
  260. mocker.patch("reflex.utils.prerequisites.os.getcwd", return_value=str(reflex))
  261. with pytest.raises(typer.Exit):
  262. prerequisites.validate_app_name()
  263. with pytest.raises(typer.Exit):
  264. prerequisites.validate_app_name(app_name="1_test")
  265. def test_node_install_windows(tmp_path, mocker):
  266. """Require user to install node manually for windows if node is not installed.
  267. Args:
  268. tmp_path: Test working dir.
  269. mocker: Pytest mocker object.
  270. """
  271. fnm_root_path = tmp_path / "reflex" / "fnm"
  272. fnm_exe = fnm_root_path / "fnm.exe"
  273. mocker.patch("reflex.utils.prerequisites.constants.Fnm.DIR", fnm_root_path)
  274. mocker.patch("reflex.utils.prerequisites.constants.Fnm.EXE", fnm_exe)
  275. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", True)
  276. mocker.patch("reflex.utils.processes.new_process")
  277. mocker.patch("reflex.utils.processes.stream_logs")
  278. class Resp(Base):
  279. status_code = 200
  280. text = "test"
  281. mocker.patch("httpx.stream", return_value=Resp())
  282. download = mocker.patch("reflex.utils.prerequisites.download_and_extract_fnm_zip")
  283. mocker.patch("reflex.utils.prerequisites.zipfile.ZipFile")
  284. mocker.patch("reflex.utils.prerequisites.path_ops.rm")
  285. prerequisites.install_node()
  286. assert fnm_root_path.exists()
  287. download.assert_called_once()
  288. @pytest.mark.parametrize(
  289. "machine, system",
  290. [
  291. ("x64", "Darwin"),
  292. ("arm64", "Darwin"),
  293. ("x64", "Windows"),
  294. ("arm64", "Windows"),
  295. ("armv7", "Linux"),
  296. ("armv8-a", "Linux"),
  297. ("armv8.1-a", "Linux"),
  298. ("armv8.2-a", "Linux"),
  299. ("armv8.3-a", "Linux"),
  300. ("armv8.4-a", "Linux"),
  301. ("aarch64", "Linux"),
  302. ("aarch32", "Linux"),
  303. ],
  304. )
  305. def test_node_install_unix(tmp_path, mocker, machine, system):
  306. fnm_root_path = tmp_path / "reflex" / "fnm"
  307. fnm_exe = fnm_root_path / "fnm"
  308. mocker.patch("reflex.utils.prerequisites.constants.Fnm.DIR", fnm_root_path)
  309. mocker.patch("reflex.utils.prerequisites.constants.Fnm.EXE", fnm_exe)
  310. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
  311. mocker.patch("reflex.utils.prerequisites.platform.machine", return_value=machine)
  312. mocker.patch("reflex.utils.prerequisites.platform.system", return_value=system)
  313. class Resp(Base):
  314. status_code = 200
  315. text = "test"
  316. mocker.patch("httpx.stream", return_value=Resp())
  317. download = mocker.patch("reflex.utils.prerequisites.download_and_extract_fnm_zip")
  318. process = mocker.patch("reflex.utils.processes.new_process")
  319. chmod = mocker.patch("reflex.utils.prerequisites.os.chmod")
  320. mocker.patch("reflex.utils.processes.stream_logs")
  321. prerequisites.install_node()
  322. assert fnm_root_path.exists()
  323. download.assert_called_once()
  324. if system == "Darwin" and machine == "arm64":
  325. process.assert_called_with(
  326. [
  327. fnm_exe,
  328. "install",
  329. "--arch=arm64",
  330. constants.Node.VERSION,
  331. "--fnm-dir",
  332. fnm_root_path,
  333. ]
  334. )
  335. else:
  336. process.assert_called_with(
  337. [fnm_exe, "install", constants.Node.VERSION, "--fnm-dir", fnm_root_path]
  338. )
  339. chmod.assert_called_once()
  340. def test_bun_install_without_unzip(mocker):
  341. """Test that an error is thrown when installing bun with unzip not installed.
  342. Args:
  343. mocker: Pytest mocker object.
  344. """
  345. mocker.patch("reflex.utils.path_ops.which", return_value=None)
  346. mocker.patch("os.path.exists", return_value=False)
  347. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
  348. with pytest.raises(FileNotFoundError):
  349. prerequisites.install_bun()
  350. @pytest.mark.parametrize("bun_version", [constants.Bun.VERSION, "1.0.0"])
  351. def test_bun_install_version(mocker, bun_version):
  352. """Test that bun is downloaded when the host version(installed by reflex)
  353. different from the current version set in reflex.
  354. Args:
  355. mocker: Pytest mocker object.
  356. bun_version: the host bun version
  357. """
  358. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", False)
  359. mocker.patch("os.path.exists", return_value=True)
  360. mocker.patch(
  361. "reflex.utils.prerequisites.get_bun_version",
  362. return_value=version.parse(bun_version),
  363. )
  364. mocker.patch("reflex.utils.path_ops.which")
  365. mock = mocker.patch("reflex.utils.prerequisites.download_and_run")
  366. prerequisites.install_bun()
  367. if bun_version == constants.Bun.VERSION:
  368. mock.assert_not_called()
  369. else:
  370. mock.assert_called_once()
  371. @pytest.mark.parametrize("is_windows", [True, False])
  372. def test_create_reflex_dir(mocker, is_windows):
  373. """Test that a reflex directory is created on initializing frontend
  374. dependencies.
  375. Args:
  376. mocker: Pytest mocker object.
  377. is_windows: Whether platform is windows.
  378. """
  379. mocker.patch("reflex.utils.prerequisites.constants.IS_WINDOWS", is_windows)
  380. mocker.patch("reflex.utils.prerequisites.processes.run_concurrently", mocker.Mock())
  381. mocker.patch("reflex.utils.prerequisites.initialize_web_directory", mocker.Mock())
  382. mocker.patch("reflex.utils.processes.run_concurrently")
  383. mocker.patch("reflex.utils.prerequisites.validate_bun")
  384. create_cmd = mocker.patch(
  385. "reflex.utils.prerequisites.path_ops.mkdir", mocker.Mock()
  386. )
  387. prerequisites.initialize_reflex_user_directory()
  388. assert create_cmd.called
  389. def test_output_system_info(mocker):
  390. """Make sure reflex does not crash dumping system info.
  391. Args:
  392. mocker: Pytest mocker object.
  393. This test makes no assertions about the output, other than it executes
  394. without crashing.
  395. """
  396. mocker.patch("reflex.utils.console._LOG_LEVEL", constants.LogLevel.DEBUG)
  397. utils_exec.output_system_info()
  398. @pytest.mark.parametrize(
  399. "callable", [ExampleTestState.test_event_handler, test_func, lambda x: x]
  400. )
  401. def test_style_prop_with_event_handler_value(callable):
  402. """Test that a type error is thrown when a style prop has a
  403. callable as value.
  404. Args:
  405. callable: The callable function or event handler.
  406. """
  407. style = {
  408. "color": (
  409. EventHandler(fn=callable) if type(callable) != EventHandler else callable
  410. )
  411. }
  412. with pytest.raises(TypeError):
  413. serialize(style) # type: ignore