testing.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. """reflex.testing - tools for testing reflex apps."""
  2. from __future__ import annotations
  3. import asyncio
  4. import contextlib
  5. import dataclasses
  6. import functools
  7. import inspect
  8. import os
  9. import pathlib
  10. import platform
  11. import re
  12. import signal
  13. import socket
  14. import socketserver
  15. import subprocess
  16. import textwrap
  17. import threading
  18. import time
  19. import types
  20. from http.server import SimpleHTTPRequestHandler
  21. from typing import (
  22. TYPE_CHECKING,
  23. Any,
  24. AsyncIterator,
  25. Callable,
  26. Coroutine,
  27. List,
  28. Optional,
  29. Type,
  30. TypeVar,
  31. Union,
  32. )
  33. import psutil
  34. import uvicorn
  35. import reflex
  36. import reflex.reflex
  37. import reflex.utils.build
  38. import reflex.utils.exec
  39. import reflex.utils.format
  40. import reflex.utils.prerequisites
  41. import reflex.utils.processes
  42. from reflex.state import (
  43. BaseState,
  44. StateManager,
  45. StateManagerDisk,
  46. StateManagerMemory,
  47. StateManagerRedis,
  48. reload_state_module,
  49. )
  50. try:
  51. from selenium import webdriver # pyright: ignore [reportMissingImports]
  52. from selenium.webdriver.remote.webdriver import ( # pyright: ignore [reportMissingImports]
  53. WebDriver,
  54. )
  55. if TYPE_CHECKING:
  56. from selenium.webdriver.common.options import (
  57. ArgOptions, # pyright: ignore [reportMissingImports]
  58. )
  59. from selenium.webdriver.remote.webelement import ( # pyright: ignore [reportMissingImports]
  60. WebElement,
  61. )
  62. has_selenium = True
  63. except ImportError:
  64. has_selenium = False
  65. # The timeout (minutes) to check for the port.
  66. DEFAULT_TIMEOUT = 15
  67. POLL_INTERVAL = 0.25
  68. FRONTEND_POPEN_ARGS = {}
  69. T = TypeVar("T")
  70. TimeoutType = Optional[Union[int, float]]
  71. if platform.system() == "Windows":
  72. FRONTEND_POPEN_ARGS["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
  73. FRONTEND_POPEN_ARGS["shell"] = True
  74. else:
  75. FRONTEND_POPEN_ARGS["start_new_session"] = True
  76. # borrowed from py3.11
  77. class chdir(contextlib.AbstractContextManager):
  78. """Non thread-safe context manager to change the current working directory."""
  79. def __init__(self, path):
  80. """Prepare contextmanager.
  81. Args:
  82. path: the path to change to
  83. """
  84. self.path = path
  85. self._old_cwd = []
  86. def __enter__(self):
  87. """Save current directory and perform chdir."""
  88. self._old_cwd.append(os.getcwd())
  89. os.chdir(self.path)
  90. def __exit__(self, *excinfo):
  91. """Change back to previous directory on stack.
  92. Args:
  93. excinfo: sys.exc_info captured in the context block
  94. """
  95. os.chdir(self._old_cwd.pop())
  96. @dataclasses.dataclass
  97. class AppHarness:
  98. """AppHarness executes a reflex app in-process for testing."""
  99. app_name: str
  100. app_source: Optional[
  101. types.FunctionType | types.ModuleType | str | functools.partial[Any]
  102. ]
  103. app_path: pathlib.Path
  104. app_module_path: pathlib.Path
  105. app_module: Optional[types.ModuleType] = None
  106. app_instance: Optional[reflex.App] = None
  107. frontend_process: Optional[subprocess.Popen] = None
  108. frontend_url: Optional[str] = None
  109. frontend_output_thread: Optional[threading.Thread] = None
  110. backend_thread: Optional[threading.Thread] = None
  111. backend: Optional[uvicorn.Server] = None
  112. state_manager: Optional[StateManager] = None
  113. _frontends: list["WebDriver"] = dataclasses.field(default_factory=list)
  114. _decorated_pages: list = dataclasses.field(default_factory=list)
  115. @classmethod
  116. def create(
  117. cls,
  118. root: pathlib.Path,
  119. app_source: Optional[
  120. types.FunctionType | types.ModuleType | str | functools.partial[Any]
  121. ] = None,
  122. app_name: Optional[str] = None,
  123. ) -> "AppHarness":
  124. """Create an AppHarness instance at root.
  125. Args:
  126. root: the directory that will contain the app under test.
  127. app_source: if specified, the source code from this function or module is used
  128. as the main module for the app. It may also be the raw source code text, as a str.
  129. If unspecified, then root must already contain a working reflex app and will be used directly.
  130. app_name: provide the name of the app, otherwise will be derived from app_source or root.
  131. Raises:
  132. ValueError: when app_source is a string and app_name is not provided.
  133. Returns:
  134. AppHarness instance
  135. """
  136. if app_name is None:
  137. if app_source is None:
  138. app_name = root.name
  139. elif isinstance(app_source, functools.partial):
  140. keywords = app_source.keywords
  141. slug_suffix = "_".join([str(v) for v in keywords.values()])
  142. func_name = app_source.func.__name__
  143. app_name = f"{func_name}_{slug_suffix}"
  144. app_name = re.sub(r"[^a-zA-Z0-9_]", "_", app_name)
  145. elif isinstance(app_source, str):
  146. raise ValueError(
  147. "app_name must be provided when app_source is a string."
  148. )
  149. else:
  150. app_name = app_source.__name__
  151. app_name = app_name.lower()
  152. while "__" in app_name:
  153. app_name = app_name.replace("__", "_")
  154. return cls(
  155. app_name=app_name,
  156. app_source=app_source,
  157. app_path=root,
  158. app_module_path=root / app_name / f"{app_name}.py",
  159. )
  160. def get_state_name(self, state_cls_name: str) -> str:
  161. """Get the state name for the given state class name.
  162. Args:
  163. state_cls_name: The state class name
  164. Returns:
  165. The state name
  166. """
  167. return reflex.utils.format.to_snake_case(
  168. f"{self.app_name}___{self.app_name}___" + state_cls_name
  169. )
  170. def get_full_state_name(self, path: List[str]) -> str:
  171. """Get the full state name for the given state class name.
  172. Args:
  173. path: A list of state class names
  174. Returns:
  175. The full state name
  176. """
  177. # NOTE: using State.get_name() somehow causes trouble here
  178. # path = [State.get_name()] + [self.get_state_name(p) for p in path]
  179. path = ["reflex___state____state"] + [self.get_state_name(p) for p in path]
  180. return ".".join(path)
  181. def _get_globals_from_signature(self, func: Any) -> dict[str, Any]:
  182. """Get the globals from a function or module object.
  183. Args:
  184. func: function or module object
  185. Returns:
  186. dict of globals
  187. """
  188. overrides = {}
  189. glbs = {}
  190. if not callable(func):
  191. return glbs
  192. if isinstance(func, functools.partial):
  193. overrides = func.keywords
  194. func = func.func
  195. for param in inspect.signature(func).parameters.values():
  196. if param.default is not inspect.Parameter.empty:
  197. glbs[param.name] = param.default
  198. glbs.update(overrides)
  199. return glbs
  200. def _get_source_from_app_source(self, app_source: Any) -> str:
  201. """Get the source from app_source.
  202. Args:
  203. app_source: function or module or str
  204. Returns:
  205. source code
  206. """
  207. if isinstance(app_source, str):
  208. return app_source
  209. source = inspect.getsource(app_source)
  210. source = re.sub(
  211. r"^\s*def\s+\w+\s*\(.*?\)(\s+->\s+\w+)?:", "", source, flags=re.DOTALL
  212. )
  213. return textwrap.dedent(source)
  214. def _initialize_app(self):
  215. # disable telemetry reporting for tests
  216. os.environ["TELEMETRY_ENABLED"] = "false"
  217. self.app_path.mkdir(parents=True, exist_ok=True)
  218. if self.app_source is not None:
  219. app_globals = self._get_globals_from_signature(self.app_source)
  220. if isinstance(self.app_source, functools.partial):
  221. self.app_source = self.app_source.func # type: ignore
  222. # get the source from a function or module object
  223. source_code = "\n".join(
  224. [
  225. "\n".join(
  226. self.get_app_global_source(k, v) for k, v in app_globals.items()
  227. ),
  228. self._get_source_from_app_source(self.app_source),
  229. ]
  230. )
  231. with chdir(self.app_path):
  232. reflex.reflex._init(
  233. name=self.app_name,
  234. template=reflex.constants.Templates.DEFAULT,
  235. loglevel=reflex.constants.LogLevel.INFO,
  236. )
  237. self.app_module_path.write_text(source_code)
  238. with chdir(self.app_path):
  239. # ensure config and app are reloaded when testing different app
  240. reflex.config.get_config(reload=True)
  241. # Save decorated pages before importing the test app module
  242. before_decorated_pages = reflex.app.DECORATED_PAGES[self.app_name].copy()
  243. # Ensure the AppHarness test does not skip State assignment due to running via pytest
  244. os.environ.pop(reflex.constants.PYTEST_CURRENT_TEST, None)
  245. self.app_module = reflex.utils.prerequisites.get_compiled_app(
  246. # Do not reload the module for pre-existing apps (only apps generated from source)
  247. reload=self.app_source is not None
  248. )
  249. # Save the pages that were added during testing
  250. self._decorated_pages = [
  251. p
  252. for p in reflex.app.DECORATED_PAGES[self.app_name]
  253. if p not in before_decorated_pages
  254. ]
  255. self.app_instance = self.app_module.app
  256. if isinstance(self.app_instance._state_manager, StateManagerRedis):
  257. # Create our own redis connection for testing.
  258. self.state_manager = StateManagerRedis.create(self.app_instance.state)
  259. else:
  260. self.state_manager = self.app_instance._state_manager
  261. def _reload_state_module(self):
  262. """Reload the rx.State module to avoid conflict when reloading."""
  263. reload_state_module(module=f"{self.app_name}.{self.app_name}")
  264. def _get_backend_shutdown_handler(self):
  265. if self.backend is None:
  266. raise RuntimeError("Backend was not initialized.")
  267. original_shutdown = self.backend.shutdown
  268. async def _shutdown_redis(*args, **kwargs) -> None:
  269. # ensure redis is closed before event loop
  270. try:
  271. if self.app_instance is not None and isinstance(
  272. self.app_instance.state_manager, StateManagerRedis
  273. ):
  274. await self.app_instance.state_manager.close()
  275. except ValueError:
  276. pass
  277. await original_shutdown(*args, **kwargs)
  278. return _shutdown_redis
  279. def _start_backend(self, port=0):
  280. if self.app_instance is None:
  281. raise RuntimeError("App was not initialized.")
  282. self.backend = uvicorn.Server(
  283. uvicorn.Config(
  284. app=self.app_instance.api,
  285. host="127.0.0.1",
  286. port=port,
  287. )
  288. )
  289. self.backend.shutdown = self._get_backend_shutdown_handler()
  290. with chdir(self.app_path):
  291. self.backend_thread = threading.Thread(target=self.backend.run)
  292. self.backend_thread.start()
  293. async def _reset_backend_state_manager(self):
  294. """Reset the StateManagerRedis event loop affinity.
  295. This is necessary when the backend is restarted and the state manager is a
  296. StateManagerRedis instance.
  297. Raises:
  298. RuntimeError: when the state manager cannot be reset
  299. """
  300. if (
  301. self.app_instance is not None
  302. and isinstance(
  303. self.app_instance.state_manager,
  304. StateManagerRedis,
  305. )
  306. and self.app_instance.state is not None
  307. ):
  308. with contextlib.suppress(RuntimeError):
  309. await self.app_instance.state_manager.close()
  310. self.app_instance._state_manager = StateManagerRedis.create(
  311. state=self.app_instance.state,
  312. )
  313. if not isinstance(self.app_instance.state_manager, StateManagerRedis):
  314. raise RuntimeError("Failed to reset state manager.")
  315. def _start_frontend(self):
  316. # Set up the frontend.
  317. with chdir(self.app_path):
  318. config = reflex.config.get_config()
  319. config.api_url = "http://{0}:{1}".format(
  320. *self._poll_for_servers().getsockname(),
  321. )
  322. reflex.utils.build.setup_frontend(self.app_path)
  323. # Start the frontend.
  324. self.frontend_process = reflex.utils.processes.new_process(
  325. [reflex.utils.prerequisites.get_package_manager(), "run", "dev"],
  326. cwd=self.app_path / reflex.utils.prerequisites.get_web_dir(),
  327. env={"PORT": "0"},
  328. **FRONTEND_POPEN_ARGS,
  329. )
  330. def _wait_frontend(self):
  331. while self.frontend_url is None:
  332. line = (
  333. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  334. )
  335. if not line:
  336. break
  337. print(line) # for pytest diagnosis
  338. m = re.search(reflex.constants.Next.FRONTEND_LISTENING_REGEX, line)
  339. if m is not None:
  340. self.frontend_url = m.group(1)
  341. config = reflex.config.get_config()
  342. config.deploy_url = self.frontend_url
  343. break
  344. if self.frontend_url is None:
  345. raise RuntimeError("Frontend did not start")
  346. def consume_frontend_output():
  347. while True:
  348. try:
  349. line = (
  350. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  351. )
  352. # catch I/O operation on closed file.
  353. except ValueError as e:
  354. print(e)
  355. break
  356. if not line:
  357. break
  358. print(line)
  359. self.frontend_output_thread = threading.Thread(target=consume_frontend_output)
  360. self.frontend_output_thread.start()
  361. def start(self) -> "AppHarness":
  362. """Start the backend in a new thread and dev frontend as a separate process.
  363. Returns:
  364. self
  365. """
  366. self._initialize_app()
  367. self._start_backend()
  368. self._start_frontend()
  369. self._wait_frontend()
  370. return self
  371. @staticmethod
  372. def get_app_global_source(key, value):
  373. """Get the source code of a global object.
  374. If value is a function or class we render the actual
  375. source of value otherwise we assign value to key.
  376. Args:
  377. key: variable name to assign value to.
  378. value: value of the global variable.
  379. Returns:
  380. The rendered app global code.
  381. """
  382. if not inspect.isclass(value) and not inspect.isfunction(value):
  383. return f"{key} = {value!r}"
  384. return inspect.getsource(value)
  385. def __enter__(self) -> "AppHarness":
  386. """Contextmanager protocol for `start()`.
  387. Returns:
  388. Instance of AppHarness after calling start()
  389. """
  390. return self.start()
  391. def stop(self) -> None:
  392. """Stop the frontend and backend servers."""
  393. self._reload_state_module()
  394. if self.backend is not None:
  395. self.backend.should_exit = True
  396. if self.frontend_process is not None:
  397. # https://stackoverflow.com/a/70565806
  398. frontend_children = psutil.Process(self.frontend_process.pid).children(
  399. recursive=True,
  400. )
  401. if platform.system() == "Windows":
  402. self.frontend_process.terminate()
  403. else:
  404. pgrp = os.getpgid(self.frontend_process.pid)
  405. os.killpg(pgrp, signal.SIGTERM)
  406. # kill any remaining child processes
  407. for child in frontend_children:
  408. # It's okay if the process is already gone.
  409. with contextlib.suppress(psutil.NoSuchProcess):
  410. child.terminate()
  411. _, still_alive = psutil.wait_procs(frontend_children, timeout=3)
  412. for child in still_alive:
  413. # It's okay if the process is already gone.
  414. with contextlib.suppress(psutil.NoSuchProcess):
  415. child.kill()
  416. # wait for main process to exit
  417. self.frontend_process.communicate()
  418. if self.backend_thread is not None:
  419. self.backend_thread.join()
  420. if self.frontend_output_thread is not None:
  421. self.frontend_output_thread.join()
  422. for driver in self._frontends:
  423. driver.quit()
  424. # Cleanup decorated pages added during testing
  425. for page in self._decorated_pages:
  426. reflex.app.DECORATED_PAGES[self.app_name].remove(page)
  427. def __exit__(self, *excinfo) -> None:
  428. """Contextmanager protocol for `stop()`.
  429. Args:
  430. excinfo: sys.exc_info captured in the context block
  431. """
  432. self.stop()
  433. @staticmethod
  434. def _poll_for(
  435. target: Callable[[], T],
  436. timeout: TimeoutType = None,
  437. step: TimeoutType = None,
  438. ) -> T | bool:
  439. """Generic polling logic.
  440. Args:
  441. target: callable that returns truthy if polling condition is met.
  442. timeout: max polling time
  443. step: interval between checking target()
  444. Returns:
  445. return value of target() if truthy within timeout
  446. False if timeout elapses
  447. """
  448. if timeout is None:
  449. timeout = DEFAULT_TIMEOUT
  450. if step is None:
  451. step = POLL_INTERVAL
  452. deadline = time.time() + timeout
  453. while time.time() < deadline:
  454. success = target()
  455. if success:
  456. return success
  457. time.sleep(step)
  458. return False
  459. @staticmethod
  460. async def _poll_for_async(
  461. target: Callable[[], Coroutine[None, None, T]],
  462. timeout: TimeoutType = None,
  463. step: TimeoutType = None,
  464. ) -> T | bool:
  465. """Generic polling logic for async functions.
  466. Args:
  467. target: callable that returns truthy if polling condition is met.
  468. timeout: max polling time
  469. step: interval between checking target()
  470. Returns:
  471. return value of target() if truthy within timeout
  472. False if timeout elapses
  473. """
  474. if timeout is None:
  475. timeout = DEFAULT_TIMEOUT
  476. if step is None:
  477. step = POLL_INTERVAL
  478. deadline = time.time() + timeout
  479. while time.time() < deadline:
  480. success = await target()
  481. if success:
  482. return success
  483. await asyncio.sleep(step)
  484. return False
  485. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  486. """Poll backend server for listening sockets.
  487. Args:
  488. timeout: how long to wait for listening socket.
  489. Returns:
  490. first active listening socket on the backend
  491. Raises:
  492. RuntimeError: when the backend hasn't started running
  493. TimeoutError: when server or sockets are not ready
  494. """
  495. if self.backend is None:
  496. raise RuntimeError("Backend is not running.")
  497. backend = self.backend
  498. # check for servers to be initialized
  499. if not self._poll_for(
  500. target=lambda: getattr(backend, "servers", False),
  501. timeout=timeout,
  502. ):
  503. raise TimeoutError("Backend servers are not initialized.")
  504. # check for sockets to be listening
  505. if not self._poll_for(
  506. target=lambda: getattr(backend.servers[0], "sockets", False),
  507. timeout=timeout,
  508. ):
  509. raise TimeoutError("Backend is not listening.")
  510. return backend.servers[0].sockets[0]
  511. def frontend(
  512. self,
  513. driver_clz: Optional[Type["WebDriver"]] = None,
  514. driver_kwargs: dict[str, Any] | None = None,
  515. driver_options: ArgOptions | None = None,
  516. driver_option_args: List[str] | None = None,
  517. driver_option_capabilities: dict[str, Any] | None = None,
  518. ) -> "WebDriver":
  519. """Get a selenium webdriver instance pointed at the app.
  520. Args:
  521. driver_clz: webdriver.Chrome (default), webdriver.Firefox, webdriver.Safari,
  522. webdriver.Edge, etc
  523. driver_kwargs: additional keyword arguments to pass to the webdriver constructor
  524. driver_options: selenium ArgOptions instance to pass to the webdriver constructor
  525. driver_option_args: additional arguments for the webdriver options
  526. driver_option_capabilities: additional capabilities for the webdriver options
  527. Returns:
  528. Instance of the given webdriver navigated to the frontend url of the app.
  529. Raises:
  530. RuntimeError: when selenium is not importable or frontend is not running
  531. """
  532. if not has_selenium:
  533. raise RuntimeError(
  534. "Frontend functionality requires `selenium` to be installed, "
  535. "and it could not be imported."
  536. )
  537. if self.frontend_url is None:
  538. raise RuntimeError("Frontend is not running.")
  539. want_headless = False
  540. if os.environ.get("APP_HARNESS_HEADLESS"):
  541. want_headless = True
  542. if driver_clz is None:
  543. requested_driver = os.environ.get("APP_HARNESS_DRIVER", "Chrome")
  544. driver_clz = getattr(webdriver, requested_driver)
  545. if driver_options is None:
  546. driver_options = getattr(webdriver, f"{requested_driver}Options")()
  547. if driver_clz is webdriver.Chrome:
  548. if driver_options is None:
  549. driver_options = webdriver.ChromeOptions()
  550. driver_options.add_argument("--class=AppHarness")
  551. if want_headless:
  552. driver_options.add_argument("--headless=new")
  553. elif driver_clz is webdriver.Firefox:
  554. if driver_options is None:
  555. driver_options = webdriver.FirefoxOptions()
  556. if want_headless:
  557. driver_options.add_argument("-headless")
  558. elif driver_clz is webdriver.Edge:
  559. if driver_options is None:
  560. driver_options = webdriver.EdgeOptions()
  561. if want_headless:
  562. driver_options.add_argument("headless")
  563. if driver_options is None:
  564. raise RuntimeError(f"Could not determine options for {driver_clz}")
  565. if args := os.environ.get("APP_HARNESS_DRIVER_ARGS"):
  566. for arg in args.split(","):
  567. driver_options.add_argument(arg)
  568. if driver_option_args is not None:
  569. for arg in driver_option_args:
  570. driver_options.add_argument(arg)
  571. if driver_option_capabilities is not None:
  572. for key, value in driver_option_capabilities.items():
  573. driver_options.set_capability(key, value)
  574. if driver_kwargs is None:
  575. driver_kwargs = {}
  576. driver = driver_clz(options=driver_options, **driver_kwargs) # type: ignore
  577. driver.get(self.frontend_url)
  578. self._frontends.append(driver)
  579. return driver
  580. async def get_state(self, token: str) -> BaseState:
  581. """Get the state associated with the given token.
  582. Args:
  583. token: The state token to look up.
  584. Returns:
  585. The state instance associated with the given token
  586. Raises:
  587. RuntimeError: when the app hasn't started running
  588. """
  589. if self.state_manager is None:
  590. raise RuntimeError("state_manager is not set.")
  591. try:
  592. return await self.state_manager.get_state(token)
  593. finally:
  594. if isinstance(self.state_manager, StateManagerRedis):
  595. await self.state_manager.close()
  596. async def set_state(self, token: str, **kwargs) -> None:
  597. """Set the state associated with the given token.
  598. Args:
  599. token: The state token to set.
  600. kwargs: Attributes to set on the state.
  601. Raises:
  602. RuntimeError: when the app hasn't started running
  603. """
  604. if self.state_manager is None:
  605. raise RuntimeError("state_manager is not set.")
  606. state = await self.get_state(token)
  607. for key, value in kwargs.items():
  608. setattr(state, key, value)
  609. try:
  610. await self.state_manager.set_state(token, state)
  611. finally:
  612. if isinstance(self.state_manager, StateManagerRedis):
  613. await self.state_manager.close()
  614. @contextlib.asynccontextmanager
  615. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  616. """Modify the state associated with the given token and send update to frontend.
  617. Args:
  618. token: The state token to modify
  619. Yields:
  620. The state instance associated with the given token
  621. Raises:
  622. RuntimeError: when the app hasn't started running
  623. """
  624. if self.state_manager is None:
  625. raise RuntimeError("state_manager is not set.")
  626. if self.app_instance is None:
  627. raise RuntimeError("App is not running.")
  628. app_state_manager = self.app_instance.state_manager
  629. if isinstance(self.state_manager, StateManagerRedis):
  630. # Temporarily replace the app's state manager with our own, since
  631. # the redis connection is on the backend_thread event loop
  632. self.app_instance._state_manager = self.state_manager
  633. try:
  634. async with self.app_instance.modify_state(token) as state:
  635. yield state
  636. finally:
  637. if isinstance(self.state_manager, StateManagerRedis):
  638. self.app_instance._state_manager = app_state_manager
  639. await self.state_manager.close()
  640. def poll_for_content(
  641. self,
  642. element: "WebElement",
  643. timeout: TimeoutType = None,
  644. exp_not_equal: str = "",
  645. ) -> str:
  646. """Poll element.text for change.
  647. Args:
  648. element: selenium webdriver element to check
  649. timeout: how long to poll element.text
  650. exp_not_equal: exit the polling loop when the element text does not match
  651. Returns:
  652. The element text when the polling loop exited
  653. Raises:
  654. TimeoutError: when the timeout expires before text changes
  655. """
  656. if not self._poll_for(
  657. target=lambda: element.text != exp_not_equal,
  658. timeout=timeout,
  659. ):
  660. raise TimeoutError(
  661. f"{element} content remains {exp_not_equal!r} while polling.",
  662. )
  663. return element.text
  664. def poll_for_value(
  665. self,
  666. element: "WebElement",
  667. timeout: TimeoutType = None,
  668. exp_not_equal: str = "",
  669. ) -> Optional[str]:
  670. """Poll element.get_attribute("value") for change.
  671. Args:
  672. element: selenium webdriver element to check
  673. timeout: how long to poll element value attribute
  674. exp_not_equal: exit the polling loop when the value does not match
  675. Returns:
  676. The element value when the polling loop exited
  677. Raises:
  678. TimeoutError: when the timeout expires before value changes
  679. """
  680. if not self._poll_for(
  681. target=lambda: element.get_attribute("value") != exp_not_equal,
  682. timeout=timeout,
  683. ):
  684. raise TimeoutError(
  685. f"{element} content remains {exp_not_equal!r} while polling.",
  686. )
  687. return element.get_attribute("value")
  688. def poll_for_clients(self, timeout: TimeoutType = None) -> dict[str, BaseState]:
  689. """Poll app state_manager for any connected clients.
  690. Args:
  691. timeout: how long to wait for client states
  692. Returns:
  693. active state instances when the polling loop exited
  694. Raises:
  695. RuntimeError: when the app hasn't started running
  696. TimeoutError: when the timeout expires before any states are seen
  697. ValueError: when the state_manager is not a memory state manager
  698. """
  699. if self.app_instance is None:
  700. raise RuntimeError("App is not running.")
  701. state_manager = self.app_instance.state_manager
  702. if not isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
  703. raise ValueError("Only works with memory or disk state manager")
  704. if not self._poll_for(
  705. target=lambda: state_manager.states,
  706. timeout=timeout,
  707. ):
  708. raise TimeoutError("No states were observed while polling.")
  709. return state_manager.states
  710. class SimpleHTTPRequestHandlerCustomErrors(SimpleHTTPRequestHandler):
  711. """SimpleHTTPRequestHandler with custom error page handling."""
  712. def __init__(self, *args, error_page_map: dict[int, pathlib.Path], **kwargs):
  713. """Initialize the handler.
  714. Args:
  715. error_page_map: map of error code to error page path
  716. *args: passed through to superclass
  717. **kwargs: passed through to superclass
  718. """
  719. self.error_page_map = error_page_map
  720. super().__init__(*args, **kwargs)
  721. def send_error(
  722. self, code: int, message: str | None = None, explain: str | None = None
  723. ) -> None:
  724. """Send the error page for the given error code.
  725. If the code matches a custom error page, then message and explain are
  726. ignored.
  727. Args:
  728. code: the error code
  729. message: the error message
  730. explain: the error explanation
  731. """
  732. error_page = self.error_page_map.get(code)
  733. if error_page:
  734. self.send_response(code, message)
  735. self.send_header("Connection", "close")
  736. body = error_page.read_bytes()
  737. self.send_header("Content-Type", self.error_content_type)
  738. self.send_header("Content-Length", str(len(body)))
  739. self.end_headers()
  740. self.wfile.write(body)
  741. else:
  742. super().send_error(code, message, explain)
  743. class Subdir404TCPServer(socketserver.TCPServer):
  744. """TCPServer for SimpleHTTPRequestHandlerCustomErrors that serves from a subdir."""
  745. def __init__(
  746. self,
  747. *args,
  748. root: pathlib.Path,
  749. error_page_map: dict[int, pathlib.Path] | None,
  750. **kwargs,
  751. ):
  752. """Initialize the server.
  753. Args:
  754. root: the root directory to serve from
  755. error_page_map: map of error code to error page path
  756. *args: passed through to superclass
  757. **kwargs: passed through to superclass
  758. """
  759. self.root = root
  760. self.error_page_map = error_page_map or {}
  761. super().__init__(*args, **kwargs)
  762. def finish_request(self, request: socket.socket, client_address: tuple[str, int]):
  763. """Finish one request by instantiating RequestHandlerClass.
  764. Args:
  765. request: the requesting socket
  766. client_address: (host, port) referring to the client’s address.
  767. """
  768. self.RequestHandlerClass(
  769. request,
  770. client_address,
  771. self,
  772. directory=str(self.root), # type: ignore
  773. error_page_map=self.error_page_map, # type: ignore
  774. )
  775. class AppHarnessProd(AppHarness):
  776. """AppHarnessProd executes a reflex app in-process for testing.
  777. In prod mode, instead of running `next dev` the app is exported as static
  778. files and served via the builtin python http.server with custom 404 redirect
  779. handling. Additionally, the backend runs in multi-worker mode.
  780. """
  781. frontend_thread: Optional[threading.Thread] = None
  782. frontend_server: Optional[Subdir404TCPServer] = None
  783. def _run_frontend(self):
  784. web_root = (
  785. self.app_path
  786. / reflex.utils.prerequisites.get_web_dir()
  787. / reflex.constants.Dirs.STATIC
  788. )
  789. error_page_map = {
  790. 404: web_root / "404.html",
  791. }
  792. with Subdir404TCPServer(
  793. ("", 0),
  794. SimpleHTTPRequestHandlerCustomErrors,
  795. root=web_root,
  796. error_page_map=error_page_map,
  797. ) as self.frontend_server:
  798. self.frontend_url = "http://localhost:{1}".format(
  799. *self.frontend_server.socket.getsockname()
  800. )
  801. self.frontend_server.serve_forever()
  802. def _start_frontend(self):
  803. # Set up the frontend.
  804. with chdir(self.app_path):
  805. config = reflex.config.get_config()
  806. config.api_url = "http://{0}:{1}".format(
  807. *self._poll_for_servers().getsockname(),
  808. )
  809. reflex.reflex.export(
  810. zipping=False,
  811. frontend=True,
  812. backend=False,
  813. loglevel=reflex.constants.LogLevel.INFO,
  814. )
  815. self.frontend_thread = threading.Thread(target=self._run_frontend)
  816. self.frontend_thread.start()
  817. def _wait_frontend(self):
  818. self._poll_for(lambda: self.frontend_server is not None)
  819. if self.frontend_server is None or not self.frontend_server.socket.fileno():
  820. raise RuntimeError("Frontend did not start")
  821. def _start_backend(self):
  822. if self.app_instance is None:
  823. raise RuntimeError("App was not initialized.")
  824. os.environ[reflex.constants.SKIP_COMPILE_ENV_VAR] = "yes"
  825. self.backend = uvicorn.Server(
  826. uvicorn.Config(
  827. app=self.app_instance,
  828. host="127.0.0.1",
  829. port=0,
  830. workers=reflex.utils.processes.get_num_workers(),
  831. ),
  832. )
  833. self.backend.shutdown = self._get_backend_shutdown_handler()
  834. self.backend_thread = threading.Thread(target=self.backend.run)
  835. self.backend_thread.start()
  836. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  837. try:
  838. return super()._poll_for_servers(timeout)
  839. finally:
  840. os.environ.pop(reflex.constants.SKIP_COMPILE_ENV_VAR, None)
  841. def stop(self):
  842. """Stop the frontend python webserver."""
  843. super().stop()
  844. if self.frontend_server is not None:
  845. self.frontend_server.shutdown()
  846. if self.frontend_thread is not None:
  847. self.frontend_thread.join()