testing.py 35 KB

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