test_utils.py 19 KB

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