testing.py 28 KB

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