testing.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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. os.environ["TELEMETRY_ENABLED"] = "" # disable telemetry reporting for tests
  216. self.app_path.mkdir(parents=True, exist_ok=True)
  217. if self.app_source is not None:
  218. app_globals = self._get_globals_from_signature(self.app_source)
  219. if isinstance(self.app_source, functools.partial):
  220. self.app_source = self.app_source.func # type: ignore
  221. # get the source from a function or module object
  222. source_code = "\n".join(
  223. [
  224. "\n".join(
  225. self.get_app_global_source(k, v) for k, v in app_globals.items()
  226. ),
  227. self._get_source_from_app_source(self.app_source),
  228. ]
  229. )
  230. with chdir(self.app_path):
  231. reflex.reflex._init(
  232. name=self.app_name,
  233. template=reflex.constants.Templates.DEFAULT,
  234. loglevel=reflex.constants.LogLevel.INFO,
  235. )
  236. self.app_module_path.write_text(source_code)
  237. with chdir(self.app_path):
  238. # ensure config and app are reloaded when testing different app
  239. reflex.config.get_config(reload=True)
  240. # Save decorated pages before importing the test app module
  241. before_decorated_pages = reflex.app.DECORATED_PAGES[self.app_name].copy()
  242. # Ensure the AppHarness test does not skip State assignment due to running via pytest
  243. os.environ.pop(reflex.constants.PYTEST_CURRENT_TEST, None)
  244. self.app_module = reflex.utils.prerequisites.get_compiled_app(
  245. # Do not reload the module for pre-existing apps (only apps generated from source)
  246. reload=self.app_source is not None
  247. )
  248. # Save the pages that were added during testing
  249. self._decorated_pages = [
  250. p
  251. for p in reflex.app.DECORATED_PAGES[self.app_name]
  252. if p not in before_decorated_pages
  253. ]
  254. self.app_instance = self.app_module.app
  255. if isinstance(self.app_instance._state_manager, StateManagerRedis):
  256. # Create our own redis connection for testing.
  257. self.state_manager = StateManagerRedis.create(self.app_instance.state)
  258. elif isinstance(self.app_instance._state_manager, StateManagerDisk):
  259. self.state_manager = StateManagerDisk.create(self.app_instance.state)
  260. else:
  261. self.state_manager = self.app_instance._state_manager
  262. def _reload_state_module(self):
  263. """Reload the rx.State module to avoid conflict when reloading."""
  264. reload_state_module(module=f"{self.app_name}.{self.app_name}")
  265. def _get_backend_shutdown_handler(self):
  266. if self.backend is None:
  267. raise RuntimeError("Backend was not initialized.")
  268. original_shutdown = self.backend.shutdown
  269. async def _shutdown_redis(*args, **kwargs) -> None:
  270. # ensure redis is closed before event loop
  271. try:
  272. if self.app_instance is not None and isinstance(
  273. self.app_instance.state_manager, StateManagerRedis
  274. ):
  275. await self.app_instance.state_manager.close()
  276. except ValueError:
  277. pass
  278. await original_shutdown(*args, **kwargs)
  279. return _shutdown_redis
  280. def _start_backend(self, port=0):
  281. if self.app_instance is None:
  282. raise RuntimeError("App was not initialized.")
  283. self.backend = uvicorn.Server(
  284. uvicorn.Config(
  285. app=self.app_instance.api,
  286. host="127.0.0.1",
  287. port=port,
  288. )
  289. )
  290. self.backend.shutdown = self._get_backend_shutdown_handler()
  291. with chdir(self.app_path):
  292. self.backend_thread = threading.Thread(target=self.backend.run)
  293. self.backend_thread.start()
  294. async def _reset_backend_state_manager(self):
  295. """Reset the StateManagerRedis event loop affinity.
  296. This is necessary when the backend is restarted and the state manager is a
  297. StateManagerRedis instance.
  298. Raises:
  299. RuntimeError: when the state manager cannot be reset
  300. """
  301. if (
  302. self.app_instance is not None
  303. and isinstance(
  304. self.app_instance.state_manager,
  305. StateManagerRedis,
  306. )
  307. and self.app_instance.state is not None
  308. ):
  309. with contextlib.suppress(RuntimeError):
  310. await self.app_instance.state_manager.close()
  311. self.app_instance._state_manager = StateManagerRedis.create(
  312. state=self.app_instance.state,
  313. )
  314. if not isinstance(self.app_instance.state_manager, StateManagerRedis):
  315. raise RuntimeError("Failed to reset state manager.")
  316. def _start_frontend(self):
  317. # Set up the frontend.
  318. with chdir(self.app_path):
  319. config = reflex.config.get_config()
  320. config.api_url = "http://{0}:{1}".format(
  321. *self._poll_for_servers().getsockname(),
  322. )
  323. reflex.utils.build.setup_frontend(self.app_path)
  324. # Start the frontend.
  325. self.frontend_process = reflex.utils.processes.new_process(
  326. [reflex.utils.prerequisites.get_package_manager(), "run", "dev"],
  327. cwd=self.app_path / reflex.utils.prerequisites.get_web_dir(),
  328. env={"PORT": "0"},
  329. **FRONTEND_POPEN_ARGS,
  330. )
  331. def _wait_frontend(self):
  332. while self.frontend_url is None:
  333. line = (
  334. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  335. )
  336. if not line:
  337. break
  338. print(line) # for pytest diagnosis
  339. m = re.search(reflex.constants.Next.FRONTEND_LISTENING_REGEX, line)
  340. if m is not None:
  341. self.frontend_url = m.group(1)
  342. config = reflex.config.get_config()
  343. config.deploy_url = self.frontend_url
  344. break
  345. if self.frontend_url is None:
  346. raise RuntimeError("Frontend did not start")
  347. def consume_frontend_output():
  348. while True:
  349. line = (
  350. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  351. )
  352. if not line:
  353. break
  354. print(line)
  355. self.frontend_output_thread = threading.Thread(target=consume_frontend_output)
  356. self.frontend_output_thread.start()
  357. def start(self) -> "AppHarness":
  358. """Start the backend in a new thread and dev frontend as a separate process.
  359. Returns:
  360. self
  361. """
  362. self._initialize_app()
  363. self._start_backend()
  364. self._start_frontend()
  365. self._wait_frontend()
  366. return self
  367. @staticmethod
  368. def get_app_global_source(key, value):
  369. """Get the source code of a global object.
  370. If value is a function or class we render the actual
  371. source of value otherwise we assign value to key.
  372. Args:
  373. key: variable name to assign value to.
  374. value: value of the global variable.
  375. Returns:
  376. The rendered app global code.
  377. """
  378. if not inspect.isclass(value) and not inspect.isfunction(value):
  379. return f"{key} = {value!r}"
  380. return inspect.getsource(value)
  381. def __enter__(self) -> "AppHarness":
  382. """Contextmanager protocol for `start()`.
  383. Returns:
  384. Instance of AppHarness after calling start()
  385. """
  386. return self.start()
  387. def stop(self) -> None:
  388. """Stop the frontend and backend servers."""
  389. self._reload_state_module()
  390. if self.backend is not None:
  391. self.backend.should_exit = True
  392. if self.frontend_process is not None:
  393. # https://stackoverflow.com/a/70565806
  394. frontend_children = psutil.Process(self.frontend_process.pid).children(
  395. recursive=True,
  396. )
  397. if platform.system() == "Windows":
  398. self.frontend_process.terminate()
  399. else:
  400. pgrp = os.getpgid(self.frontend_process.pid)
  401. os.killpg(pgrp, signal.SIGTERM)
  402. # kill any remaining child processes
  403. for child in frontend_children:
  404. # It's okay if the process is already gone.
  405. with contextlib.suppress(psutil.NoSuchProcess):
  406. child.terminate()
  407. _, still_alive = psutil.wait_procs(frontend_children, timeout=3)
  408. for child in still_alive:
  409. # It's okay if the process is already gone.
  410. with contextlib.suppress(psutil.NoSuchProcess):
  411. child.kill()
  412. # wait for main process to exit
  413. self.frontend_process.communicate()
  414. if self.backend_thread is not None:
  415. self.backend_thread.join()
  416. if self.frontend_output_thread is not None:
  417. self.frontend_output_thread.join()
  418. for driver in self._frontends:
  419. driver.quit()
  420. # Cleanup decorated pages added during testing
  421. for page in self._decorated_pages:
  422. reflex.app.DECORATED_PAGES[self.app_name].remove(page)
  423. def __exit__(self, *excinfo) -> None:
  424. """Contextmanager protocol for `stop()`.
  425. Args:
  426. excinfo: sys.exc_info captured in the context block
  427. """
  428. self.stop()
  429. @staticmethod
  430. def _poll_for(
  431. target: Callable[[], T],
  432. timeout: TimeoutType = None,
  433. step: TimeoutType = None,
  434. ) -> T | bool:
  435. """Generic polling logic.
  436. Args:
  437. target: callable that returns truthy if polling condition is met.
  438. timeout: max polling time
  439. step: interval between checking target()
  440. Returns:
  441. return value of target() if truthy within timeout
  442. False if timeout elapses
  443. """
  444. if timeout is None:
  445. timeout = DEFAULT_TIMEOUT
  446. if step is None:
  447. step = POLL_INTERVAL
  448. deadline = time.time() + timeout
  449. while time.time() < deadline:
  450. success = target()
  451. if success:
  452. return success
  453. time.sleep(step)
  454. return False
  455. @staticmethod
  456. async def _poll_for_async(
  457. target: Callable[[], Coroutine[None, None, T]],
  458. timeout: TimeoutType = None,
  459. step: TimeoutType = None,
  460. ) -> T | bool:
  461. """Generic polling logic for async functions.
  462. Args:
  463. target: callable that returns truthy if polling condition is met.
  464. timeout: max polling time
  465. step: interval between checking target()
  466. Returns:
  467. return value of target() if truthy within timeout
  468. False if timeout elapses
  469. """
  470. if timeout is None:
  471. timeout = DEFAULT_TIMEOUT
  472. if step is None:
  473. step = POLL_INTERVAL
  474. deadline = time.time() + timeout
  475. while time.time() < deadline:
  476. success = await target()
  477. if success:
  478. return success
  479. await asyncio.sleep(step)
  480. return False
  481. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  482. """Poll backend server for listening sockets.
  483. Args:
  484. timeout: how long to wait for listening socket.
  485. Returns:
  486. first active listening socket on the backend
  487. Raises:
  488. RuntimeError: when the backend hasn't started running
  489. TimeoutError: when server or sockets are not ready
  490. """
  491. if self.backend is None:
  492. raise RuntimeError("Backend is not running.")
  493. backend = self.backend
  494. # check for servers to be initialized
  495. if not self._poll_for(
  496. target=lambda: getattr(backend, "servers", False),
  497. timeout=timeout,
  498. ):
  499. raise TimeoutError("Backend servers are not initialized.")
  500. # check for sockets to be listening
  501. if not self._poll_for(
  502. target=lambda: getattr(backend.servers[0], "sockets", False),
  503. timeout=timeout,
  504. ):
  505. raise TimeoutError("Backend is not listening.")
  506. return backend.servers[0].sockets[0]
  507. def frontend(
  508. self,
  509. driver_clz: Optional[Type["WebDriver"]] = None,
  510. driver_kwargs: dict[str, Any] | None = None,
  511. driver_options: ArgOptions | None = None,
  512. driver_option_args: List[str] | None = None,
  513. driver_option_capabilities: dict[str, Any] | None = None,
  514. ) -> "WebDriver":
  515. """Get a selenium webdriver instance pointed at the app.
  516. Args:
  517. driver_clz: webdriver.Chrome (default), webdriver.Firefox, webdriver.Safari,
  518. webdriver.Edge, etc
  519. driver_kwargs: additional keyword arguments to pass to the webdriver constructor
  520. driver_options: selenium ArgOptions instance to pass to the webdriver constructor
  521. driver_option_args: additional arguments for the webdriver options
  522. driver_option_capabilities: additional capabilities for the webdriver options
  523. Returns:
  524. Instance of the given webdriver navigated to the frontend url of the app.
  525. Raises:
  526. RuntimeError: when selenium is not importable or frontend is not running
  527. """
  528. if not has_selenium:
  529. raise RuntimeError(
  530. "Frontend functionality requires `selenium` to be installed, "
  531. "and it could not be imported."
  532. )
  533. if self.frontend_url is None:
  534. raise RuntimeError("Frontend is not running.")
  535. want_headless = False
  536. if os.environ.get("APP_HARNESS_HEADLESS"):
  537. want_headless = True
  538. if driver_clz is None:
  539. requested_driver = os.environ.get("APP_HARNESS_DRIVER", "Chrome")
  540. driver_clz = getattr(webdriver, requested_driver)
  541. if driver_options is None:
  542. driver_options = getattr(webdriver, f"{requested_driver}Options")()
  543. if driver_clz is webdriver.Chrome:
  544. if driver_options is None:
  545. driver_options = webdriver.ChromeOptions()
  546. driver_options.add_argument("--class=AppHarness")
  547. if want_headless:
  548. driver_options.add_argument("--headless=new")
  549. elif driver_clz is webdriver.Firefox:
  550. if driver_options is None:
  551. driver_options = webdriver.FirefoxOptions()
  552. if want_headless:
  553. driver_options.add_argument("-headless")
  554. elif driver_clz is webdriver.Edge:
  555. if driver_options is None:
  556. driver_options = webdriver.EdgeOptions()
  557. if want_headless:
  558. driver_options.add_argument("headless")
  559. if driver_options is None:
  560. raise RuntimeError(f"Could not determine options for {driver_clz}")
  561. if args := os.environ.get("APP_HARNESS_DRIVER_ARGS"):
  562. for arg in args.split(","):
  563. driver_options.add_argument(arg)
  564. if driver_option_args is not None:
  565. for arg in driver_option_args:
  566. driver_options.add_argument(arg)
  567. if driver_option_capabilities is not None:
  568. for key, value in driver_option_capabilities.items():
  569. driver_options.set_capability(key, value)
  570. if driver_kwargs is None:
  571. driver_kwargs = {}
  572. driver = driver_clz(options=driver_options, **driver_kwargs) # type: ignore
  573. driver.get(self.frontend_url)
  574. self._frontends.append(driver)
  575. return driver
  576. async def get_state(self, token: str) -> BaseState:
  577. """Get the state associated with the given token.
  578. Args:
  579. token: The state token to look up.
  580. Returns:
  581. The state instance associated with the given token
  582. Raises:
  583. RuntimeError: when the app hasn't started running
  584. """
  585. if self.state_manager is None:
  586. raise RuntimeError("state_manager is not set.")
  587. try:
  588. return await self.state_manager.get_state(token)
  589. finally:
  590. if isinstance(self.state_manager, StateManagerRedis):
  591. await self.state_manager.close()
  592. async def set_state(self, token: str, **kwargs) -> None:
  593. """Set the state associated with the given token.
  594. Args:
  595. token: The state token to set.
  596. kwargs: Attributes to set on the state.
  597. Raises:
  598. RuntimeError: when the app hasn't started running
  599. """
  600. if self.state_manager is None:
  601. raise RuntimeError("state_manager is not set.")
  602. state = await self.get_state(token)
  603. for key, value in kwargs.items():
  604. setattr(state, key, value)
  605. try:
  606. await self.state_manager.set_state(token, state)
  607. finally:
  608. if isinstance(self.state_manager, StateManagerRedis):
  609. await self.state_manager.close()
  610. @contextlib.asynccontextmanager
  611. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  612. """Modify the state associated with the given token and send update to frontend.
  613. Args:
  614. token: The state token to modify
  615. Yields:
  616. The state instance associated with the given token
  617. Raises:
  618. RuntimeError: when the app hasn't started running
  619. """
  620. if self.state_manager is None:
  621. raise RuntimeError("state_manager is not set.")
  622. if self.app_instance is None:
  623. raise RuntimeError("App is not running.")
  624. app_state_manager = self.app_instance.state_manager
  625. if isinstance(self.state_manager, StateManagerRedis):
  626. # Temporarily replace the app's state manager with our own, since
  627. # the redis connection is on the backend_thread event loop
  628. self.app_instance._state_manager = self.state_manager
  629. try:
  630. async with self.app_instance.modify_state(token) as state:
  631. yield state
  632. finally:
  633. if isinstance(self.state_manager, StateManagerRedis):
  634. self.app_instance._state_manager = app_state_manager
  635. await self.state_manager.close()
  636. def poll_for_content(
  637. self,
  638. element: "WebElement",
  639. timeout: TimeoutType = None,
  640. exp_not_equal: str = "",
  641. ) -> str:
  642. """Poll element.text for change.
  643. Args:
  644. element: selenium webdriver element to check
  645. timeout: how long to poll element.text
  646. exp_not_equal: exit the polling loop when the element text does not match
  647. Returns:
  648. The element text when the polling loop exited
  649. Raises:
  650. TimeoutError: when the timeout expires before text changes
  651. """
  652. if not self._poll_for(
  653. target=lambda: element.text != exp_not_equal,
  654. timeout=timeout,
  655. ):
  656. raise TimeoutError(
  657. f"{element} content remains {exp_not_equal!r} while polling.",
  658. )
  659. return element.text
  660. def poll_for_value(
  661. self,
  662. element: "WebElement",
  663. timeout: TimeoutType = None,
  664. exp_not_equal: str = "",
  665. ) -> Optional[str]:
  666. """Poll element.get_attribute("value") for change.
  667. Args:
  668. element: selenium webdriver element to check
  669. timeout: how long to poll element value attribute
  670. exp_not_equal: exit the polling loop when the value does not match
  671. Returns:
  672. The element value when the polling loop exited
  673. Raises:
  674. TimeoutError: when the timeout expires before value changes
  675. """
  676. if not self._poll_for(
  677. target=lambda: element.get_attribute("value") != exp_not_equal,
  678. timeout=timeout,
  679. ):
  680. raise TimeoutError(
  681. f"{element} content remains {exp_not_equal!r} while polling.",
  682. )
  683. return element.get_attribute("value")
  684. def poll_for_clients(self, timeout: TimeoutType = None) -> dict[str, BaseState]:
  685. """Poll app state_manager for any connected clients.
  686. Args:
  687. timeout: how long to wait for client states
  688. Returns:
  689. active state instances when the polling loop exited
  690. Raises:
  691. RuntimeError: when the app hasn't started running
  692. TimeoutError: when the timeout expires before any states are seen
  693. ValueError: when the state_manager is not a memory state manager
  694. """
  695. if self.app_instance is None:
  696. raise RuntimeError("App is not running.")
  697. state_manager = self.app_instance.state_manager
  698. if not isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
  699. raise ValueError("Only works with memory or disk state manager")
  700. if not self._poll_for(
  701. target=lambda: state_manager.states,
  702. timeout=timeout,
  703. ):
  704. raise TimeoutError("No states were observed while polling.")
  705. return state_manager.states
  706. class SimpleHTTPRequestHandlerCustomErrors(SimpleHTTPRequestHandler):
  707. """SimpleHTTPRequestHandler with custom error page handling."""
  708. def __init__(self, *args, error_page_map: dict[int, pathlib.Path], **kwargs):
  709. """Initialize the handler.
  710. Args:
  711. error_page_map: map of error code to error page path
  712. *args: passed through to superclass
  713. **kwargs: passed through to superclass
  714. """
  715. self.error_page_map = error_page_map
  716. super().__init__(*args, **kwargs)
  717. def send_error(
  718. self, code: int, message: str | None = None, explain: str | None = None
  719. ) -> None:
  720. """Send the error page for the given error code.
  721. If the code matches a custom error page, then message and explain are
  722. ignored.
  723. Args:
  724. code: the error code
  725. message: the error message
  726. explain: the error explanation
  727. """
  728. error_page = self.error_page_map.get(code)
  729. if error_page:
  730. self.send_response(code, message)
  731. self.send_header("Connection", "close")
  732. body = error_page.read_bytes()
  733. self.send_header("Content-Type", self.error_content_type)
  734. self.send_header("Content-Length", str(len(body)))
  735. self.end_headers()
  736. self.wfile.write(body)
  737. else:
  738. super().send_error(code, message, explain)
  739. class Subdir404TCPServer(socketserver.TCPServer):
  740. """TCPServer for SimpleHTTPRequestHandlerCustomErrors that serves from a subdir."""
  741. def __init__(
  742. self,
  743. *args,
  744. root: pathlib.Path,
  745. error_page_map: dict[int, pathlib.Path] | None,
  746. **kwargs,
  747. ):
  748. """Initialize the server.
  749. Args:
  750. root: the root directory to serve from
  751. error_page_map: map of error code to error page path
  752. *args: passed through to superclass
  753. **kwargs: passed through to superclass
  754. """
  755. self.root = root
  756. self.error_page_map = error_page_map or {}
  757. super().__init__(*args, **kwargs)
  758. def finish_request(self, request: socket.socket, client_address: tuple[str, int]):
  759. """Finish one request by instantiating RequestHandlerClass.
  760. Args:
  761. request: the requesting socket
  762. client_address: (host, port) referring to the client’s address.
  763. """
  764. self.RequestHandlerClass(
  765. request,
  766. client_address,
  767. self,
  768. directory=str(self.root), # type: ignore
  769. error_page_map=self.error_page_map, # type: ignore
  770. )
  771. class AppHarnessProd(AppHarness):
  772. """AppHarnessProd executes a reflex app in-process for testing.
  773. In prod mode, instead of running `next dev` the app is exported as static
  774. files and served via the builtin python http.server with custom 404 redirect
  775. handling. Additionally, the backend runs in multi-worker mode.
  776. """
  777. frontend_thread: Optional[threading.Thread] = None
  778. frontend_server: Optional[Subdir404TCPServer] = None
  779. def _run_frontend(self):
  780. web_root = (
  781. self.app_path
  782. / reflex.utils.prerequisites.get_web_dir()
  783. / reflex.constants.Dirs.STATIC
  784. )
  785. error_page_map = {
  786. 404: web_root / "404.html",
  787. }
  788. with Subdir404TCPServer(
  789. ("", 0),
  790. SimpleHTTPRequestHandlerCustomErrors,
  791. root=web_root,
  792. error_page_map=error_page_map,
  793. ) as self.frontend_server:
  794. self.frontend_url = "http://localhost:{1}".format(
  795. *self.frontend_server.socket.getsockname()
  796. )
  797. self.frontend_server.serve_forever()
  798. def _start_frontend(self):
  799. # Set up the frontend.
  800. with chdir(self.app_path):
  801. config = reflex.config.get_config()
  802. config.api_url = "http://{0}:{1}".format(
  803. *self._poll_for_servers().getsockname(),
  804. )
  805. reflex.reflex.export(
  806. zipping=False,
  807. frontend=True,
  808. backend=False,
  809. loglevel=reflex.constants.LogLevel.INFO,
  810. )
  811. self.frontend_thread = threading.Thread(target=self._run_frontend)
  812. self.frontend_thread.start()
  813. def _wait_frontend(self):
  814. self._poll_for(lambda: self.frontend_server is not None)
  815. if self.frontend_server is None or not self.frontend_server.socket.fileno():
  816. raise RuntimeError("Frontend did not start")
  817. def _start_backend(self):
  818. if self.app_instance is None:
  819. raise RuntimeError("App was not initialized.")
  820. os.environ[reflex.constants.SKIP_COMPILE_ENV_VAR] = "yes"
  821. self.backend = uvicorn.Server(
  822. uvicorn.Config(
  823. app=self.app_instance,
  824. host="127.0.0.1",
  825. port=0,
  826. workers=reflex.utils.processes.get_num_workers(),
  827. ),
  828. )
  829. self.backend.shutdown = self._get_backend_shutdown_handler()
  830. self.backend_thread = threading.Thread(target=self.backend.run)
  831. self.backend_thread.start()
  832. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  833. try:
  834. return super()._poll_for_servers(timeout)
  835. finally:
  836. os.environ.pop(reflex.constants.SKIP_COMPILE_ENV_VAR, None)
  837. def stop(self):
  838. """Stop the frontend python webserver."""
  839. super().stop()
  840. if self.frontend_server is not None:
  841. self.frontend_server.shutdown()
  842. if self.frontend_thread is not None:
  843. self.frontend_thread.join()