testing.py 29 KB

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