1
0

test_utils.py 18 KB

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