testing.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. """reflex.testing - tools for testing reflex apps."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dataclasses
  5. import inspect
  6. import os
  7. import pathlib
  8. import platform
  9. import re
  10. import signal
  11. import socket
  12. import socketserver
  13. import subprocess
  14. import textwrap
  15. import threading
  16. import time
  17. import types
  18. from http.server import SimpleHTTPRequestHandler
  19. from typing import (
  20. TYPE_CHECKING,
  21. Any,
  22. Callable,
  23. Coroutine,
  24. Optional,
  25. Type,
  26. TypeVar,
  27. Union,
  28. cast,
  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.app import EventNamespace
  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. DEFAULT_TIMEOUT = 10
  52. POLL_INTERVAL = 0.25
  53. FRONTEND_LISTENING_MESSAGE = re.compile(r"ready started server on.*, url: (.*:[0-9]+)$")
  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. backend_thread: Optional[threading.Thread] = None
  93. backend: Optional[uvicorn.Server] = None
  94. _frontends: list["WebDriver"] = dataclasses.field(default_factory=list)
  95. @classmethod
  96. def create(
  97. cls,
  98. root: pathlib.Path,
  99. app_source: Optional[types.FunctionType | types.ModuleType] = None,
  100. app_name: Optional[str] = None,
  101. ) -> "AppHarness":
  102. """Create an AppHarness instance at root.
  103. Args:
  104. root: the directory that will contain the app under test.
  105. app_source: if specified, the source code from this function or module is used
  106. as the main module for the app. If unspecified, then root must already
  107. contain a working reflex app and will be used directly.
  108. app_name: provide the name of the app, otherwise will be derived from app_source or root.
  109. Returns:
  110. AppHarness instance
  111. """
  112. if app_name is None:
  113. if app_source is None:
  114. app_name = root.name.lower()
  115. else:
  116. app_name = app_source.__name__.lower()
  117. return cls(
  118. app_name=app_name,
  119. app_source=app_source,
  120. app_path=root,
  121. app_module_path=root / app_name / f"{app_name}.py",
  122. )
  123. def _initialize_app(self):
  124. os.environ["TELEMETRY_ENABLED"] = "" # disable telemetry reporting for tests
  125. self.app_path.mkdir(parents=True, exist_ok=True)
  126. if self.app_source is not None:
  127. # get the source from a function or module object
  128. source_code = textwrap.dedent(
  129. "".join(inspect.getsource(self.app_source).splitlines(True)[1:]),
  130. )
  131. with chdir(self.app_path):
  132. reflex.reflex.init(
  133. name=self.app_name,
  134. template=reflex.constants.Template.DEFAULT,
  135. loglevel=reflex.constants.LogLevel.INFO,
  136. )
  137. self.app_module_path.write_text(source_code)
  138. with chdir(self.app_path):
  139. # ensure config and app are reloaded when testing different app
  140. reflex.config.get_config(reload=True)
  141. self.app_module = reflex.utils.prerequisites.get_app(reload=True)
  142. self.app_instance = self.app_module.app
  143. def _start_backend(self, port=0):
  144. if self.app_instance is None:
  145. raise RuntimeError("App was not initialized.")
  146. self.backend = uvicorn.Server(
  147. uvicorn.Config(
  148. app=self.app_instance.api,
  149. host="127.0.0.1",
  150. port=port,
  151. )
  152. )
  153. self.backend_thread = threading.Thread(target=self.backend.run)
  154. self.backend_thread.start()
  155. def _start_frontend(self):
  156. # Set up the frontend.
  157. with chdir(self.app_path):
  158. config = reflex.config.get_config()
  159. config.api_url = "http://{0}:{1}".format(
  160. *self._poll_for_servers().getsockname(),
  161. )
  162. reflex.utils.build.setup_frontend(self.app_path)
  163. # Start the frontend.
  164. self.frontend_process = reflex.utils.processes.new_process(
  165. [reflex.utils.prerequisites.get_package_manager(), "run", "dev"],
  166. cwd=self.app_path / reflex.constants.WEB_DIR,
  167. env={"PORT": "0"},
  168. **FRONTEND_POPEN_ARGS,
  169. )
  170. def _wait_frontend(self):
  171. while self.frontend_url is None:
  172. line = (
  173. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  174. )
  175. if not line:
  176. break
  177. print(line) # for pytest diagnosis
  178. m = FRONTEND_LISTENING_MESSAGE.search(line)
  179. if m is not None:
  180. self.frontend_url = m.group(1)
  181. break
  182. if self.frontend_url is None:
  183. raise RuntimeError("Frontend did not start")
  184. def start(self) -> "AppHarness":
  185. """Start the backend in a new thread and dev frontend as a separate process.
  186. Returns:
  187. self
  188. """
  189. self._initialize_app()
  190. self._start_backend()
  191. self._start_frontend()
  192. self._wait_frontend()
  193. return self
  194. def __enter__(self) -> "AppHarness":
  195. """Contextmanager protocol for `start()`.
  196. Returns:
  197. Instance of AppHarness after calling start()
  198. """
  199. return self.start()
  200. def stop(self) -> None:
  201. """Stop the frontend and backend servers."""
  202. if self.backend is not None:
  203. self.backend.should_exit = True
  204. if self.frontend_process is not None:
  205. # https://stackoverflow.com/a/70565806
  206. frontend_children = psutil.Process(self.frontend_process.pid).children(
  207. recursive=True,
  208. )
  209. if platform.system() == "Windows":
  210. self.frontend_process.terminate()
  211. else:
  212. pgrp = os.getpgid(self.frontend_process.pid)
  213. os.killpg(pgrp, signal.SIGTERM)
  214. # kill any remaining child processes
  215. for child in frontend_children:
  216. # It's okay if the process is already gone.
  217. with contextlib.suppress(psutil.NoSuchProcess):
  218. child.terminate()
  219. _, still_alive = psutil.wait_procs(frontend_children, timeout=3)
  220. for child in still_alive:
  221. # It's okay if the process is already gone.
  222. with contextlib.suppress(psutil.NoSuchProcess):
  223. child.kill()
  224. # wait for main process to exit
  225. self.frontend_process.communicate()
  226. if self.backend_thread is not None:
  227. self.backend_thread.join()
  228. for driver in self._frontends:
  229. driver.quit()
  230. def __exit__(self, *excinfo) -> None:
  231. """Contextmanager protocol for `stop()`.
  232. Args:
  233. excinfo: sys.exc_info captured in the context block
  234. """
  235. self.stop()
  236. @staticmethod
  237. def _poll_for(
  238. target: Callable[[], T],
  239. timeout: TimeoutType = None,
  240. step: TimeoutType = None,
  241. ) -> T | bool:
  242. """Generic polling logic.
  243. Args:
  244. target: callable that returns truthy if polling condition is met.
  245. timeout: max polling time
  246. step: interval between checking target()
  247. Returns:
  248. return value of target() if truthy within timeout
  249. False if timeout elapses
  250. """
  251. if timeout is None:
  252. timeout = DEFAULT_TIMEOUT
  253. if step is None:
  254. step = POLL_INTERVAL
  255. deadline = time.time() + timeout
  256. while time.time() < deadline:
  257. success = target()
  258. if success:
  259. return success
  260. time.sleep(step)
  261. return False
  262. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  263. """Poll backend server for listening sockets.
  264. Args:
  265. timeout: how long to wait for listening socket.
  266. Returns:
  267. first active listening socket on the backend
  268. Raises:
  269. RuntimeError: when the backend hasn't started running
  270. TimeoutError: when server or sockets are not ready
  271. """
  272. if self.backend is None:
  273. raise RuntimeError("Backend is not running.")
  274. backend = self.backend
  275. # check for servers to be initialized
  276. if not self._poll_for(
  277. target=lambda: getattr(backend, "servers", False),
  278. timeout=timeout,
  279. ):
  280. raise TimeoutError("Backend servers are not initialized.")
  281. # check for sockets to be listening
  282. if not self._poll_for(
  283. target=lambda: getattr(backend.servers[0], "sockets", False),
  284. timeout=timeout,
  285. ):
  286. raise TimeoutError("Backend is not listening.")
  287. return backend.servers[0].sockets[0]
  288. def frontend(self, driver_clz: Optional[Type["WebDriver"]] = None) -> "WebDriver":
  289. """Get a selenium webdriver instance pointed at the app.
  290. Args:
  291. driver_clz: webdriver.Chrome (default), webdriver.Firefox, webdriver.Safari,
  292. webdriver.Edge, etc
  293. Returns:
  294. Instance of the given webdriver navigated to the frontend url of the app.
  295. Raises:
  296. RuntimeError: when selenium is not importable or frontend is not running
  297. """
  298. if not has_selenium:
  299. raise RuntimeError(
  300. "Frontend functionality requires `selenium` to be installed, "
  301. "and it could not be imported."
  302. )
  303. if self.frontend_url is None:
  304. raise RuntimeError("Frontend is not running.")
  305. driver = driver_clz() if driver_clz is not None else webdriver.Chrome()
  306. driver.get(self.frontend_url)
  307. self._frontends.append(driver)
  308. return driver
  309. async def emit_state_updates(self) -> list[Any]:
  310. """Send any backend state deltas to the frontend.
  311. Returns:
  312. List of awaited response from each EventNamespace.emit() call.
  313. Raises:
  314. RuntimeError: when the app hasn't started running
  315. """
  316. if self.app_instance is None or self.app_instance.sio is None:
  317. raise RuntimeError("App is not running.")
  318. event_ns: EventNamespace = cast(
  319. EventNamespace,
  320. self.app_instance.event_namespace,
  321. )
  322. pending: list[Coroutine[Any, Any, Any]] = []
  323. for state in self.app_instance.state_manager.states.values():
  324. delta = state.get_delta()
  325. if delta:
  326. update = reflex.state.StateUpdate(delta=delta, events=[], final=True)
  327. state._clean()
  328. # Emit the event.
  329. pending.append(
  330. event_ns.emit(
  331. str(reflex.constants.SocketEvent.EVENT),
  332. update.json(),
  333. to=state.get_sid(),
  334. ),
  335. )
  336. responses = []
  337. for request in pending:
  338. responses.append(await request)
  339. return responses
  340. def poll_for_content(
  341. self,
  342. element: "WebElement",
  343. timeout: TimeoutType = None,
  344. exp_not_equal: str = "",
  345. ) -> str:
  346. """Poll element.text for change.
  347. Args:
  348. element: selenium webdriver element to check
  349. timeout: how long to poll element.text
  350. exp_not_equal: exit the polling loop when the element text does not match
  351. Returns:
  352. The element text when the polling loop exited
  353. Raises:
  354. TimeoutError: when the timeout expires before text changes
  355. """
  356. if not self._poll_for(
  357. target=lambda: element.text != exp_not_equal,
  358. timeout=timeout,
  359. ):
  360. raise TimeoutError(
  361. f"{element} content remains {exp_not_equal!r} while polling.",
  362. )
  363. return element.text
  364. def poll_for_value(
  365. self,
  366. element: "WebElement",
  367. timeout: TimeoutType = None,
  368. exp_not_equal: str = "",
  369. ) -> Optional[str]:
  370. """Poll element.get_attribute("value") for change.
  371. Args:
  372. element: selenium webdriver element to check
  373. timeout: how long to poll element value attribute
  374. exp_not_equal: exit the polling loop when the value does not match
  375. Returns:
  376. The element value when the polling loop exited
  377. Raises:
  378. TimeoutError: when the timeout expires before value changes
  379. """
  380. if not self._poll_for(
  381. target=lambda: element.get_attribute("value") != exp_not_equal,
  382. timeout=timeout,
  383. ):
  384. raise TimeoutError(
  385. f"{element} content remains {exp_not_equal!r} while polling.",
  386. )
  387. return element.get_attribute("value")
  388. def poll_for_clients(self, timeout: TimeoutType = None) -> dict[str, reflex.State]:
  389. """Poll app state_manager for any connected clients.
  390. Args:
  391. timeout: how long to wait for client states
  392. Returns:
  393. active state instances when the polling loop exited
  394. Raises:
  395. RuntimeError: when the app hasn't started running
  396. TimeoutError: when the timeout expires before any states are seen
  397. """
  398. if self.app_instance is None:
  399. raise RuntimeError("App is not running.")
  400. state_manager = self.app_instance.state_manager
  401. if not self._poll_for(
  402. target=lambda: state_manager.states,
  403. timeout=timeout,
  404. ):
  405. raise TimeoutError("No states were observed while polling.")
  406. return state_manager.states
  407. class SimpleHTTPRequestHandlerCustomErrors(SimpleHTTPRequestHandler):
  408. """SimpleHTTPRequestHandler with custom error page handling."""
  409. def __init__(self, *args, error_page_map: dict[int, pathlib.Path], **kwargs):
  410. """Initialize the handler.
  411. Args:
  412. error_page_map: map of error code to error page path
  413. *args: passed through to superclass
  414. **kwargs: passed through to superclass
  415. """
  416. self.error_page_map = error_page_map
  417. super().__init__(*args, **kwargs)
  418. def send_error(
  419. self, code: int, message: str | None = None, explain: str | None = None
  420. ) -> None:
  421. """Send the error page for the given error code.
  422. If the code matches a custom error page, then message and explain are
  423. ignored.
  424. Args:
  425. code: the error code
  426. message: the error message
  427. explain: the error explanation
  428. """
  429. error_page = self.error_page_map.get(code)
  430. if error_page:
  431. self.send_response(code, message)
  432. self.send_header("Connection", "close")
  433. body = error_page.read_bytes()
  434. self.send_header("Content-Type", self.error_content_type)
  435. self.send_header("Content-Length", str(len(body)))
  436. self.end_headers()
  437. self.wfile.write(body)
  438. else:
  439. super().send_error(code, message, explain)
  440. class Subdir404TCPServer(socketserver.TCPServer):
  441. """TCPServer for SimpleHTTPRequestHandlerCustomErrors that serves from a subdir."""
  442. def __init__(
  443. self,
  444. *args,
  445. root: pathlib.Path,
  446. error_page_map: dict[int, pathlib.Path] | None,
  447. **kwargs,
  448. ):
  449. """Initialize the server.
  450. Args:
  451. root: the root directory to serve from
  452. error_page_map: map of error code to error page path
  453. *args: passed through to superclass
  454. **kwargs: passed through to superclass
  455. """
  456. self.root = root
  457. self.error_page_map = error_page_map or {}
  458. super().__init__(*args, **kwargs)
  459. def finish_request(self, request: socket.socket, client_address: tuple[str, int]):
  460. """Finish one request by instantiating RequestHandlerClass.
  461. Args:
  462. request: the requesting socket
  463. client_address: (host, port) referring to the client’s address.
  464. """
  465. print(client_address, type(client_address))
  466. self.RequestHandlerClass(
  467. request,
  468. client_address,
  469. self,
  470. directory=str(self.root), # type: ignore
  471. error_page_map=self.error_page_map, # type: ignore
  472. )
  473. class AppHarnessProd(AppHarness):
  474. """AppHarnessProd executes a reflex app in-process for testing.
  475. In prod mode, instead of running `next dev` the app is exported as static
  476. files and served via the builtin python http.server with custom 404 redirect
  477. handling. Additionally, the backend runs in multi-worker mode.
  478. """
  479. frontend_thread: Optional[threading.Thread] = None
  480. frontend_server: Optional[Subdir404TCPServer] = None
  481. def _run_frontend(self):
  482. web_root = self.app_path / reflex.constants.WEB_DIR / "_static"
  483. error_page_map = {
  484. 404: web_root / "404.html",
  485. }
  486. with Subdir404TCPServer(
  487. ("", 0),
  488. SimpleHTTPRequestHandlerCustomErrors,
  489. root=web_root,
  490. error_page_map=error_page_map,
  491. ) as self.frontend_server:
  492. self.frontend_url = "http://localhost:{1}".format(
  493. *self.frontend_server.socket.getsockname()
  494. )
  495. self.frontend_server.serve_forever()
  496. def _start_frontend(self):
  497. # Set up the frontend.
  498. with chdir(self.app_path):
  499. config = reflex.config.get_config()
  500. config.api_url = "http://{0}:{1}".format(
  501. *self._poll_for_servers().getsockname(),
  502. )
  503. reflex.reflex.export(
  504. zipping=False,
  505. frontend=True,
  506. backend=False,
  507. loglevel=reflex.constants.LogLevel.INFO,
  508. )
  509. self.frontend_thread = threading.Thread(target=self._run_frontend)
  510. self.frontend_thread.start()
  511. def _wait_frontend(self):
  512. self._poll_for(lambda: self.frontend_server is not None)
  513. if self.frontend_server is None or not self.frontend_server.socket.fileno():
  514. raise RuntimeError("Frontend did not start")
  515. def _start_backend(self):
  516. if self.app_instance is None:
  517. raise RuntimeError("App was not initialized.")
  518. os.environ[reflex.constants.SKIP_COMPILE_ENV_VAR] = "yes"
  519. self.backend = uvicorn.Server(
  520. uvicorn.Config(
  521. app=self.app_instance,
  522. host="127.0.0.1",
  523. port=0,
  524. workers=reflex.utils.processes.get_num_workers(),
  525. ),
  526. )
  527. self.backend_thread = threading.Thread(target=self.backend.run)
  528. self.backend_thread.start()
  529. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  530. try:
  531. return super()._poll_for_servers(timeout)
  532. finally:
  533. os.environ.pop(reflex.constants.SKIP_COMPILE_ENV_VAR, None)
  534. def stop(self):
  535. """Stop the frontend python webserver."""
  536. super().stop()
  537. if self.frontend_server is not None:
  538. self.frontend_server.shutdown()
  539. if self.frontend_thread is not None:
  540. self.frontend_thread.join()