testing.py 28 KB

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