testing.py 36 KB

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