1
0

testing.py 37 KB

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