testing.py 27 KB

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