testing.py 26 KB

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