testing.py 35 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 platform
  10. import re
  11. import signal
  12. import socket
  13. import socketserver
  14. import subprocess
  15. import textwrap
  16. import threading
  17. import time
  18. import types
  19. from http.server import SimpleHTTPRequestHandler
  20. from pathlib import Path
  21. from typing import (
  22. TYPE_CHECKING,
  23. Any,
  24. AsyncIterator,
  25. Callable,
  26. Coroutine,
  27. Optional,
  28. Type,
  29. TypeVar,
  30. )
  31. import psutil
  32. import uvicorn
  33. import reflex
  34. import reflex.reflex
  35. import reflex.utils.build
  36. import reflex.utils.exec
  37. import reflex.utils.format
  38. import reflex.utils.prerequisites
  39. import reflex.utils.processes
  40. from reflex.components.component import CustomComponent
  41. from reflex.config import environment
  42. from reflex.state import (
  43. BaseState,
  44. StateManager,
  45. StateManagerDisk,
  46. StateManagerMemory,
  47. StateManagerRedis,
  48. reload_state_module,
  49. )
  50. from reflex.utils import console
  51. try:
  52. from selenium import webdriver
  53. from selenium.webdriver.remote.webdriver import WebDriver
  54. if TYPE_CHECKING:
  55. from selenium.webdriver.common.options import ArgOptions
  56. from selenium.webdriver.remote.webelement import WebElement
  57. has_selenium = True
  58. except ImportError:
  59. has_selenium = False
  60. # The timeout (minutes) to check for the port.
  61. DEFAULT_TIMEOUT = 15
  62. POLL_INTERVAL = 0.25
  63. FRONTEND_POPEN_ARGS = {}
  64. T = TypeVar("T")
  65. TimeoutType = int | float | None
  66. if platform.system() == "Windows":
  67. FRONTEND_POPEN_ARGS["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue]
  68. FRONTEND_POPEN_ARGS["shell"] = True
  69. else:
  70. FRONTEND_POPEN_ARGS["start_new_session"] = True
  71. # borrowed from py3.11
  72. class chdir(contextlib.AbstractContextManager): # noqa: N801
  73. """Non thread-safe context manager to change the current working directory."""
  74. def __init__(self, path: str | Path):
  75. """Prepare contextmanager.
  76. Args:
  77. path: the path to change to
  78. """
  79. self.path = path
  80. self._old_cwd = []
  81. def __enter__(self):
  82. """Save current directory and perform chdir."""
  83. self._old_cwd.append(Path.cwd())
  84. os.chdir(self.path)
  85. def __exit__(self, *excinfo):
  86. """Change back to previous directory on stack.
  87. Args:
  88. excinfo: sys.exc_info captured in the context block
  89. """
  90. os.chdir(self._old_cwd.pop())
  91. @dataclasses.dataclass
  92. class AppHarness:
  93. """AppHarness executes a reflex app in-process for testing."""
  94. app_name: str
  95. app_source: (
  96. Callable[[], None] | types.ModuleType | str | functools.partial[Any] | None
  97. )
  98. app_path: Path
  99. app_module_path: Path
  100. app_module: types.ModuleType | None = None
  101. app_instance: reflex.App | None = None
  102. frontend_process: subprocess.Popen | None = None
  103. frontend_url: str | None = None
  104. frontend_output_thread: threading.Thread | None = None
  105. backend_thread: threading.Thread | None = None
  106. backend: uvicorn.Server | None = None
  107. state_manager: StateManager | None = None
  108. _frontends: list["WebDriver"] = dataclasses.field(default_factory=list)
  109. _decorated_pages: list = dataclasses.field(default_factory=list)
  110. @classmethod
  111. def create(
  112. cls,
  113. root: Path,
  114. app_source: (
  115. Callable[[], None] | types.ModuleType | str | functools.partial[Any] | None
  116. ) = None,
  117. app_name: str | None = None,
  118. ) -> "AppHarness":
  119. """Create an AppHarness instance at root.
  120. Args:
  121. root: the directory that will contain the app under test.
  122. app_source: if specified, the source code from this function or module is used
  123. as the main module for the app. It may also be the raw source code text, as a str.
  124. If unspecified, then root must already contain a working reflex app and will be used directly.
  125. app_name: provide the name of the app, otherwise will be derived from app_source or root.
  126. Raises:
  127. ValueError: when app_source is a string and app_name is not provided.
  128. Returns:
  129. AppHarness instance
  130. """
  131. if app_name is None:
  132. if app_source is None:
  133. app_name = root.name
  134. elif isinstance(app_source, functools.partial):
  135. keywords = app_source.keywords
  136. slug_suffix = "_".join([str(v) for v in keywords.values()])
  137. func_name = app_source.func.__name__
  138. app_name = f"{func_name}_{slug_suffix}"
  139. app_name = re.sub(r"[^a-zA-Z0-9_]", "_", app_name)
  140. elif isinstance(app_source, str):
  141. raise ValueError(
  142. "app_name must be provided when app_source is a string."
  143. )
  144. else:
  145. app_name = app_source.__name__
  146. app_name = app_name.lower()
  147. while "__" in app_name:
  148. app_name = app_name.replace("__", "_")
  149. return cls(
  150. app_name=app_name,
  151. app_source=app_source,
  152. app_path=root,
  153. app_module_path=root / app_name / f"{app_name}.py",
  154. )
  155. def get_state_name(self, state_cls_name: str) -> str:
  156. """Get the state name for the given state class name.
  157. Args:
  158. state_cls_name: The state class name
  159. Returns:
  160. The state name
  161. """
  162. return reflex.utils.format.to_snake_case(
  163. f"{self.app_name}___{self.app_name}___" + state_cls_name
  164. )
  165. def get_full_state_name(self, path: list[str]) -> str:
  166. """Get the full state name for the given state class name.
  167. Args:
  168. path: A list of state class names
  169. Returns:
  170. The full state name
  171. """
  172. # NOTE: using State.get_name() somehow causes trouble here
  173. # path = [State.get_name()] + [self.get_state_name(p) for p in path] # noqa: ERA001
  174. path = ["reflex___state____state"] + [self.get_state_name(p) for p in path]
  175. return ".".join(path)
  176. def _get_globals_from_signature(self, func: Any) -> dict[str, Any]:
  177. """Get the globals from a function or module object.
  178. Args:
  179. func: function or module object
  180. Returns:
  181. dict of globals
  182. """
  183. overrides = {}
  184. glbs = {}
  185. if not callable(func):
  186. return glbs
  187. if isinstance(func, functools.partial):
  188. overrides = func.keywords
  189. func = func.func
  190. for param in inspect.signature(func).parameters.values():
  191. if param.default is not inspect.Parameter.empty:
  192. glbs[param.name] = param.default
  193. glbs.update(overrides)
  194. return glbs
  195. def _get_source_from_app_source(self, app_source: Any) -> str:
  196. """Get the source from app_source.
  197. Args:
  198. app_source: function or module or str
  199. Returns:
  200. source code
  201. """
  202. if isinstance(app_source, str):
  203. return app_source
  204. source = inspect.getsource(app_source)
  205. source = re.sub(
  206. r"^\s*def\s+\w+\s*\(.*?\)(\s+->\s+\w+)?:", "", source, flags=re.DOTALL
  207. )
  208. return textwrap.dedent(source)
  209. def _initialize_app(self):
  210. # disable telemetry reporting for tests
  211. os.environ["TELEMETRY_ENABLED"] = "false"
  212. CustomComponent.create().get_component.cache_clear()
  213. self.app_path.mkdir(parents=True, exist_ok=True)
  214. if self.app_source is not None:
  215. app_globals = self._get_globals_from_signature(self.app_source)
  216. if isinstance(self.app_source, functools.partial):
  217. self.app_source = self.app_source.func
  218. # get the source from a function or module object
  219. source_code = "\n".join(
  220. [
  221. "\n".join(
  222. self.get_app_global_source(k, v) for k, v in app_globals.items()
  223. ),
  224. self._get_source_from_app_source(self.app_source),
  225. ]
  226. )
  227. with chdir(self.app_path):
  228. reflex.reflex._init(
  229. name=self.app_name,
  230. template=reflex.constants.Templates.DEFAULT,
  231. loglevel=reflex.constants.LogLevel.INFO,
  232. )
  233. self.app_module_path.write_text(source_code)
  234. with chdir(self.app_path):
  235. # ensure config and app are reloaded when testing different app
  236. reflex.config.get_config(reload=True)
  237. # Save decorated pages before importing the test app module
  238. before_decorated_pages = reflex.app.DECORATED_PAGES[self.app_name].copy()
  239. # Ensure the AppHarness test does not skip State assignment due to running via pytest
  240. os.environ.pop(reflex.constants.PYTEST_CURRENT_TEST, None)
  241. os.environ[reflex.constants.APP_HARNESS_FLAG] = "true"
  242. self.app_module = reflex.utils.prerequisites.get_compiled_app(
  243. # Do not reload the module for pre-existing apps (only apps generated from source)
  244. reload=self.app_source is not None
  245. )
  246. # Save the pages that were added during testing
  247. self._decorated_pages = [
  248. p
  249. for p in reflex.app.DECORATED_PAGES[self.app_name]
  250. if p not in before_decorated_pages
  251. ]
  252. self.app_instance = self.app_module.app
  253. if self.app_instance and isinstance(
  254. self.app_instance._state_manager, StateManagerRedis
  255. ):
  256. # Create our own redis connection for testing.
  257. self.state_manager = StateManagerRedis.create(self.app_instance._state) # pyright: ignore [reportArgumentType]
  258. else:
  259. self.state_manager = (
  260. self.app_instance._state_manager if self.app_instance else None
  261. )
  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: int = 0):
  281. if self.app_instance is None or self.app_instance.api 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 #noqa: T201
  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. try:
  350. line = (
  351. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  352. )
  353. # catch I/O operation on closed file.
  354. except ValueError as e:
  355. console.error(str(e))
  356. break
  357. if not line:
  358. break
  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: str, value: Any):
  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 environment.APP_HARNESS_HEADLESS.get():
  541. want_headless = True
  542. if driver_clz is None:
  543. requested_driver = environment.APP_HARNESS_DRIVER.get()
  544. driver_clz = getattr(webdriver, requested_driver) # pyright: ignore [reportPossiblyUnboundVariable]
  545. if driver_options is None:
  546. driver_options = getattr(webdriver, f"{requested_driver}Options")() # pyright: ignore [reportPossiblyUnboundVariable]
  547. if driver_clz is webdriver.Chrome: # pyright: ignore [reportPossiblyUnboundVariable]
  548. if driver_options is None:
  549. driver_options = webdriver.ChromeOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  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: # pyright: ignore [reportPossiblyUnboundVariable]
  554. if driver_options is None:
  555. driver_options = webdriver.FirefoxOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  556. if want_headless:
  557. driver_options.add_argument("-headless")
  558. elif driver_clz is webdriver.Edge: # pyright: ignore [reportPossiblyUnboundVariable]
  559. if driver_options is None:
  560. driver_options = webdriver.EdgeOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  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 := environment.APP_HARNESS_DRIVER_ARGS.get():
  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) # pyright: ignore [reportOptionalCall, reportArgumentType]
  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. ) -> str | None:
  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, 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: Path,
  749. error_page_map: dict[int, 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), # pyright: ignore [reportCallIssue]
  773. error_page_map=self.error_page_map, # pyright: ignore [reportCallIssue]
  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: threading.Thread | None = None
  782. frontend_server: Subdir404TCPServer | None = 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. env=reflex.constants.Env.PROD,
  815. )
  816. self.frontend_thread = threading.Thread(target=self._run_frontend)
  817. self.frontend_thread.start()
  818. def _wait_frontend(self):
  819. self._poll_for(lambda: self.frontend_server is not None)
  820. if self.frontend_server is None or not self.frontend_server.socket.fileno():
  821. raise RuntimeError("Frontend did not start")
  822. def _start_backend(self):
  823. if self.app_instance is None:
  824. raise RuntimeError("App was not initialized.")
  825. environment.REFLEX_SKIP_COMPILE.set(True)
  826. self.backend = uvicorn.Server(
  827. uvicorn.Config(
  828. app=self.app_instance,
  829. host="127.0.0.1",
  830. port=0,
  831. workers=reflex.utils.processes.get_num_workers(),
  832. ),
  833. )
  834. self.backend.shutdown = self._get_backend_shutdown_handler()
  835. self.backend_thread = threading.Thread(target=self.backend.run)
  836. self.backend_thread.start()
  837. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  838. try:
  839. return super()._poll_for_servers(timeout)
  840. finally:
  841. environment.REFLEX_SKIP_COMPILE.set(None)
  842. def stop(self):
  843. """Stop the frontend python webserver."""
  844. super().stop()
  845. if self.frontend_server is not None:
  846. self.frontend_server.shutdown()
  847. if self.frontend_thread is not None:
  848. self.frontend_thread.join()