from __future__ import annotations
import asyncio
import logging
from contextlib import AsyncExitStack, suppress
from types import TracebackType
from typing import Any, Callable
from urllib.parse import urlencode, urlunparse
from reactpy.backend import default as default_server
from reactpy.backend.types import BackendType
from reactpy.backend.utils import find_available_port
from reactpy.config import REACTPY_TESTING_DEFAULT_TIMEOUT
from reactpy.core.component import component
from reactpy.core.hooks import use_callback, use_effect, use_state
from reactpy.core.types import ComponentConstructor
from reactpy.testing.logs import (
LogAssertionError,
capture_reactpy_logs,
list_logged_exceptions,
)
from reactpy.utils import Ref
[docs]class BackendFixture:
"""A test fixture for running a server and imperatively displaying views
This fixture is typically used alongside async web drivers like ``playwight``.
Example:
.. code-block::
async with BackendFixture() as server:
server.mount(MyComponent)
"""
_records: list[logging.LogRecord]
_server_future: asyncio.Task[Any]
_exit_stack = AsyncExitStack()
def __init__(
self,
host: str = "127.0.0.1",
port: int | None = None,
app: Any | None = None,
implementation: BackendType[Any] | None = None,
options: Any | None = None,
timeout: float | None = None,
) -> None:
self.host = host
self.port = port or find_available_port(host)
self.mount, self._root_component = _hotswap()
self.timeout = (
REACTPY_TESTING_DEFAULT_TIMEOUT.current if timeout is None else timeout
)
if app is not None and implementation is None:
msg = "If an application instance its corresponding server implementation must be provided too."
raise ValueError(msg)
self._app = app
self.implementation = implementation or default_server
self._options = options
@property
def log_records(self) -> list[logging.LogRecord]:
"""A list of captured log records"""
return self._records
[docs] def url(self, path: str = "", query: Any | None = None) -> str:
"""Return a URL string pointing to the host and point of the server
Args:
path: the path to a resource on the server
query: a dictionary or list of query parameters
"""
return urlunparse(
[
"http",
f"{self.host}:{self.port}",
path,
"",
urlencode(query or ()),
"",
]
)
[docs] def list_logged_exceptions(
self,
pattern: str = "",
types: type[Any] | tuple[type[Any], ...] = Exception,
log_level: int = logging.ERROR,
del_log_records: bool = True,
) -> list[BaseException