1
0

testing.py 30 KB

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