test_utils.py 18 KB

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