=============== LIBRARY RULES =============== From library maintainers: - Run it with no installation: uvx uci-test-suite . The engine is a full command line, not only a binary path: uvx uci-test-suite python my_engine.py, or uvx uci-test-suite -- java -jar engine.jar --threads 1 (suite options go before the --). - Checks are grouped into protocol levels L0-L6; L0-L2 together are the minimum a playable UCI engine must implement. Select levels with --level/-l: -l 2, -l 0-2, -l 0-2,5. Without it, every level runs. - --list prints every check with its level and purpose; --json writes machine-readable results (level, name, status, message, details, timings) to stdout with the human report on stderr. - The exit code is non-zero if any selected check failed, so a CI step can gate on it directly. - L4 optional features (Ponder, MultiPV, UCI_Chess960, UCI_AnalyseMode) are skipped, not failed, when the engine does not declare them; a failure at L0-L3 or L5 is a real conformance bug. - It tests protocol correctness only, never playing strength. ### Example: Using RawSession with stockfish Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/09-checks-session.md Shows constructing a RawUciClient, starting it, creating a RawSession with a timeout, accessing the handshake, setting a position, and getting a search result. Finally quits the client to clean up. ```python from uci_test_suite.transport import RawUciClient from uci_test_suite.checks.session import RawSession client = RawUciClient(["/usr/local/bin/stockfish"], default_timeout=5.0) client.start() session = RawSession(client, timeout=5.0) try: h = session.handshake print(h.id.get("name"), [o.name for o in h.options]) session.set_position() result = session.go("movetime 200") # -> SearchResult print(result.bestmove.move, len(result.infos)) finally: client.quit() ``` -------------------------------- ### ProcessSession client() usage example Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/09-checks-session.md Shows how to create a ProcessSession and use its client() context manager to start a RawUciClient on a new engine process. The example sends the UCI command and expects the 'uciok' response. ```python from uci_test_suite.checks.session import ProcessSession session = ProcessSession(command=("/usr/local/bin/stockfish",), timeout=5.0) with session.client() as client: client.send("uci") client.expect("uciok") ``` -------------------------------- ### Protocol parsing examples Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/03-protocol.md Code examples from the protocol API documentation. ```python def parse_id(line: str) -> IdLine | None: """Parse an ``id`` line.""" ``` ```python def parse_option(line: str) -> OptionSpec | None: """ Parse an ``option`` line. The option name spans everything between ``name`` and ``type``; a value spans everything up to the next ``default``/``min``/``max``/``var`` keyword. Engine output line to parse. **Returns:** an `OptionSpec` when the line is of the `option` kind; `None` for lines of another kind. **Throws `ProtocolError`** when: - the option line does not start with `name`, - the line has no `type`, - the name is empty, - there is no type value, - the type value is not one of `OptionType`'s five values, - an unexpected token appears after the type (before any `default`/`min`/`max`/`var` keyword), - `min` or `max` is not an integer. Valid keywords after the type are `default`, `min`, `max` and `var`; a `var` value consumes everything up to the next keyword, and repeated `var`s accumulate into the `var` tuple. """ ``` ```python from uci_test_suite.protocol import parse_option spec = parse_option("option name Hash type spin default 16 min 1 max 128") assert spec.name == "Hash" and spec.type == "spin" assert (spec.min, spec.max, spec.default) == (1, 128, "16") # Declarations that contradict the spec can be surfaced after parsing: assert parse_option("option name T type button default 1").issues() == ( "button option carries a default/min/max/var", ) ``` -------------------------------- ### start() -> None Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md Spawns the engine process and begins collecting its output. Raises TransportError if called twice or if the process cannot be started. ```APIDOC ## start() -> None ### Description Spawns the engine process and begins collecting its output. Raises `TransportError("already started")` if called twice, and wraps any `OSError` in `TransportError(f"cannot start {' '.join(self.command)}: {error}")`. Uses `subprocess.Popen` with `text=True`, `encoding="utf-8"`, `errors="replace"`, line-buffered pipes, and `CREATE_NO_WINDOW` on Windows; stdin is reconfigured to a bare `\n` newline for UCI commands. Two daemon threads pump stdout and stderr. ### Method start ### Parameters None ### Returns None ### Exceptions - `TransportError` - if already started or if the process cannot be started. ``` -------------------------------- ### CLI usage examples Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/01-cli.md Shell examples for running the suite. The first block shows level selection (`-l 2`, `-l 0-2,5`) and passing engine options after `--`. The second shows `--json` output redirection and checking the exit code (0 = all passed, 1 = at least one failed). ```sh # One level uci-test-suite -l 2 ./engine # An inclusive range plus a single level: the minimum UCI engine + robustness uci-test-suite -l 0-2,5 ./engine # Engine that needs an interpreter; suite options before the '--' uci-test-suite --timeout 30 -- java -jar engine.jar --threads 1 ``` ```sh # Machine-readable run: results JSON to stdout, human report to stderr; gate CI on the exit code uci-test-suite --json ./engine > results.json echo $? # 0 = all selected checks passed, 1 = at least one failed ``` -------------------------------- ### CLI examples for uci-test-suite Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/configuration.md Three example invocations of the CLI: minimum UCI engine levels, levels plus machine-readable output, and a timeout with a Java engine command. ```sh uci-test-suite -l 0-2 ./engine # minimum UCI engine levels ``` ```sh uci-test-suite -l 0-2,5 --json ./engine # levels plus machine-readable output ``` ```sh uci-test-suite --timeout 30 -- java -jar engine.jar --threads 1 ``` -------------------------------- ### Setup and Development Workflow Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/README.md Commands to clone the repository, initialize the virtual environment, run tests, and perform code quality checks. ```bash # Clone the repository git clone https://github.com/AnglerfishChess/uci-test-suite.git # ... or # git clone git@github.com:AnglerfishChess/uci-test-suite.git cd uci-test-suite # Create the virtual environment and install the package and its development dependencies uv sync # Run the tests; those needing a real engine are skipped unless `stockfish` is on PATH uv run pytest # Check code style and types uvx ruff check . uvx ruff format --check . uvx pyrefly check ``` -------------------------------- ### is_lan_move usage example Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/03-protocol.md Example usage of is_lan_move, demonstrating valid moves, promotions, and invalid tokens like null moves and out-of-range squares. ```python from uci_test_suite.protocol import is_lan_move assert is_lan_move("e2e4") assert is_lan_move("e7e8q") # promotion assert not is_lan_move("0000") assert not is_lan_move("e9e4") ``` -------------------------------- ### run_suite(engine, *, timeout=DEFAULT_TIMEOUT, levels=None) -> list[CheckResult] Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/05-runner.md Runs every registered check of the selected levels against the engine, lowest level first. Each level gets its own engine process; a crashed engine fails the rest of that level immediately instead of waiting for timeouts, and the next level starts afresh. ```APIDOC ## `run_suite(engine, *, timeout=DEFAULT_TIMEOUT, levels=None) -> list[CheckResult]` ### Description Runs every registered check of the selected levels against the engine, lowest level first. Each level gets its own engine process; a crashed engine fails the rest of that level immediately instead of waiting for timeouts, and the next level starts afresh. ### Parameters - **engine** (`str | Sequence[str]`) - Required - Engine executable, or its whole command line as an argv sequence. A string is wrapped into a 1-tuple. - **timeout** (`float`) - Optional - Default: `DEFAULT_TIMEOUT` (10.0) - Seconds allowed for a single exchange with the engine; also scales every check's own budget. - **levels** (`Collection[Level] | None`) - Optional - Default: `None` - Levels to run; all of them when `None`. ### Returns One `CheckResult` per attempted or dead check, in run order (lowest level first, registration order within a level). A check that could not be attempted at all is returned as a `FAIL` result with `duration=0.0`. ### Behavior Details - The per-check budget scale is `timeout / DEFAULT_TIMEOUT`. Each check's `budget` is multiplied by this scale; the transport's `default_timeout` and each session's `timeout` are set to the scaled budget. - Levels are executed in ascending order; `checks_of(set(levels))` supplies the checks. - Per level, the internal `_Sessions` object opens at most one shared `Driver.RAW` session and one shared `Driver.CLIENT` (`esca`) session, lazily, on first use; `Driver.FRESH` checks get a process of their own that is quit when the check ends; `Driver.PROCESS` checks manage their own processes via the `ProcessSession`. - When a shared session's engine dies, `_Sessions` records a refusal reason (`"the engine is no longer running"`, or the transport/`esca` error from first start) and every remaining check of that driver in the level is immediately marked failed with that reason. - After each check on the shared raw session, `sessions.settle(check)` calls `resync()` to put the engine back into an idle, responsive state; failures there are logged, not fatal. - The verdict conversion in `_run` maps exceptions as follows: `CheckSkipped` → `Status.SKIP`, `CheckFailure` → `Status.FAIL`, `EngineDied` → `Status.FAIL` with `{"returncode": ...}` details, any other `TransportError` → `Status.FAIL` with `{"error": type(error).__name__}`, any unexpected `Exception` → `Status.FAIL` with the exception's class name and message (logged with `logger.exception`, so a broken check never aborts the suite). ### Example ```python from uci_test_suite.runner import run_suite from uci_test_suite.levels import Level # Everything at levels L0-L2 (the minimum UCI engine) with a 20 s exchange timeout results = run_suite(["/usr/local/bin/stockfish"], timeout=20.0, levels={Level.PROCESS, Level.HANDSHAKE, Level.PLAY}) for result in results: print(result.status, result.name, result.message) ``` ```python import json from uci_test_suite.runner import run_suite from uci_test_suite.report import payload # Run all levels and hand the JSON-ready payload to a CI gate results = run_suite("my_engine --threads 1") blob = json.dumps(payload(results), indent=2, default=str) failed = sum(1 for r in results if r.status.name == "FAIL") ``` ``` -------------------------------- ### format_levels usage example Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/02-levels.md Example usage of format_levels with a set of levels, producing the output 'L0-L2, L5'. ```python from uci_test_suite.levels import Level, format_levels print(format_levels({Level.PROCESS, Level.HANDSHAKE, Level.PLAY, Level.ROBUSTNESS})) # L0-L2, L5 ``` -------------------------------- ### How to catch EngineTimeout using RawUciClient Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/errors.md Shows how to start a RawUciClient and catch EngineTimeout, then inspect the lines received before the timeout. ```python from uci_test_suite.transport import RawUciClient, EngineTimeout client = RawUciClient(["/usr/local/bin/stockfish"], default_timeout=1.0) client.start() try: client.expect("uciok", timeout=5.0) except EngineTimeout as error: print("saw", len(error.lines), "lines before timeout") finally: client.quit() ``` -------------------------------- ### RawSession.__init__ Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/configuration.md Constructor for a raw session, wrapping a started transport client with a default timeout. ```APIDOC ## RawSession.__init__ ### Description Initializes a raw session wrapper around a started transport client. ### Method Constructor ### Endpoint `RawSession.__init__` ### Parameters #### Constructor Parameters - **client** (`RawUciClient`) - Required - A *started* transport client. - **timeout** (`float`) - Optional, default `10.0` - Seconds allowed for a single exchange, unless a call overrides it. ### Notes Method-level defaults: `sync(timeout=None)`, `go(arguments="", timeout=None)`, `collect_search(timeout=None, settle=SETTLE_TIME)`, `set_position(*, fen=None, moves=())`, `set_option(name, value=None)`, `collect_for(duration)`. ``` -------------------------------- ### Context manager (__enter__ / __exit__) Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md Allows using the Transport as a context manager: __enter__ calls start(), __exit__ calls quit(). ```APIDOC ## Context manager (__enter__ / __exit__) ### Description Allows using the Transport as a context manager: `__enter__` calls `start()`, `__exit__` calls `quit()`. ### Method __enter__ / __exit__ ### Parameters None ### Returns - `Self` - from `__enter__` - `None` - from `__exit__` ``` -------------------------------- ### ProcessSession Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/09-checks-session.md Documentation for the ProcessSession class, including its fields, context manager methods, and an example usage. ```APIDOC ## ProcessSession ### Description A frozen dataclass representing the engine as a command line, spawned afresh for each use. It provides context managers to start a new engine process and obtain a client or session. ### Fields - `command` (tuple[str, ...]) - Required - Engine argv. - `timeout` (float) - Optional, default `10.0` - Transport timeout for the spawned process. ### Methods #### `client()` - Signature: `@contextmanager def client(self) -> Iterator[RawUciClient]` - Yields: A started `RawUciClient` on a new engine process, quit on exit. #### `session()` - Signature: `@contextmanager def session(self) -> Iterator[RawSession]` - Yields: A `RawSession` on a new engine process, quit on exit. ### Example ```python from uci_test_suite.checks.session import ProcessSession session = ProcessSession(command=("/usr/local/bin/stockfish",), timeout=5.0) with session.client() as client: client.send("uci") client.expect("uciok") ``` ``` -------------------------------- ### is_alive() -> bool Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md Returns whether the engine process is started and still running. ```APIDOC ## is_alive() -> bool ### Description Returns whether the engine process is started and still running. ### Method is_alive ### Parameters None ### Returns - `bool` - True if the engine process is started and still running. ``` -------------------------------- ### Example: extending the suite with a custom check Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/08-checks-registry.md Shows how to register a custom check using the raw_check decorator and then retrieve it with checks_of. The check measures engine latency and returns an Outcome with details. ```python from uci_test_suite.checks.registry import raw_check, checks_of from uci_test_suite.checks.base import Outcome from uci_test_suite.checks.session import RawSession from uci_test_suite.levels import Level @raw_check("custom_isready_after_start", Level.HANDSHAKE, budget=10.0) def check_custom(session: RawSession) -> Outcome: latency = session.sync() return Outcome(f"readyok after {latency:.3f} s", details={"latency_s": round(latency, 3)}) for check in checks_of({Level.HANDSHAKE}): print(check.name, "->", check.purpose) ``` -------------------------------- ### parse_levels usage example Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/02-levels.md Example usage of parse_levels with a range selector and a mixed selector. Shows that ranges are equivalent to listing each level individually. ```python from uci_test_suite.levels import parse_levels assert parse_levels("0-2") == parse_levels("0,1,2") parse_levels("0-2,5") # {PROCESS, HANDSHAKE, PLAY, ROBUSTNESS} ``` -------------------------------- ### get_version() function signature Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/01-cli.md Returns the version of the installed suite, or "unknown" if the import fails. The function body is not shown in the source; only the signature and docstring are displayed. ```python def get_version() -> str: """The version of the installed suite, or ``"unknown"``.""" ``` -------------------------------- ### Context manager methods Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md The context manager implementation for the Transport class, which automatically starts the engine on entry and quits it on exit. ```python def __enter__(self) -> Self: # transport.py:286 -> self.start() def __exit__(self, exc_type, exc_value, traceback) -> None: # transport.py:290 -> self.quit() ``` -------------------------------- ### Timeout handling with RawUciClient Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md Demonstrates handling timeouts and engine death when reading lines from a UCI engine. Starts the client manually, attempts to read a line, and catches EngineTimeout or EngineDied exceptions. The default_timeout is set to 2.0 seconds. ```python from uci_test_suite.transport import RawUciClient, EngineTimeout, EngineDied client = RawUciClient(["/usr/local/bin/stockfish"], default_timeout=2.0) client.start() try: client.read_line() # no output expected -> times out loudly except EngineTimeout as error: print("silent engine:", len(error.lines), "lines seen") except EngineDied as died: print("engine died, exit code:", died.returncode) finally: client.quit() ``` -------------------------------- ### kill() -> None Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md Terminates the engine process, hard (process.kill()), setting killed = True. No-op when not started or already exited. ```APIDOC ## kill() -> None ### Description Terminates the engine process, hard (`process.kill()`), setting `killed = True`. No-op when not started or already exited. ### Method kill ### Parameters None ### Returns None ``` -------------------------------- ### RawSession Constructor Signature Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/09-checks-session.md Constructor for RawSession. Takes a started RawUciClient and an optional timeout (default 10.0) for each exchange unless overridden. Raises TransportError when the engine dies. ```python def __init__(self, client: RawUciClient, *, timeout: float = 10.0): ``` -------------------------------- ### quit(timeout: float = DEFAULT_QUIT_TIMEOUT) -> int | None Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md Asks the engine to quit, waits for it to exit, and kills it if it lingers. Closes the pipes and returns the exit code (None if never started). ```APIDOC ## quit(timeout: float = DEFAULT_QUIT_TIMEOUT) -> int | None ### Description Asks the engine to quit (`send("quit")` if it is still running; `TransportError` from a dead engine is swallowed), waits for it to exit, and kills it if it lingers. Closes the pipes and returns the exit code (`None` if never started). ### Method quit ### Parameters #### Query Parameters - `timeout` (float) - Optional - Default: `DEFAULT_QUIT_TIMEOUT` (5.0) - Seconds for the engine to exit by itself. ### Returns - `int | None` - The exit code, or `None` if never started. ``` -------------------------------- ### Catching ProtocolError when parsing UCI lines Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/errors.md Example showing how to catch ProtocolError when parsing UCI option lines. It creates a RawUciClient, sends 'uci', expects 'uciok', and iterates over lines to parse each option, printing any malformed option lines. ```python from uci_test_suite.protocol import ProtocolError from uci_test_suite.transport import RawUciClient with RawUciClient(["/usr/local/bin/stockfish"]) as client: client.send("uci") lines = client.expect("uciok") for line in lines: try: parse_option(line.text) except ProtocolError as error: print("malformed option line:", error) ``` -------------------------------- ### Run with uv Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/README.md Use this command if you have the repository cloned locally. ```sh uv run uci-test-suite /usr/local/bin/stockfish ``` -------------------------------- ### Run with uvx Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/README.md The recommended way to run the test suite using uvx, which handles dependencies in an automatically created virtual environment. ```sh uvx uci-test-suite@latest /usr/local/bin/stockfish ``` -------------------------------- ### parse_levels ValueError example Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/02-levels.md Example of parse_levels raising ValueError for a level outside the valid range 0-6. The error message is printed. ```python try: parse_levels("7") except ValueError as error: print(error) # level 7 does not exist; levels are 0 to 6 ``` -------------------------------- ### verify_responsive Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/10-checks-verify.md Function that verifies the engine responds to the `isready` command within a timeout, returning the response time in seconds. ```APIDOC ## `verify_responsive(session: RawSession, after: str, timeout: float | None = None) -> float` Source: `checks/verify.py:32-47` ```python def verify_responsive(session: RawSession, after: str, timeout: float | None = None) -> float: """Seconds the engine took to answer ``isready``; fails when it dies or stays silent.""" ``` | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `session` | `RawSession` | yes | — | Session to probe with `isready`. | | `after` | `str` | no | — | What just happened, used in the failure message ("engine stopped answering isready after …"). | | `timeout` | `float \| None` | no | `None` (session default) | Optional per-call timeout. | **Returns:** seconds the engine took to answer `isready` with `readyok`. **Throws `CheckFailure`:** with `CheckFailure(f"engine stopped answering isready after {after}", after=after)` on `EngineTimeout`, or `CheckFailure(f"engine died after {after}: {died}", after=after, returncode=died.returncode)` on `EngineDied`. ``` -------------------------------- ### RawUciClient.__init__ signature Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/configuration.md Constructor for RawUciClient. Accepts an engine executable or argv sequence, with optional default_timeout (default 10.0) and cwd. Method-level defaults: expect(timeout=None), read_line(timeout=None), poll_line(timeout=None) fall back to default_timeout; drain(quiet_for=0.1, timeout=2.0); quit(timeout=DEFAULT_QUIT_TIMEOUT) where DEFAULT_QUIT_TIMEOUT = 5.0. ```python def __init__( self, command: str | Sequence[str], *, default_timeout: float = DEFAULT_TIMEOUT, cwd: str | os.PathLike[str] | None = None, ): ``` -------------------------------- ### TransportError exception class definition Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/errors.md Base class for all transport failures. Raised directly by RawUciClient.start when already started or when subprocess.Popen fails. ```python class TransportError(Exception): """Base class for transport failures.""" ``` -------------------------------- ### CLI [uci-test-suite] Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/01-cli.md Command-line interface for running the UCI test suite against a chess engine. It accepts an engine command line, optional level selectors, and various output/behavior flags. ```APIDOC ## CLI [uci-test-suite] ### Description Command-line interface for running the UCI test suite against a chess engine. It accepts an engine command line, optional level selectors, and various output/behavior flags. ### Method CLI (Click application) ### Endpoint `uci-test-suite [OPTIONS] ENGINE...` ### Parameters #### Positional Arguments - **engine** (tuple[str, ...]) - Required - Whole engine command line; may start with flags of its own (put `--` before them). #### Options - **--level, -l** (tuple[str, ...]) - Optional - Repeatable; levels to run; grammar of `LEVEL_RANGE_SYNTAX`. Default: all levels. - **--list** (bool) - Optional - List the checks by level and exit. - **--json** (bool) - Optional - Write results as JSON to stdout; everything else to stderr. - **--debug/--no-debug** (bool) - Optional - Enable debug logging. Default: false. - **--quiet/--no-quiet** (bool) - Optional - Show only failed checks. Default: false. - **--verbose/--no-verbose** (bool) - Optional - Show the details each check recorded. Default: false. - **--timeout** (float) - Optional - Seconds to wait for a single engine response; also scales every check's own time budget. Default: 10.0 (min 0.1). - **--version** - Optional - Show the version and exit. - **-h, --help** - Optional - Show help message and exit. ### Request Example ```sh uci-test-suite -l 2 ./engine ``` ### Response #### Success Response (exit 0) - All selected checks passed. #### Response Example ```sh uci-test-suite --json ./engine > results.json echo $? # 0 = all selected checks passed ``` #### Error Response (exit 1) - At least one check failed. #### Error Response (usage errors) - Missing engine: `click.UsageError` - Bad level selector: `click.BadParameter` - Non-executable engine: `click.BadParameter` ### Notes - With `--json`, results JSON goes to stdout; human output goes to stderr. - Exit code 1 if any check failed; otherwise 0. - Usage errors exit with Click's standard usage-error status. ``` -------------------------------- ### Raising CheckSkipped and CheckFailure in a Check Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/errors.md Example of raising CheckSkipped or CheckFailure inside a check function. The runner converts these exceptions into test verdicts. ```python from uci_test_suite.checks.base import CheckFailure, CheckSkipped, Outcome from uci_test_suite.checks.registry import raw_check from uci_test_suite.checks.session import RawSession from uci_test_suite.levels import Level @raw_check("custom_feature", Level.OPTIONAL, budget=10.0) def check_custom(session: RawSession) -> Outcome: if session.handshake.option("MyFeature") is None: raise CheckSkipped("engine does not declare the MyFeature option") if not session.sync() > 0: raise CheckFailure("engine answered isready instantly", latency_s=session.sync()) return Outcome("feature works") ``` -------------------------------- ### RawSession Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/09-checks-session.md Documentation for the RawSession class, including its constructor, handshake property, and all public methods. ```APIDOC ## RawSession ### Description A session wrapper around a raw UCI transport client that handles the UCI handshake and provides high-level methods for sending commands and collecting search results. ### Constructor ```python def __init__(self, client: RawUciClient, *, timeout: float = 10.0): ``` #### Parameters - **client** (RawUciClient) - Required - A *started* transport client. - **timeout** (float) - Optional, default `10.0` - Seconds allowed for a single exchange, unless a call overrides it. ### Handshake Property ```python @property def handshake(self) -> Handshake: ``` Sends `uci`, expects `uciok` within `self.timeout`, then drains for another `HANDSHAKE_TAIL` seconds. Parses `id` and `option` lines, classifies the rest, and builds the `Handshake`. Any exception during the first attempt is remembered and re-raised on every subsequent access (no retry). ### Methods #### sync ```python def sync(self, timeout: float | None = None) -> float ``` Sends `isready` (after handshake), waits for `readyok`, returns seconds taken. #### send ```python def send(self, command: str) -> None ``` Writes one command line, without waiting for anything. #### new_game ```python def new_game(self) -> None ``` Sends `ucinewgame` then `sync()`s. #### set_option ```python def set_option(self, name: str, value: str | None = None) -> None ``` Sends `setoption name {name}` (bare, when `value is None`) or `setoption name {name} value {value}`, then `sync()`s. #### set_position ```python def set_position(self, *, fen: str | None = None, moves: Sequence[str] = ()) -> None ``` Sends `position startpos` (no FEN) or `position fen {fen}`, plus `moves {…}` when given, then `sync()`s. #### go ```python def go(self, arguments: str = "", timeout: float | None = None) -> SearchResult ``` `send_go(arguments)` then `collect_search(timeout=timeout)`. #### send_go ```python def send_go(self, arguments: str = "") -> None ``` Starts a search without waiting for its result (`go {arguments}`.rstrip()). #### stop ```python def stop(self) -> None ``` Asks the engine to end the current search (`stop`). #### collect_search ```python def collect_search(self, timeout: float | None = None, settle: float = SETTLE_TIME) -> SearchResult ``` Waits for the `bestmove` of a running search, then keeps listening for `settle` seconds; parses `info`/`bestmove` lines, collects invalid lines and extra bestmoves. Raises `EngineTimeout` when no `bestmove` arrived in time, and `ProtocolError` for an unparsable `bestmove` line. #### collect_for ```python def collect_for(self, duration: float) -> list[Line] ``` Collects every line the engine emits over the next `duration` seconds. #### resync ```python def resync(self) -> None ``` Returns the engine to an idle, responsive state whatever the previous check left behind: sends `stop`, drains, and `sync()`s (up to `min(self.timeout, 5.0)` s); swallows `EngineTimeout`. ### Example ```python from uci_test_suite.transport import RawUciClient from uci_test_suite.checks.session import RawSession client = RawUciClient(["/usr/local/bin/stockfish"], default_timeout=5.0) client.start() session = RawSession(client, timeout=5.0) try: h = session.handshake print(h.id.get("name"), [o.name for o in h.options]) session.set_position() result = session.go("movetime 200") # -> SearchResult print(result.bestmove.move, len(result.infos)) finally: client.quit() ``` ``` -------------------------------- ### RawUciClient.__init__ Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/configuration.md Constructor for the raw UCI transport client, accepting an engine command and optional timeout and working directory. ```APIDOC ## RawUciClient.__init__ ### Description Initializes a raw UCI transport client with an engine executable or argv sequence. ### Method Constructor ### Endpoint `RawUciClient.__init__` ### Parameters #### Constructor Parameters - **command** (`str | Sequence[str]`) - Required - Engine executable or argv sequence. - **default_timeout** (`float`) - Optional, default `10.0` - Seconds to wait for a line when a call does not specify its own timeout. - **cwd** (`str | os.PathLike[str] | None`) - Optional, default `None` - Working directory for the engine process. ### Notes Method-level defaults: `expect(timeout=None)`, `read_line(timeout=None)`, `poll_line(timeout=None)` fall back to `default_timeout`; `drain(quiet_for=0.1, timeout=2.0)`; `quit(timeout=DEFAULT_QUIT_TIMEOUT)` where `DEFAULT_QUIT_TIMEOUT = 5.0`. ``` -------------------------------- ### fresh_check decorator definition Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/08-checks-registry.md Registers a check that talks to the engine over the raw transport on a process of its own. The check takes a RawSession but runs on an engine process started for this check alone, with driver=Driver.FRESH. ```python def fresh_check(name: str, level: Level, budget: float = DEFAULT_BUDGET) -> Callable[[RawCheckFunc], RawCheckFunc]: """Register a check that talks to the engine over the raw transport, on a process of its own.""" ``` -------------------------------- ### Run suite with selected levels and timeout Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/05-runner.md Runs all checks at levels L0-L2 (the minimum UCI engine) with a 20-second exchange timeout. Prints each result's status, name, and message. ```python from uci_test_suite.runner import run_suite from uci_test_suite.levels import Level # Everything at levels L0-L2 (the minimum UCI engine) with a 20 s exchange timeout results = run_suite(["/usr/local/bin/stockfish"], timeout=20.0, levels={Level.PROCESS, Level.HANDSHAKE, Level.PLAY}) for result in results: print(result.status, result.name, result.message) ``` -------------------------------- ### Constructing and printing a CheckResult Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/07-checks-base.md Shows how to build a CheckResult, print it (produces 'PASS [L2]: go_movetime - answered in 0.240 s'), assert it passed, and print its as_dict() output. ```python from uci_test_suite.checks.base import CheckResult, Status from uci_test_suite.levels import Level result = CheckResult( name="go_movetime", level=Level.PLAY, status=Status.PASS, message="served in 0.240 s", duration=0.24, details={"bestmove": "e2e4", "elapsed_s": 0.24}, ) print(result) # PASS [L2]: go_movetime - answered in 0.240 s assert result.passed print(result.as_dict()) ``` -------------------------------- ### Line dataclass definition Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md Defines the frozen, slotted Line dataclass with direction, text, and at fields. The at field is seconds since client start, based on time.monotonic(). The __str__ method formats the line as '[ 3.142] >> position startpos'. ```python @dataclass(frozen=True, slots=True) class Line: """One line of the conversation, with the seconds elapsed since the client was started.""" direction: Direction text: str at: float def __str__(self) -> str: return f"[{self.at:8.3f}] {self.direction.value} {self.text}" ``` -------------------------------- ### parse_bestmove: Parse a bestmove line Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/03-protocol.md The function signature for parse_bestmove, which parses a bestmove line and returns a BestMove or None. The example shows parsing a bestmove with a ponder move and a null move, asserting the move, ponder, and is_null properties. ```python def parse_bestmove(line: str) -> BestMove | None: """Parse a ``bestmove`` line.""" ``` ```python from uci_test_suite.protocol import parse_bestmove best = parse_bestmove("bestmove e2e4 ponder e7e5") assert best.move == "e2e4" and best.ponder == "e7e5" assert not best.is_null assert parse_bestmove("bestmove 0000").is_null ``` -------------------------------- ### Basic scripted conversation with RawUciClient Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md Shows a basic scripted conversation with a UCI engine using RawUciClient as a context manager. Sends 'uci', expects 'uciok', prints the transcript, and sends 'quit'. The default_timeout is set to 5.0 seconds. ```python from uci_test_suite.transport import RawUciClient, EngineTimeout with RawUciClient(["/usr/local/bin/stockfish"], default_timeout=5.0) as client: client.send("uci") lines = client.expect("uciok") # first token 'uciok' print(client.transcript) # every line, sent and received, in order client.send("quit") ``` -------------------------------- ### parse_info: Parse an info line Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/03-protocol.md The function signature for parse_info, which parses an engine output line and returns an InfoLine or None. The example shows parsing an info line with depth, score, and pv fields, and asserts the parsed values. ```python def parse_info(line: str) -> InfoLine | None: """Parse an ``info`` line.""" ``` ```python from uci_test_suite.protocol import parse_info info = parse_info("info depth 12 score cp 35 pv e2e4 e7e5") assert info.depth == 12 assert info.score.cp == 35 assert info.pv == ("e2e4", "e7e5") ``` -------------------------------- ### main command decorator and signature Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/01-cli.md Click decorator and function signature for the `main` command. The decorator defines the CLI options and arguments; the function signature shows the parameters and their defaults. Use when implementing or extending the command entry point. ```python @click.command(context_settings={"help_option_names": ["-h", "--help"]}) @click.version_option(version=__version__, prog_name="uci-test-suite") @click.argument("engine", nargs=-1, type=click.UNPROCESSED) @click.option( "--level", "-l", "level_selectors", multiple=True, metavar="LEVELS", help=f"Levels to run: {LEVEL_RANGE_SYNTAX}. Repeatable. All levels by default.", ) @click.option("--list", "list_checks", is_flag=True, help="List the checks by level and exit") @click.option("--json", "as_json", is_flag=True, help="Write the results as JSON to stdout, everything else to stderr") @click.option("--debug/--no-debug", default=False, help="Enable debug logging") @click.option("--quiet/--no-quiet", default=False, help="Show only failed checks") @click.option("--verbose/--no-verbose", default=False, help="Show the details each check recorded") @click.option( "--timeout", type=click.FloatRange(min=0.1), default=DEFAULT_TIMEOUT, show_default=True, help="Seconds to wait for a single engine response; also scales every check's own time budget", ) ``` ```python def main( engine: tuple[str, ...], level_selectors: tuple[str, ...] = (), list_checks: bool = False, as_json: bool = False, debug: bool = False, quiet: bool = False, verbose: bool = False, timeout: float = DEFAULT_TIMEOUT, ) -> None: ``` -------------------------------- ### AcceptanceSession Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/configuration.md Constructor for an acceptance session, taking an esca UCI engine and optional notes. ```APIDOC ## AcceptanceSession ### Description Session for acceptance testing with an esca UCI engine. ### Method Constructor ### Endpoint `AcceptanceSession` ### Parameters #### Constructor Parameters - **engine** (`esca.uci.Engine`) - Required - The esca UCI client; the runner creates it as `esca.uci.Engine(command[0], command[1:], timeout=budget)` and calls `handshake()`. - **notes** (`dict[str, str]`) - Optional, default `{}` - Annotation space. ``` -------------------------------- ### ProcessSession Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/configuration.md Constructor for a process-based session, taking an engine argv and timeout. ```APIDOC ## ProcessSession ### Description Session for spawned engine processes. ### Method Constructor ### Endpoint `ProcessSession` ### Parameters #### Constructor Parameters - **command** (`tuple[str, ...]`) - Required - Engine argv. - **timeout** (`float`) - Optional, default `10.0` - Transport timeout for spawned processes. ``` -------------------------------- ### Line dataclass for UCI transport Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/types.md Immutable dataclass representing a single UCI line with direction, text (newline stripped), and timestamp in seconds since client start (time.monotonic()). str(line) produces a formatted string like "[ 3.142] >> position startpos". Returned by RawUciClient.send, poll_line, read_line, expect, and drain; RawUciClient.transcript is a tuple of Line, and RawSession.collect_for returns a list of Line. ```python @dataclass(frozen=True, slots=True) class Line: direction: Direction text: str at: float ``` -------------------------------- ### Using verifiers in a custom check Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/10-checks-verify.md Import the verifier functions and call them after a UCI search. verify_single_bestmove checks the result, verify_move validates the best move against the game, and move_details builds the details for the Outcome. ```python from uci_test_suite.checks.verify import verify_single_bestmove, verify_move, move_details # inside a raw check function after `result = session.go("movetime 250")`: verify_single_bestmove(result) move = verify_move(game, result.bestmove, "the starting position") return Outcome( f"bestmove {result.bestmove.move} ({game.move_to_san(move)})", details=move_details(game, result, move), ) ``` -------------------------------- ### AcceptanceSession Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/09-checks-session.md Documentation for the AcceptanceSession class, including its fields and the engine methods used by L6 checks. ```APIDOC ## AcceptanceSession ### Description A dataclass representing an `esca` UCI client bound to the engine, standing in for a mainstream GUI. It provides access to the engine client and a notes dictionary for checks. ### Fields - `engine` (esca.uci.Engine) - Required - The `esca` UCI client, already handshaken by the runner. - `notes` (dict[str, str]) - Optional, default `{}` - Free-form annotation space for checks. ### Usage - Call `engine.play(game, esca.uci.Limits(movetime=...))` - Call `engine.analyse(game, esca.uci.Limits(depth=...))` - Read `engine.name`, `engine.author`, `engine.options`, `engine.is_alive`, `engine.timeout` - Call `engine.quit()` and `engine.kill()` ``` -------------------------------- ### run_suite Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/configuration.md Runs the UCI test suite against an engine, returning a list of check results. ```APIDOC ## run_suite ### Description Runs the UCI test suite against an engine. ### Method Function ### Endpoint `run_suite` ### Parameters #### Function Parameters - **engine** (`str | Sequence[str]`) - Required - Engine executable or whole command line. - **timeout** (`float`) - Optional, default `10.0` - Seconds per exchange; scales every check's budget. - **levels** (`Collection[Level] | None`) - Optional, default `None` (all) - Levels to run. ### Returns - **list[CheckResult]** - The results of the checks. ``` -------------------------------- ### verify_responsive function signature Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/10-checks-verify.md Defines the verify_responsive assertion that probes a RawSession with isready and returns the response time in seconds. It raises CheckFailure if the engine times out or dies. ```python def verify_responsive(session: RawSession, after: str, timeout: float | None = None) -> float: """Seconds the engine took to answer ``isready``; fails when it dies or stays silent.""" ``` -------------------------------- ### class RawUciClient Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md A UCI engine subprocess addressed one text line at a time, with timeout-bounded reads and context manager support. ```APIDOC ## class RawUciClient ### Description A UCI engine subprocess addressed one text line at a time. Every read is bounded by a timeout and fails loudly rather than blocking; a dead process is reported as `EngineDied` instead of an endless wait. Usable as a context manager, which quits the engine on exit. ### Constructor #### Parameters - **command** (str | Sequence[str]) - Required - Engine executable, or an argv sequence. A string is wrapped into a 1-tuple. - **default_timeout** (float) - Optional - Default: `DEFAULT_TIMEOUT` (10.0) - Seconds to wait for a line when a call does not specify its own timeout. Mutable; the runner reassigns it per level budget. - **cwd** (str | os.PathLike[str] | None) - Optional - Default: `None` - Working directory for the engine process. ### Properties - **transcript** - `def transcript(self) -> tuple[Line, ...]` - Returns every line sent and received so far, in order. - **stderr_lines** - `def stderr_lines(self) -> tuple[str, ...]` - Returns everything the engine wrote to its standard error. - **returncode** - `def returncode(self) -> int | None` - Returns the exit code of the engine process; `None` while it runs or before it is started. - **killed** - `def killed(self) -> bool` - Returns whether the engine had to be terminated instead of exiting by itself. ``` -------------------------------- ### Engine command line arguments Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/README.md The engine argument accepts a full command line, allowing for interpreters or specific engine arguments. Use -- to separate suite options from engine options. ```sh uci-test-suite python my_engine.py uci-test-suite -- java -jar engine.jar --threads 1 ``` -------------------------------- ### Generate machine-readable output Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/README.md Use the --json flag to write full results to standard output, while human-readable logs are sent to standard error. ```sh uci-test-suite --json ./engine > results.json ``` -------------------------------- ### run_suite signature Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/configuration.md Function to run the test suite. Accepts an engine executable or whole command line, with optional timeout (default 10.0) and levels (default None meaning all). Returns a list of CheckResult. ```python def run_suite( engine: str | Sequence[str], *, timeout: float = DEFAULT_TIMEOUT, levels: Collection[Level] | None = None, ) -> list[CheckResult]: ``` -------------------------------- ### send(text: str) -> Line Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/04-transport.md Writes one command line to the engine (after require_alive()). Returns the recorded Line with Direction.SENT. Raises EngineDied on OSError. ```APIDOC ## send(text: str) -> Line ### Description Writes one command line to the engine (after `require_alive()`). Returns the recorded `Line` with `Direction.SENT`. Raises `EngineDied(f"cannot write to the engine: {error}", returncode=process.poll())` on `OSError`. ### Method send ### Parameters #### Request Body - `text` (str) - Required - One command line; `\n` is appended. ### Returns - `Line` - The recorded line with `Direction.SENT`. ### Exceptions - `EngineDied` - if writing to the engine fails. ``` -------------------------------- ### level_summary function Source: https://github.com/anglerfishchess/uci-test-suite/blob/main/_autodocs/api-reference/06-report.md Creates a summary string for the run, merging adjacent levels that share the same verdict. ```python def level_summary(results: Sequence[CheckResult]) -> str: """The per-level summary line, merging neighbouring levels that went the same way.""" ```