test_utils.py 18 KB

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