test_config.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import multiprocessing
  2. import os
  3. from pathlib import Path
  4. from typing import Any, Dict
  5. import pytest
  6. import reflex as rx
  7. import reflex.config
  8. from reflex.config import (
  9. environment,
  10. interpret_boolean_env,
  11. interpret_enum_env,
  12. interpret_int_env,
  13. )
  14. from reflex.constants import Endpoint, Env
  15. def test_requires_app_name():
  16. """Test that a config requires an app_name."""
  17. with pytest.raises(ValueError):
  18. rx.Config() # type: ignore
  19. def test_set_app_name(base_config_values):
  20. """Test that the app name is set to the value passed in.
  21. Args:
  22. base_config_values: Config values.
  23. """
  24. config = rx.Config(**base_config_values)
  25. assert config.app_name == base_config_values["app_name"]
  26. @pytest.mark.parametrize(
  27. "env_var, value",
  28. [
  29. ("APP_NAME", "my_test_app"),
  30. ("FRONTEND_PORT", 3001),
  31. ("FRONTEND_PATH", "/test"),
  32. ("BACKEND_PORT", 8001),
  33. ("API_URL", "https://mybackend.com:8000"),
  34. ("DEPLOY_URL", "https://myfrontend.com"),
  35. ("BACKEND_HOST", "127.0.0.1"),
  36. ("DB_URL", "postgresql://user:pass@localhost:5432/db"),
  37. ("REDIS_URL", "redis://localhost:6379"),
  38. ("TIMEOUT", 600),
  39. ("TELEMETRY_ENABLED", False),
  40. ("TELEMETRY_ENABLED", True),
  41. ],
  42. )
  43. def test_update_from_env(
  44. base_config_values: Dict[str, Any],
  45. monkeypatch: pytest.MonkeyPatch,
  46. env_var: str,
  47. value: Any,
  48. ):
  49. """Test that environment variables override config values.
  50. Args:
  51. base_config_values: Config values.
  52. monkeypatch: The pytest monkeypatch object.
  53. env_var: The environment variable name.
  54. value: The environment variable value.
  55. """
  56. monkeypatch.setenv(env_var, str(value))
  57. assert os.environ.get(env_var) == str(value)
  58. config = rx.Config(**base_config_values)
  59. assert getattr(config, env_var.lower()) == value
  60. def test_update_from_env_path(
  61. base_config_values: Dict[str, Any],
  62. monkeypatch: pytest.MonkeyPatch,
  63. tmp_path: Path,
  64. ):
  65. """Test that environment variables override config values.
  66. Args:
  67. base_config_values: Config values.
  68. monkeypatch: The pytest monkeypatch object.
  69. tmp_path: The pytest tmp_path fixture object.
  70. """
  71. monkeypatch.setenv("BUN_PATH", "/test")
  72. assert os.environ.get("BUN_PATH") == "/test"
  73. with pytest.raises(ValueError):
  74. rx.Config(**base_config_values)
  75. monkeypatch.setenv("BUN_PATH", str(tmp_path))
  76. assert os.environ.get("BUN_PATH") == str(tmp_path)
  77. config = rx.Config(**base_config_values)
  78. assert config.bun_path == tmp_path
  79. @pytest.mark.parametrize(
  80. "kwargs, expected",
  81. [
  82. (
  83. {"app_name": "test_app", "api_url": "http://example.com"},
  84. f"{Endpoint.EVENT}",
  85. ),
  86. (
  87. {"app_name": "test_app", "api_url": "http://example.com/api"},
  88. f"/api{Endpoint.EVENT}",
  89. ),
  90. ],
  91. )
  92. def test_event_namespace(mocker, kwargs, expected):
  93. """Test the event namespace.
  94. Args:
  95. mocker: The pytest mock object.
  96. kwargs: The Config kwargs.
  97. expected: Expected namespace
  98. """
  99. conf = rx.Config(**kwargs)
  100. mocker.patch("reflex.config.get_config", return_value=conf)
  101. config = reflex.config.get_config()
  102. assert conf == config
  103. assert config.get_event_namespace() == expected
  104. DEFAULT_CONFIG = rx.Config(app_name="a")
  105. @pytest.mark.parametrize(
  106. ("config_kwargs", "env_vars", "set_persistent_vars", "exp_config_values"),
  107. [
  108. (
  109. {},
  110. {},
  111. {},
  112. {
  113. "api_url": DEFAULT_CONFIG.api_url,
  114. "backend_port": DEFAULT_CONFIG.backend_port,
  115. "deploy_url": DEFAULT_CONFIG.deploy_url,
  116. "frontend_port": DEFAULT_CONFIG.frontend_port,
  117. },
  118. ),
  119. # Ports set in config kwargs
  120. (
  121. {"backend_port": 8001, "frontend_port": 3001},
  122. {},
  123. {},
  124. {
  125. "api_url": "http://localhost:8001",
  126. "backend_port": 8001,
  127. "deploy_url": "http://localhost:3001",
  128. "frontend_port": 3001,
  129. },
  130. ),
  131. # Ports set in environment take precedence
  132. (
  133. {"backend_port": 8001, "frontend_port": 3001},
  134. {"BACKEND_PORT": 8002},
  135. {},
  136. {
  137. "api_url": "http://localhost:8002",
  138. "backend_port": 8002,
  139. "deploy_url": "http://localhost:3001",
  140. "frontend_port": 3001,
  141. },
  142. ),
  143. # Ports set on the command line take precedence
  144. (
  145. {"backend_port": 8001, "frontend_port": 3001},
  146. {"BACKEND_PORT": 8002},
  147. {"frontend_port": "3005"},
  148. {
  149. "api_url": "http://localhost:8002",
  150. "backend_port": 8002,
  151. "deploy_url": "http://localhost:3005",
  152. "frontend_port": 3005,
  153. },
  154. ),
  155. # api_url / deploy_url already set should not be overridden
  156. (
  157. {"api_url": "http://foo.bar:8900", "deploy_url": "http://foo.bar:3001"},
  158. {"BACKEND_PORT": 8002},
  159. {"frontend_port": "3005"},
  160. {
  161. "api_url": "http://foo.bar:8900",
  162. "backend_port": 8002,
  163. "deploy_url": "http://foo.bar:3001",
  164. "frontend_port": 3005,
  165. },
  166. ),
  167. ],
  168. )
  169. def test_replace_defaults(
  170. monkeypatch,
  171. config_kwargs,
  172. env_vars,
  173. set_persistent_vars,
  174. exp_config_values,
  175. ):
  176. """Test that the config replaces defaults with values from the environment.
  177. Args:
  178. monkeypatch: The pytest monkeypatch object.
  179. config_kwargs: The config kwargs.
  180. env_vars: The environment variables.
  181. set_persistent_vars: The values passed to config._set_persistent variables.
  182. exp_config_values: The expected config values.
  183. """
  184. mock_os_env = os.environ.copy()
  185. monkeypatch.setattr(reflex.config.os, "environ", mock_os_env) # type: ignore
  186. mock_os_env.update({k: str(v) for k, v in env_vars.items()})
  187. c = rx.Config(app_name="a", **config_kwargs)
  188. c._set_persistent(**set_persistent_vars)
  189. for key, value in exp_config_values.items():
  190. assert getattr(c, key) == value
  191. def reflex_dir_constant() -> Path:
  192. return environment.REFLEX_DIR
  193. def test_reflex_dir_env_var(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
  194. """Test that the REFLEX_DIR environment variable is used to set the Reflex.DIR constant.
  195. Args:
  196. monkeypatch: The pytest monkeypatch object.
  197. tmp_path: The pytest tmp_path object.
  198. """
  199. monkeypatch.setenv("REFLEX_DIR", str(tmp_path))
  200. mp_ctx = multiprocessing.get_context(method="spawn")
  201. with mp_ctx.Pool(processes=1) as pool:
  202. assert pool.apply(reflex_dir_constant) == tmp_path
  203. def test_interpret_enum_env() -> None:
  204. assert interpret_enum_env(Env.PROD.value, Env, "REFLEX_ENV") == Env.PROD
  205. def test_interpret_int_env() -> None:
  206. assert interpret_int_env("3001", "FRONTEND_PORT") == 3001
  207. @pytest.mark.parametrize("value, expected", [("true", True), ("false", False)])
  208. def test_interpret_bool_env(value: str, expected: bool) -> None:
  209. assert interpret_boolean_env(value, "TELEMETRY_ENABLED") == expected