test_utils.py 18 KB

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