test_utils.py 18 KB

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