1
0

testing.py 28 KB

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