1
0

testing.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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. print( # noqa: T201
  298. "Creating backend in a new thread..."
  299. ) # for pytest diagnosis
  300. self.backend_thread = threading.Thread(target=self.backend.run)
  301. self.backend_thread.start()
  302. print("Backend started.") # for pytest diagnosis #noqa: T201
  303. async def _reset_backend_state_manager(self):
  304. """Reset the StateManagerRedis event loop affinity.
  305. This is necessary when the backend is restarted and the state manager is a
  306. StateManagerRedis instance.
  307. Raises:
  308. RuntimeError: when the state manager cannot be reset
  309. """
  310. if (
  311. self.app_instance is not None
  312. and isinstance(
  313. self.app_instance._state_manager,
  314. StateManagerRedis,
  315. )
  316. and self.app_instance._state is not None
  317. ):
  318. with contextlib.suppress(RuntimeError):
  319. await self.app_instance._state_manager.close()
  320. self.app_instance._state_manager = StateManagerRedis.create(
  321. state=self.app_instance._state,
  322. )
  323. if not isinstance(self.app_instance.state_manager, StateManagerRedis):
  324. raise RuntimeError("Failed to reset state manager.")
  325. def _start_frontend(self):
  326. # Set up the frontend.
  327. with chdir(self.app_path):
  328. config = reflex.config.get_config()
  329. print("Polling for servers...") # for pytest diagnosis #noqa: T201
  330. config.api_url = "http://{}:{}".format(
  331. *self._poll_for_servers(timeout=30).getsockname(),
  332. )
  333. print("Building frontend...") # for pytest diagnosis #noqa: T201
  334. reflex.utils.build.setup_frontend(self.app_path)
  335. print("Frontend starting...") # for pytest diagnosis #noqa: T201
  336. # Start the frontend.
  337. self.frontend_process = reflex.utils.processes.new_process(
  338. [
  339. *reflex.utils.prerequisites.get_js_package_executor(raise_on_none=True)[
  340. 0
  341. ],
  342. "run",
  343. "dev",
  344. ],
  345. cwd=self.app_path / reflex.utils.prerequisites.get_web_dir(),
  346. env={"PORT": "0", "NO_COLOR": "1"},
  347. **FRONTEND_POPEN_ARGS,
  348. )
  349. def _wait_frontend(self):
  350. if self.frontend_process is None or self.frontend_process.stdout is None:
  351. raise RuntimeError("Frontend process has no stdout.")
  352. while self.frontend_url is None:
  353. line = self.frontend_process.stdout.readline()
  354. if not line:
  355. break
  356. print(line) # for pytest diagnosis #noqa: T201
  357. m = re.search(reflex.constants.ReactRouter.FRONTEND_LISTENING_REGEX, line)
  358. if m is not None:
  359. self.frontend_url = m.group(1)
  360. config = reflex.config.get_config()
  361. config.deploy_url = self.frontend_url
  362. break
  363. if self.frontend_url is None:
  364. raise RuntimeError("Frontend did not start")
  365. def consume_frontend_output():
  366. while True:
  367. try:
  368. line = (
  369. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  370. )
  371. # catch I/O operation on closed file.
  372. except ValueError as e:
  373. console.error(str(e))
  374. break
  375. if not line:
  376. break
  377. self.frontend_output_thread = threading.Thread(target=consume_frontend_output)
  378. self.frontend_output_thread.start()
  379. def start(self) -> AppHarness:
  380. """Start the backend in a new thread and dev frontend as a separate process.
  381. Returns:
  382. self
  383. """
  384. self._initialize_app()
  385. self._start_backend()
  386. self._start_frontend()
  387. self._wait_frontend()
  388. return self
  389. @staticmethod
  390. def get_app_global_source(key: str, value: Any):
  391. """Get the source code of a global object.
  392. If value is a function or class we render the actual
  393. source of value otherwise we assign value to key.
  394. Args:
  395. key: variable name to assign value to.
  396. value: value of the global variable.
  397. Returns:
  398. The rendered app global code.
  399. """
  400. if not inspect.isclass(value) and not inspect.isfunction(value):
  401. return f"{key} = {value!r}"
  402. return inspect.getsource(value)
  403. def __enter__(self) -> AppHarness:
  404. """Contextmanager protocol for `start()`.
  405. Returns:
  406. Instance of AppHarness after calling start()
  407. """
  408. return self.start()
  409. def stop(self) -> None:
  410. """Stop the frontend and backend servers."""
  411. # Quit browsers first to avoid any lingering events being sent during shutdown.
  412. for driver in self._frontends:
  413. driver.quit()
  414. self._reload_state_module()
  415. if self.backend is not None:
  416. self.backend.should_exit = True
  417. if self.frontend_process is not None:
  418. # https://stackoverflow.com/a/70565806
  419. frontend_children = psutil.Process(self.frontend_process.pid).children(
  420. recursive=True,
  421. )
  422. if sys.platform == "win32":
  423. self.frontend_process.terminate()
  424. else:
  425. pgrp = os.getpgid(self.frontend_process.pid)
  426. os.killpg(pgrp, signal.SIGTERM)
  427. # kill any remaining child processes
  428. for child in frontend_children:
  429. # It's okay if the process is already gone.
  430. with contextlib.suppress(psutil.NoSuchProcess):
  431. child.terminate()
  432. _, still_alive = psutil.wait_procs(frontend_children, timeout=3)
  433. for child in still_alive:
  434. # It's okay if the process is already gone.
  435. with contextlib.suppress(psutil.NoSuchProcess):
  436. child.kill()
  437. # wait for main process to exit
  438. self.frontend_process.communicate()
  439. if self.backend_thread is not None:
  440. self.backend_thread.join()
  441. if self.frontend_output_thread is not None:
  442. self.frontend_output_thread.join()
  443. def __exit__(self, *excinfo) -> None:
  444. """Contextmanager protocol for `stop()`.
  445. Args:
  446. excinfo: sys.exc_info captured in the context block
  447. """
  448. self.stop()
  449. @staticmethod
  450. def _poll_for(
  451. target: Callable[[], T],
  452. timeout: TimeoutType = None,
  453. step: TimeoutType = None,
  454. ) -> T | bool:
  455. """Generic polling logic.
  456. Args:
  457. target: callable that returns truthy if polling condition is met.
  458. timeout: max polling time
  459. step: interval between checking target()
  460. Returns:
  461. return value of target() if truthy within timeout
  462. False if timeout elapses
  463. """
  464. if timeout is None:
  465. timeout = DEFAULT_TIMEOUT
  466. if step is None:
  467. step = POLL_INTERVAL
  468. deadline = time.time() + timeout
  469. while time.time() < deadline:
  470. success = target()
  471. if success:
  472. return success
  473. time.sleep(step)
  474. return False
  475. @staticmethod
  476. async def _poll_for_async(
  477. target: Callable[[], Coroutine[None, None, T]],
  478. timeout: TimeoutType = None,
  479. step: TimeoutType = None,
  480. ) -> T | bool:
  481. """Generic polling logic for async functions.
  482. Args:
  483. target: callable that returns truthy if polling condition is met.
  484. timeout: max polling time
  485. step: interval between checking target()
  486. Returns:
  487. return value of target() if truthy within timeout
  488. False if timeout elapses
  489. """
  490. if timeout is None:
  491. timeout = DEFAULT_TIMEOUT
  492. if step is None:
  493. step = POLL_INTERVAL
  494. deadline = time.time() + timeout
  495. while time.time() < deadline:
  496. success = await target()
  497. if success:
  498. return success
  499. await asyncio.sleep(step)
  500. return False
  501. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  502. """Poll backend server for listening sockets.
  503. Args:
  504. timeout: how long to wait for listening socket.
  505. Returns:
  506. first active listening socket on the backend
  507. Raises:
  508. RuntimeError: when the backend hasn't started running
  509. TimeoutError: when server or sockets are not ready
  510. """
  511. if self.backend is None:
  512. raise RuntimeError("Backend is not running.")
  513. backend = self.backend
  514. # check for servers to be initialized
  515. if not self._poll_for(
  516. target=lambda: getattr(backend, "servers", False),
  517. timeout=timeout,
  518. ):
  519. raise TimeoutError("Backend servers are not initialized.")
  520. # check for sockets to be listening
  521. if not self._poll_for(
  522. target=lambda: getattr(backend.servers[0], "sockets", False),
  523. timeout=timeout,
  524. ):
  525. raise TimeoutError("Backend is not listening.")
  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. raise RuntimeError(
  550. "Frontend functionality requires `selenium` to be installed, "
  551. "and it could not be imported."
  552. )
  553. if self.frontend_url is None:
  554. raise RuntimeError("Frontend is not running.")
  555. want_headless = False
  556. if environment.APP_HARNESS_HEADLESS.get():
  557. want_headless = True
  558. if driver_clz is None:
  559. requested_driver = environment.APP_HARNESS_DRIVER.get()
  560. driver_clz = getattr(webdriver, requested_driver) # pyright: ignore [reportPossiblyUnboundVariable]
  561. if driver_options is None:
  562. driver_options = getattr(webdriver, f"{requested_driver}Options")() # pyright: ignore [reportPossiblyUnboundVariable]
  563. if driver_clz is webdriver.Chrome: # pyright: ignore [reportPossiblyUnboundVariable]
  564. if driver_options is None:
  565. driver_options = webdriver.ChromeOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  566. driver_options.add_argument("--class=AppHarness")
  567. if want_headless:
  568. driver_options.add_argument("--headless=new")
  569. elif driver_clz is webdriver.Firefox: # pyright: ignore [reportPossiblyUnboundVariable]
  570. if driver_options is None:
  571. driver_options = webdriver.FirefoxOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  572. if want_headless:
  573. driver_options.add_argument("-headless")
  574. elif driver_clz is webdriver.Edge: # pyright: ignore [reportPossiblyUnboundVariable]
  575. if driver_options is None:
  576. driver_options = webdriver.EdgeOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  577. if want_headless:
  578. driver_options.add_argument("headless")
  579. if driver_options is None:
  580. raise RuntimeError(f"Could not determine options for {driver_clz}")
  581. if args := environment.APP_HARNESS_DRIVER_ARGS.get():
  582. for arg in args.split(","):
  583. driver_options.add_argument(arg)
  584. if driver_option_args is not None:
  585. for arg in driver_option_args:
  586. driver_options.add_argument(arg)
  587. if driver_option_capabilities is not None:
  588. for key, value in driver_option_capabilities.items():
  589. driver_options.set_capability(key, value)
  590. if driver_kwargs is None:
  591. driver_kwargs = {}
  592. driver = driver_clz(options=driver_options, **driver_kwargs) # pyright: ignore [reportOptionalCall, reportArgumentType]
  593. driver.get(self.frontend_url)
  594. self._frontends.append(driver)
  595. return driver
  596. async def get_state(self, token: str) -> BaseState:
  597. """Get the state associated with the given token.
  598. Args:
  599. token: The state token to look up.
  600. Returns:
  601. The state instance associated with the given token
  602. Raises:
  603. RuntimeError: when the app hasn't started running
  604. """
  605. if self.state_manager is None:
  606. raise RuntimeError("state_manager is not set.")
  607. try:
  608. return await self.state_manager.get_state(token)
  609. finally:
  610. if isinstance(self.state_manager, StateManagerRedis):
  611. await self.state_manager.close()
  612. async def set_state(self, token: str, **kwargs) -> None:
  613. """Set the state associated with the given token.
  614. Args:
  615. token: The state token to set.
  616. kwargs: Attributes to set on the state.
  617. Raises:
  618. RuntimeError: when the app hasn't started running
  619. """
  620. if self.state_manager is None:
  621. raise RuntimeError("state_manager is not set.")
  622. state = await self.get_state(token)
  623. for key, value in kwargs.items():
  624. setattr(state, key, value)
  625. try:
  626. await self.state_manager.set_state(token, state)
  627. finally:
  628. if isinstance(self.state_manager, StateManagerRedis):
  629. await self.state_manager.close()
  630. @contextlib.asynccontextmanager
  631. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  632. """Modify the state associated with the given token and send update to frontend.
  633. Args:
  634. token: The state token to modify
  635. Yields:
  636. The state instance associated with the given token
  637. Raises:
  638. RuntimeError: when the app hasn't started running
  639. """
  640. if self.state_manager is None:
  641. raise RuntimeError("state_manager is not set.")
  642. if self.app_instance is None:
  643. raise RuntimeError("App is not running.")
  644. app_state_manager = self.app_instance.state_manager
  645. if isinstance(self.state_manager, StateManagerRedis):
  646. # Temporarily replace the app's state manager with our own, since
  647. # the redis connection is on the backend_thread event loop
  648. self.app_instance._state_manager = self.state_manager
  649. try:
  650. async with self.app_instance.modify_state(token) as state:
  651. yield state
  652. finally:
  653. if isinstance(self.state_manager, StateManagerRedis):
  654. self.app_instance._state_manager = app_state_manager
  655. await self.state_manager.close()
  656. def poll_for_content(
  657. self,
  658. element: WebElement,
  659. timeout: TimeoutType = None,
  660. exp_not_equal: str = "",
  661. ) -> str:
  662. """Poll element.text for change.
  663. Args:
  664. element: selenium webdriver element to check
  665. timeout: how long to poll element.text
  666. exp_not_equal: exit the polling loop when the element text does not match
  667. Returns:
  668. The element text when the polling loop exited
  669. Raises:
  670. TimeoutError: when the timeout expires before text changes
  671. """
  672. if not self._poll_for(
  673. target=lambda: element.text != exp_not_equal,
  674. timeout=timeout,
  675. ):
  676. raise TimeoutError(
  677. f"{element} content remains {exp_not_equal!r} while polling.",
  678. )
  679. return element.text
  680. def poll_for_value(
  681. self,
  682. element: WebElement,
  683. timeout: TimeoutType = None,
  684. exp_not_equal: str | Sequence[str] = "",
  685. ) -> str | None:
  686. """Poll element.get_attribute("value") for change.
  687. Args:
  688. element: selenium webdriver element to check
  689. timeout: how long to poll element value attribute
  690. exp_not_equal: exit the polling loop when the value does not match
  691. Returns:
  692. The element value when the polling loop exited
  693. Raises:
  694. TimeoutError: when the timeout expires before value changes
  695. """
  696. exp_not_equal = (
  697. (exp_not_equal,) if isinstance(exp_not_equal, str) else exp_not_equal
  698. )
  699. if not self._poll_for(
  700. target=lambda: element.get_attribute("value") not in exp_not_equal,
  701. timeout=timeout,
  702. ):
  703. raise TimeoutError(
  704. f"{element} content remains {exp_not_equal!r} while polling.",
  705. )
  706. return element.get_attribute("value")
  707. def poll_for_clients(self, timeout: TimeoutType = None) -> dict[str, BaseState]:
  708. """Poll app state_manager for any connected clients.
  709. Args:
  710. timeout: how long to wait for client states
  711. Returns:
  712. active state instances when the polling loop exited
  713. Raises:
  714. RuntimeError: when the app hasn't started running
  715. TimeoutError: when the timeout expires before any states are seen
  716. ValueError: when the state_manager is not a memory state manager
  717. """
  718. if self.app_instance is None:
  719. raise RuntimeError("App is not running.")
  720. state_manager = self.app_instance.state_manager
  721. if not isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
  722. raise ValueError("Only works with memory or disk state manager")
  723. if not self._poll_for(
  724. target=lambda: state_manager.states,
  725. timeout=timeout,
  726. ):
  727. raise TimeoutError("No states were observed while polling.")
  728. return state_manager.states
  729. @staticmethod
  730. def poll_for_result(
  731. f: Callable[[], T],
  732. exception: type[Exception] = Exception,
  733. max_attempts: int = 5,
  734. seconds_between_attempts: int = 1,
  735. ) -> T:
  736. """Poll for a result from a function.
  737. Args:
  738. f: function to call
  739. exception: exception to catch
  740. max_attempts: maximum number of attempts
  741. seconds_between_attempts: seconds to wait between
  742. Returns:
  743. Result of the function
  744. Raises:
  745. AssertionError: if the function does not return a value
  746. """
  747. attempts = 0
  748. while attempts < max_attempts:
  749. try:
  750. return f()
  751. except exception: # noqa: PERF203
  752. attempts += 1
  753. time.sleep(seconds_between_attempts)
  754. raise AssertionError("Function did not return a value")
  755. class SimpleHTTPRequestHandlerCustomErrors(SimpleHTTPRequestHandler):
  756. """SimpleHTTPRequestHandler with custom error page handling."""
  757. def __init__(self, *args, error_page_map: dict[int, Path], **kwargs):
  758. """Initialize the handler.
  759. Args:
  760. error_page_map: map of error code to error page path
  761. *args: passed through to superclass
  762. **kwargs: passed through to superclass
  763. """
  764. self.error_page_map = error_page_map
  765. super().__init__(*args, **kwargs)
  766. def send_error(
  767. self, code: int, message: str | None = None, explain: str | None = None
  768. ) -> None:
  769. """Send the error page for the given error code.
  770. If the code matches a custom error page, then message and explain are
  771. ignored.
  772. Args:
  773. code: the error code
  774. message: the error message
  775. explain: the error explanation
  776. """
  777. error_page = self.error_page_map.get(code)
  778. if error_page:
  779. self.send_response(code, message)
  780. self.send_header("Connection", "close")
  781. body = error_page.read_bytes()
  782. self.send_header("Content-Type", self.error_content_type)
  783. self.send_header("Content-Length", str(len(body)))
  784. self.end_headers()
  785. self.wfile.write(body)
  786. else:
  787. super().send_error(code, message, explain)
  788. class Subdir404TCPServer(socketserver.TCPServer):
  789. """TCPServer for SimpleHTTPRequestHandlerCustomErrors that serves from a subdir."""
  790. def __init__(
  791. self,
  792. *args,
  793. root: Path,
  794. error_page_map: dict[int, Path] | None,
  795. **kwargs,
  796. ):
  797. """Initialize the server.
  798. Args:
  799. root: the root directory to serve from
  800. error_page_map: map of error code to error page path
  801. *args: passed through to superclass
  802. **kwargs: passed through to superclass
  803. """
  804. self.root = root
  805. self.error_page_map = error_page_map or {}
  806. super().__init__(*args, **kwargs)
  807. def finish_request(self, request: socket.socket, client_address: tuple[str, int]):
  808. """Finish one request by instantiating RequestHandlerClass.
  809. Args:
  810. request: the requesting socket
  811. client_address: (host, port) referring to the client's address.
  812. """
  813. self.RequestHandlerClass(
  814. request,
  815. client_address,
  816. self,
  817. directory=str(self.root), # pyright: ignore [reportCallIssue]
  818. error_page_map=self.error_page_map, # pyright: ignore [reportCallIssue]
  819. )
  820. class AppHarnessProd(AppHarness):
  821. """AppHarnessProd executes a reflex app in-process for testing.
  822. In prod mode, instead of running `react-router dev` the app is exported as static
  823. files and served via the builtin python http.server with custom 404 redirect
  824. handling. Additionally, the backend runs in multi-worker mode.
  825. """
  826. frontend_thread: threading.Thread | None = None
  827. frontend_server: Subdir404TCPServer | None = None
  828. def _run_frontend(self):
  829. web_root = (
  830. self.app_path
  831. / reflex.utils.prerequisites.get_web_dir()
  832. / reflex.constants.Dirs.STATIC
  833. )
  834. error_page_map = {
  835. 404: web_root / "404" / "index.html",
  836. }
  837. with Subdir404TCPServer(
  838. ("", 0),
  839. SimpleHTTPRequestHandlerCustomErrors,
  840. root=web_root,
  841. error_page_map=error_page_map,
  842. ) as self.frontend_server:
  843. self.frontend_url = "http://localhost:{1}".format(
  844. *self.frontend_server.socket.getsockname()
  845. )
  846. self.frontend_server.serve_forever()
  847. def _start_frontend(self):
  848. # Set up the frontend.
  849. with chdir(self.app_path):
  850. config = reflex.config.get_config()
  851. print("Polling for servers...") # for pytest diagnosis #noqa: T201
  852. config.api_url = "http://{}:{}".format(
  853. *self._poll_for_servers(timeout=30).getsockname(),
  854. )
  855. print("Building frontend...") # for pytest diagnosis #noqa: T201
  856. get_config().loglevel = reflex.constants.LogLevel.INFO
  857. reflex.utils.prerequisites.assert_in_reflex_dir()
  858. if reflex.utils.prerequisites.needs_reinit():
  859. reflex.reflex._init(name=get_config().app_name)
  860. export(
  861. zipping=False,
  862. frontend=True,
  863. backend=False,
  864. loglevel=reflex.constants.LogLevel.INFO,
  865. env=reflex.constants.Env.PROD,
  866. )
  867. print("Frontend starting...") # for pytest diagnosis #noqa: T201
  868. self.frontend_thread = threading.Thread(target=self._run_frontend)
  869. self.frontend_thread.start()
  870. def _wait_frontend(self):
  871. self._poll_for(lambda: self.frontend_server is not None)
  872. if self.frontend_server is None or not self.frontend_server.socket.fileno():
  873. raise RuntimeError("Frontend did not start")
  874. def _start_backend(self):
  875. if self.app_asgi is None:
  876. raise RuntimeError("App was not initialized.")
  877. environment.REFLEX_SKIP_COMPILE.set(True)
  878. self.backend = uvicorn.Server(
  879. uvicorn.Config(
  880. app=self.app_asgi,
  881. host="127.0.0.1",
  882. port=0,
  883. workers=reflex.utils.processes.get_num_workers(),
  884. ),
  885. )
  886. self.backend.shutdown = self._get_backend_shutdown_handler()
  887. print( # noqa: T201
  888. "Creating backend in a new thread..."
  889. )
  890. self.backend_thread = threading.Thread(target=self.backend.run)
  891. self.backend_thread.start()
  892. print("Backend started.") # for pytest diagnosis #noqa: T201
  893. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  894. try:
  895. return super()._poll_for_servers(timeout)
  896. finally:
  897. environment.REFLEX_SKIP_COMPILE.set(None)
  898. def stop(self):
  899. """Stop the frontend python webserver."""
  900. super().stop()
  901. if self.frontend_server is not None:
  902. self.frontend_server.shutdown()
  903. if self.frontend_thread is not None:
  904. self.frontend_thread.join()