test_utils.py 18 KB

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