"""Shared test utilities for e2e tests. Python-side port of the TS ``@chkit/clickhouse/e2e-testkit`` + ``packages/cli/src/test/e2e-testkit`` modules — see DRIFT for the parity note. The Python port intentionally omits the TS ``runCli`` / ``runCliWithRetry`` / ``waitForCliJson`` helpers: Python's convention is ``typer.testing.CliRunner`` in-process invocation, not subprocess spawn, so those helpers don't translate. What IS ported are the primitives that don't depend on the runtime shape: - ``LiveEnv`` — validated ClickHouse env resolution (hard-fail variant). - ``resolve_live_env`` — port of TS ``getLiveEnv``: the local test stack (``LOCAL_STACK_ENV``) unless ``CLICKHOUSE_URL``/``CLICKHOUSE_HOST`` is set. - ``create_prefix`` / ``create_journal_table_name`` / ``create_run_tag`` — unique name builders for isolating parallel runs. - ``quote_ident`` — backtick identifier quoter for hand-built DDL. - ``format_test_diagnostic`` — structured failure message for CLI results. Live-cluster e2e tests that grow a subprocess pattern in Python can add CLI-runner helpers on top of this module; the naming/env primitives stay runtime-agnostic here. """ from __future__ import annotations import json import os import secrets import time from collections.abc import Callable from dataclasses import dataclass from typing import Any, Protocol, TypeVar from urllib.parse import urlparse T = TypeVar("T") @dataclass(frozen=True) class LiveEnv: """Resolved ClickHouse connection info for e2e tests. Mirrors the TS ``LiveEnv`` interface. Immutable so it can be threaded through fixtures without copy-on-mutate surprises. """ clickhouse_url: str clickhouse_user: str clickhouse_password: str clickhouse_database: str # The ClickHouse in test/infra/docker-compose.yml, which `bun run infra:up` # starts on CHKIT_TEST_PORT (default 8123). _LOCAL_STACK_PORT = (os.environ.get("CHKIT_TEST_PORT") or "").strip() or "8123" LOCAL_STACK_ENV = LiveEnv( clickhouse_url=f"http://localhost:{_LOCAL_STACK_PORT}", clickhouse_user="default", clickhouse_password="chkit-ci", clickhouse_database="default", ) def get_required_env() -> LiveEnv: """Read + validate ClickHouse env vars. Raises on missing URL/password. The remote-target half of TS ``getLiveEnv`` (formerly ``getRequiredEnv``). Tests use :func:`resolve_live_env`, which falls back to the local test stack when no target is set. """ host = (os.environ.get("CLICKHOUSE_HOST") or "").strip() url = (os.environ.get("CLICKHOUSE_URL") or "").strip() if not url and host: url = f"https://{host}" user = (os.environ.get("CLICKHOUSE_USER") or "").strip() or "default" password = (os.environ.get("CLICKHOUSE_PASSWORD") or "").strip() database = (os.environ.get("CLICKHOUSE_DB") or "").strip() or "default" if not url: msg = "Missing CLICKHOUSE_URL or CLICKHOUSE_HOST" raise RuntimeError(msg) if not password: msg = "Missing CLICKHOUSE_PASSWORD" raise RuntimeError(msg) return LiveEnv( clickhouse_url=url, clickhouse_user=user, clickhouse_password=password, clickhouse_database=database, ) def resolve_live_env() -> LiveEnv: """Read the ClickHouse target from env vars, like TS ``getLiveEnv``. Without ``CLICKHOUSE_URL`` or ``CLICKHOUSE_HOST`` the tests run against the local test stack (``test/infra``, started by ``bun run infra:up``): :data:`LOCAL_STACK_ENV`. A remote target must also set ``CLICKHOUSE_PASSWORD``; a missing one raises instead of silently connecting without credentials. """ host = (os.environ.get("CLICKHOUSE_HOST") or "").strip() url = (os.environ.get("CLICKHOUSE_URL") or "").strip() if not url and host: url = f"https://{host}" if not url: return LOCAL_STACK_ENV return get_required_env() def live_env_to_client_kwargs(env: LiveEnv) -> dict[str, Any]: """Convert a :class:`LiveEnv` to ``clickhouse_connect.get_client`` kwargs. The TS testkit exposes ``createLiveExecutor(env)`` returning a ClickHouseExecutor — that shape is bound to the TS clickhouse-connect wrapper. Python's clickhouse-connect takes ``host/port/secure/...``, so we parse the URL here and hand back a kwargs dict callers can splat. """ parsed = urlparse(env.clickhouse_url) host_only = parsed.hostname or "localhost" secure = parsed.scheme == "https" port = parsed.port if parsed.port is not None else (443 if secure else 80) return { "host": host_only, "port": port, "secure": secure, "username": env.clickhouse_user, "password": env.clickhouse_password, "database": env.clickhouse_database, } def quote_ident(value: str) -> str: """Return ``value`` wrapped in backticks, escaping backslashes and backticks. Direct port of TS ``quoteIdent`` (core ``quoteIdentifier``): the name can never terminate the quoted identifier early, and the escaping matches ClickHouse's own formatting of quoted identifiers. Use when building DDL by string concatenation in a test. """ escaped = value.replace("\\", "\\\\").replace("`", "\\`") return f"`{escaped}`" def drop_database( client: Any, database: str, *, timeout: float = 30.0, interval: float = 0.5 ) -> None: """Drop a test database, re-running the DROP while it fails with ``DATABASE_NOT_EMPTY``. DROP DATABASE drops the tables the serving replica lists, then fails if a table appeared meanwhile. On a multi-replica service (ObsessionDB) that happens when the replica applies an earlier CREATE during the drop; the server answers "Try again". Any other error raises at once. ``timeout`` stops the re-runs; it does not cut short a DROP that is still running. Port of TS ``dropDatabase``. """ deadline = time.monotonic() + timeout while True: try: client.execute(f"DROP DATABASE IF EXISTS {quote_ident(database)} SYNC") return except Exception as error: if time.monotonic() >= deadline or "DATABASE_NOT_EMPTY" not in str(error): raise time.sleep(interval) def _random_suffix() -> str: """Return an 8-hex-digit random suffix (32 bits). TS uses ``Math.floor(Math.random() * 100000)``. Five decimal digits made names collide when many are built within the same millisecond (birthday bound: ~5% for 100 calls), so the Python port uses a wider suffix. """ return secrets.token_hex(4) def create_run_tag() -> str: """Return a ``__`` tag unique per invocation. Mirrors TS ``createRunTag``. Useful as a suffix on transient objects that outlive a single test (e.g. a fixture-scoped database name). """ return f"{os.getpid()}_{int(time.time() * 1000)}_{_random_suffix()}" def create_prefix(label: str = "test") -> str: """Return ``chkit_e2e_