首頁 / 概念對照 / 14 bombadil

14完整 驗收與證據Skills

bombadil:UI 屬性測試

作者
Antithesis(antithesishq)
日期
手冊標示版本 v0.8.0;抓取於 2026-11-23 09:00(台北時間)
來源
https://github.com/antithesishq/bombadil
是否完整
完整。README 加上 Browser/Terminal 兩份官方純文字手冊。
抓取時間
2026-11-23 09:00(台北時間)
一句話:用屬性測試自動探索網頁和終端機 UI,在更早抓到人手點不到的錯。

這篇在說什麼

開源工具,可在本機、CI 裡跑,也能進 Antithesis 的確定性環境復現失敗。目前穩定版是 v0.8.0。你用 TypeScript 或 JavaScript 寫規格,宣告屬性和動作產生器,例如「錯誤訊息出現後,五秒內必須消失」。沒有規格時,也有內建屬性,例如不要洩漏資源。Lauren 在主讀那篇講演裡,把它當成 UI 屬性測試的工具之一。本頁附完整手冊,長文已摺疊,可點開閱讀。

以上摘要整理自 2026-11-22 的閱讀筆記,並對過本包原文。完整論證以下面正文為準。

全文

bombadil:UI 屬性測試

  • 來源: https://github.com/antithesishq/bombadil
  • 作者: Antithesis(antithesishq)
  • 日期: 手冊標示版本 v0.8.0;本頁抓取於上述時間
  • 抓取時間: 2026-11-23 09:00(台北時間)
  • 是否完整: 完整(README+Browser/Terminal 兩份官方純文字手冊)
  • 說明/缺漏:
  • GitHub:https://github.com/antithesishq/bombadil
  • 手冊首頁:https://antithesishq.github.io/bombadil/
  • 已抓 Browser 版與 Terminal 版官方 plain text 手冊(給 Agent 讀的格式)。未另存 PDF/EPUB。

GitHub README

來源:https://raw.githubusercontent.com/antithesishq/bombadil/main/README.md

Bombadil

Property-based testing for web and terminal UIs, autonomously exploring and
validating correctness properties, finding harder bugs earlier.

Runs in your local developer environment, in CI, and inside Antithesis.

Documentation

Learn all about Bombadil with the following resources:

Join us

Join us on our quest to reinvent how the world thinks about software reliability. We are hiring.

Or, if you want to hack on it, see
Contributing. We prefer GitHub issues and Discord discussions
over drive-by pull requests. Make sure you read the Gen AI
Policy
before using LLMs in your
contributions.


Tom Bombadil

Old Tom Bombadil is a merry fellow,

Bright blue his jacket is, and his boots are yellow.

Bugs have never fooled him yet, for Tom, he is the Master:

His specs are stronger specs, and his fuzzer is faster.

Built by Antithesis.

官方手冊(Browser 版純文字)(點開看完整手冊)

官方手冊(Browser 版純文字)

來源:https://antithesishq.github.io/bombadil/browser/bombadil-manual.txt

Introduction

Bombadil is property-based testing[1] for user interfaces. It autonomously explores and validates correctness properties, finding harder bugs earlier. It runs in your local developer environment, in CI, and inside Antithesis.

If want to learn more about the background and theory behind property-based testing and user interfaces, begin with Why Bombadil and How it works. If you’re already convinced and just want to get started, head over to Installation.

Why Bombadil

Or rather, why property-based testing? Because example-based testing, especially when browser testing, is costly and limited:

  • Costly, because maintaining suites of Playwright or Cypress tests takes a lot of work. Even in the age of AI, tests written and updated by coding agents can easily break and require your attention.

  • Limited, in that they only test very small parts of the state space; a bunch of happy cases, a set of regression tests, and maybe even some error handling cases that are important. But what about everything else — like all the stuff you or the agent didn’t think about testing?

This is where property-based testing, or fuzzing if you will, comes into play. By randomly and systematically searching the state space, Bombadil behaves in ways you didn’t think about testing for; unexpected sequences of actions, weird timings, strange inputs that you forgot could be entered.

How it works

Instead of describing “what good looks like” in terms of fixed test cases,

you express general properties of your system, defining how it should behave in all cases. Bombadil checks each property as it explores your system in its chaotic ways, reporting back any violations.

To test a web application using Bombadil,

you write a specification in TypeScript that exports properties and action generators. These can be domain-specific — to exercise and validate your system’s logic in custom ways — or be imported from Bombadil’s defaults. Bombadil tests anything that uses the DOM, no matter how it’s built. This includes single-page apps, server-side rendered apps, and even static HTML.

Conceptually, it runs in a loop doing the following:

  1. Extracts the current state from the browser
  2. Checks all properties against the current state, recording violations[2]
  3. Selects the next action based on the current state, and performs it
  4. Waits for the next event (page navigation, DOM mutation, or timeout)
  5. Returns to step 1

Bombadil itself decides what is an interesting event and when to capture state. You provide the properties and actions, Bombadil does the rest!

Getting started

Bombadil runs on your development machine if you’re on macOS or Linux. Use it to validate changes to TypeScript specifications, and to run short tests while working on your system. Configure something like GitHub Actions or a cron job to continously run longer tests on your main branch or in a deployed staging environment. When you’re ready to put your system under extreme conditions, and test your full stack deterministically, run it inside Antithesis.

Installation

The most straightforward way for you to get started is downloading the executable for your platform:

npm
Install as a development dependency in your project:

npm install --save-dev @antithesishq/bombadil

Add a script to your package.json to run Bombadil:

{
  "scripts": {
    "test": "bombadil browser test --time-limit=1m https://your-app.example.com"
  }
}

Then run it with npm test. This also provides TypeScript type definitions for writing specifications.

macOS
Download the bombadil binary using curl (or wget) and make it executable:

curl -L -o bombadil https://github.com/antithesishq/bombadil/releases/download/v%version%/bombadil-aarch64-darwin
chmod +x bombadil

Put the binary somewhere on your PATH, like in ~/.local/bin if that is configured.

mv ./bombadil ~/.local/bin/bombadil

You should now be able to run it:

bombadil --version

Do not download the executable with your web browser. It will be blocked by GateKeeper.

Linux
Download the bombadil binary and make it executable:

curl -L -o bombadil https://github.com/antithesishq/bombadil/releases/download/v%version%/bombadil-x86_64-linux
chmod +x bombadil

Put the binary somewhere on your PATH, like in ~/.local/bin if that is configured.

mv ./bombadil ~/.local/bin/bombadil

You should now be able to run it:

bombadil --version

Nix (flake)
nix run github:antithesishq/bombadil/v%version% -- --version

GitHub Actions
- uses: antithesishq/bombadil-action@v2
with:
driver: browser
origin: https://your-app.example.com
specification: ./bombadil/specification.ts
time-limit: 5m
exit-on-violation: true
output-path: bombadil-output

See its README for detailed instructions.

Docker
Releases are published as tags on Docker Hub:

docker run antithesishq/bombadil:%version% --version

If you want to compile from source, see Contributing.

TypeScript support

When writing specifications in TypeScript, you’ll want the types available. If you installed Bombadil via npm, you already have them — skip ahead to Your first test.

Otherwise, install the package with your package manager of choice:

npm
npm install --save-dev @antithesishq/bombadil

Yarn
yarn add --dev @antithesishq/bombadil

Bun
bun add --development @antithesishq/bombadil

Or use the files provided in the release package.

Your first test

With the CLI installed, let’s run a browser test just to see that things are working:

bombadil browser test https://en.wikipedia.org --output-path my-test

This will run until you shut it down using Ctrl+C. Any property violations will be logged as errors, and with the --output-path option you will get results to inspect afterwards.

The trace is the file my-test, including its screenshots. Any filename is accepted, but its parent directory must already exist; an existing directory cannot be used as the output path.

Launch the Bombadil Inspect tool to see what happened in the test you just ran:

bombadil browser inspect my-test

This will open a web application in your browser, which has some features to highlight:

  • This interface is focused on state transitions, i.e. the state before and after each action.
  • On the left is the actions list, which you can use to navigate the state transitions by clicking the actions.
  • In the bottom you’ll see the timeline, which you can scrub (click and drag) with your mouse. The timeline also shows the currently selected state transition.
  • If there were any violations found in the test, they’ll be shown as exclamation mark icons in the timeline.

No violations? That’s fine, Wikipedia is pretty solid! This confirms that Bombadil runs and produces results.

Specification language

To extend Bombadil with domain-specific knowledge, you write specifications. These are plain TypeScript or JavaScript modules that use the library provided by Bombadil to export properties and action generators.

Here’s how you run Bombadil with a custom specification:

bombadil browser test https://example.com example.ts

For a full listing of CLI options, see the reference.

Structure

A specification is a regular ES module. The following examples use TypeScript, but you may also write them in JavaScript. If you do use TypeScript, you’ll want to install the types from @antithesishq/bombadil.

Both properties and action generators are exposed to Bombadil as exports:

export const myProperty = ...;

export const myAction = ...;

You may split up your specification into multiple modules and structure it the way you like, but the top-level specification you give to Bombadil must only export properties and action generators.

Importing modules and files

You can split your specification up into multiple modules and import them from the top level specification module:

import { thing } from "./lib/thing.ts";

If you install packages from NPM or similar, you may import those too:

import equal from "deep-equal";

The runtime is limited, so many existing packages might not work, e.g. if they import NodeJS packages.

Non-code files

You can import JSON, text, or binary data. This is useful for bootstrapping tests with reference data, dictionaries, configuration, etc. Use ES import attributes to specify the type of import:

import data from "./fixtures/data.json" with { type: "json" };
import contents from "./wordlist.txt" with { type: "text" };
import raw from "./snapshot.dat" with { type: "binary" };

When using "text" you get a string, and when using "binary" you get Uint8Array.

For JSON data, you can also just use the file extension:

import data from "./fixtures/data.json";

Default properties and action generators

Bombadil comes with a set of default properties and action generators that work for most web applications. You’ll probably want to reexport all or at least most of these:

export * from "@antithesishq/bombadil/browser/defaults";

In fact, these defaults are exactly what are used when running tests without a custom specification file. If you want to selectively pick just a subset of these, replace the * with the relevant names:

export {
    noUncaughtExceptions,
} from "@antithesishq/bombadil/browser/defaults/properties";
export { 
    // Actions
    clicks, 
    reload,
} from "@antithesishq/bombadil/browser/defaults/actions";

You may freely combine defaults with your own properties and action generators. All properties and action generators exported by the top-level module are used by Bombadil.

The browser defaults include properties checking for uncaught exceptions, unhandled promise rejections, error logs, HTTP 4xx and 5xx responses, and more. On the actions side, there are generators for general navigation and interaction with semantic HTML elements.

Language features

The specification language of Bombadil, embedded in TypeScript or JavaScript, has a small set of central concepts. This section describes them in detail.

Properties

A property is a description of how the system under test should behave in general. This is different from example-based testing (e.g. Playwright, Cypress, or Selenium) where you describe how it behaves for particular cases.

The most intuitive kind of property, which you might have come across before, is an invariant: a condition that should always be true. In Bombadil, invariants are expressed using the always temporal operator:

always( 
    // some condition that should always be true
)

To instruct Bombadil to check your property, you must export it from your specification module. Its name is used in error reports, so give the export a meaningful name.

export const hasTitle = always( 
    // check that there's a title rendered somehow
);

You may export multiple properties, including the defaults, and they’ll all be checked independently. But how do you “check that there’s a title somehow”? You need access to the browser, and for that, you use extractors.

Extractors

In order to describe a condition about the web page you’re testing, you first need to extract state. This is done with the extract function, which runs inside the browser on every state that Bombadil decides to capture.

extract(state => ...)

You give it a function that takes the current browser state as an argument, and returns JSON-serializable data. The state object contains a bunch of things, but the most important are document and window — the same ones you have access to in JavaScript running in a browser.

To extract the title, you’d define this at the top level of your specification:

const title = extract(state => state.document.title || "");

The title value is not a string though — it’s a Cell, a stateful value that changes over time. For every new state captured by Bombadil, the extractor function gets run, and the cell is updated with its return value.

Using the title cell, you can define the property:

export const hasTitle = always(() => 
    title.current !== ""
);

Two things to note about this example:

  1. The expression passed to always is a function that takes no arguments — a thunk. This is because it needs to be evaluated in every state. It needs to always be true, not just once, and that’s why you need to supply the thunk rather than a boolean.
  2. To get the string value out of the cell, you use .current.

This is a custom property using the temporal operator called always. There are other temporal operators, described in Formulas below.

Transforming cells

A cell can be turned into a new cell with map, which applies a function to the value of the original cell in every state:

const titleLength = title.map((title) => title.length);

export const hasShortTitle = always(() =>
    titleLength.current < 80
);

Formulas

Formulas and temporal operators may sound scary, but fear not — they are essentially ways of expressing “conditions over time”. Here are some quick facts about formulas and temporal operators:

  • Temporal operators return formulas.
  • Every property in Bombadil is a formula (of the Formula type).
  • A temporal operator is a function that takes some subformula and evaluates it over time.
  • Different temporal operators evaluate their subformulas in different ways.
  • Bombadil evaluates formulas against a sequence of states to check if they hold true.

Temporal operator types include always, as discussed in the example in Extractors above, and also eventually and next. Here’s an informal[3] description of how they work:

  • always(x) holds if x holds in this and every future state
  • next(x) holds if x holds in the next state
  • eventually(x) holds if x holds in this or any future state

They accept subformulas as arguments. You’ll notice in the example with always above, the argument was a thunk. This still works, because the operators automatically convert thunks into formulas. In fact, there’s an operator for doing that explicitly, called now:

always(now(() => title.current !== ""))

You normally don’t have to use the now operator, unless you want to use logical connectives at the formula level. They are defined as methods on formulas:

  • x.and(y) holds if x holds and y holds
  • x.or(y) holds if x holds or y holds
  • x.implies(y) holds if x doesn’t hold or y holds

There’s also negation, both as a function and as a method on formulas, i.e. not(x) and x.not().

The now operator is useful when expressing single-state preconditions. The following property checks that pressing a button shows a spinner that is eventually hidden again:

const buttonPressed = extract(() => ...);
const spinnerVisible = extract(() => ...);

now(() => buttonPressed.current).implies(
    now(() => spinnerVisible.current)
        .and(eventually(() => !spinnerVisible.current))
)

You can build more advanced formulas, and even include nested temporal operators, but the basics are often powerful enough. See the examples at the bottom for more inspiration.

Action generators

In addition to exporting properties in a specification, you export action generators. A generator is an object of the ActionGenerator class. An action generator generates values of type Tree.

Like with default properties, there are default action generators provided by Bombadil. These will get you a long way, but there are times where you’ll need to define your own action generators.

For every state that Bombadil captures, all action generators are run, contributing to a tree structure of possible action templates. These are called action templates and are parameterized by ranges of values. Bombadil then randomly picks one in that tree, and picks random values within the ranges for the parameters. Why a tree, though? It’s because the branches are weighted — equally, by default. But you can override this to control the probability of an action being picked.

To define a custom action generator, you use the actions function, which takes a thunk that returns an array of action templates:

export const myAction = actions(() => {
    return [
        ...
    ];
});

In the returned array, each element is a value of the ActionTemplate type, provided by the NPM package. See the TypeScript source for reference.

Here’s a generator for clicks in the center of a canvas element:

const canvas = extract((state) => {
    const canvas = state.document.querySelector("#my-canvas");
    if (!canvas) {
        return null;
    }
    const rect = canvas.getBoundingClientRect();
    if (rect.width > 0 && rect.height > 0) {
        return {
            fingerprint: getFingerprint(canvas),
            point: {
                x: rect.left + rect.width / 2,
                y: rect.top + rect.height / 2,
            }
        };
    }
    return null;
});


export const clickCanvas = actions(() => {
    return canvas.current ? [{ Click: canvas.current }] : [];
});

Or for double-click actions:

export const doubleClickCanvas = actions(() => {
    return canvas.current ? [{ DoubleClick: canvas.current }] : [];
});

The actions you return must be possible to perform in the current state. Your action generators should therefore depend on cells and validate your actions before returning them, as done with canvas in the previous example. Another example is the back action generator provided by Bombadil, which checks that there’s a history entry to go back to, otherwise returning [].

To give actions different weights, use the weighted combinator and wrap each subgenerator in an array with the weight as the first element:

export const navigation = weighted([
    [10, back],
    [1, forward],
    [1, reload],
]);

Transforming action generators

Rather than writing a generator from scratch, you can often adapt an existing one, such as the ones provided as defaults. Action generators have map, filter, and flatMap methods that work similarly to those in Array. Weights are preserved when transforming a generator. Use isAction to check what kind of action you’re dealing with, which also narrows its type.

The difference between the two mapping methods is what the function returns. With map, each action is replaced by a single other action. With flatMap, each action is replaced by an array of actions, picked uniformly, or by another action generator. Returning an empty array from flatMap drops the action.

Here’s the default clicks generator, restricted to elements outside of a sidebar:

import { extract, weighted, type Point } from "@antithesishq/bombadil/browser";
import { isAction, type Range } from "@antithesishq/bombadil/actions";
import {
    clicks,
    inputs,
    scroll,
} from "@antithesishq/bombadil/browser/defaults/actions";

const sidebar = extract((state) => {
    const element = state.document.querySelector("#sidebar");
    if (!element) return null;
    const { left, top, right, bottom } = element.getBoundingClientRect();
    return { left, top, right, bottom };
});

function inSidebar({ x, y }: Point<Range>): boolean {
    const rect = sidebar.current;
    return (
        rect !== null &&
        typeof x === "number" &&
        typeof y === "number" &&
        x >= rect.left &&
        x <= rect.right &&
        y >= rect.top &&
        y <= rect.bottom
    );
}

export const myActions = weighted([
    [
        100,
        clicks.filter(
            (action) =>
                !(isAction(action, "Click") && inSidebar(action.Click.point)),
        ),
    ],
    [100, inputs],
    [50, scroll],
]);

Only export the filtered clicks and not the original definition. Otherwise Bombadil will still be able to click in the sidebar.

The map method replaces each action, here turning every click into a double-click:

export const doubleClicks = clicks.map((action) =>
    isAction(action, "Click") ? { DoubleClick: action.Click } : action,
);

To enable a generator only in certain states, use when with a boolean, a cell, or a function returning a boolean. When the condition is false, the generator isn’t run at all:

export const clicksUnlessModal = clicks.when(() => !modalOpen.current);

Custom actions

In addition to the built-in actions, you can define custom actions. These are arbitrary functions that run in the browser when the action is invoked, with full DOM access and your extractor cells. Defining a custom action is useful if you have a multi-step workflow in your interface which you just want to get past quickly, like authentication forms or cookie consent dialogs.

Call registerCustomAction with a name and a handler function, which accepts Document and Window as the first two parameters, and any other parameters you need. The remaining parameters correspond to the arguments passed when generating the custom action.

Here’s a custom action that fills out and submits a search form:

const search = registerCustomAction(
  "search",
  async (document, _window, query: string) => {
    const searchButton = document.querySelector<HTMLButtonElement>(
      "form [type=submit]",
    );
    if (!searchButton) {
      throw new Error("Search button not found");
    }
    const searchInput = document.querySelector<HTMLInputElement>(
      "form [type=search]",
    );
    if (!searchInput) {
      throw new Error("Search input not found");
    }
    searchInput.focus();
    searchInput.value = query;
    searchInput.dispatchEvent(new Event("input", { bubbles: true }));
    searchButton.click();
  },
);

To generate the search action, invoke the returned function in an action generator:

export const myActions = actions(() => [
    search("Something"), 
    // other actions...
]);

As with any action generator, you should only return actions that are currently valid. A common pattern is a guard in your action generator:

export const myActions = actions(() => {
    if (title.current == "Search") {
        return [search("Something")];
    }

    return [
        // other actions...
    ];
});

Optional properties

In addition to the default properties, there’s a set of extras modules with properties that you can use. These are not included in the defaults and need to be specifically used and exported in your top-level specification module.

Detecting resource leaks

Bombadil provides a parameterized property for catching resource leaks in the web application being tested:

import { noResourceLeak } from "@antithesishq/bombadil/browser/extras/resources";

// At most 5MB heap growth within 10 seconds.
export const noHeapLeak = noResourceLeak({
  metric: "js_heap_used",
  growthLimit: 5 * 1024 ** 2,
  windowMillis: 10_000,
});

// At most 500 DOM nodes allocated within 1 second.
export const noDomLeak = noResourceLeak({
  metric: "dom_nodes",
  growthLimit: 500,
  windowMillis: 1_000,
});

The property is a sliding-window invariant — within any window of windowMillis, the chosen metric must not grow by more than growthLimit. The available metric values are:

Metric Meaning


"js_heap_used" Used JS heap, in bytes
"js_heap_total" Total JS heap, in bytes
"dom_nodes" Live DOM node count
"js_event_listeners" Registered event-listener count
"layout_objects" Layout object count

The JS heap is noisy because of garbage collection. For a more robust detection, watch dom_nodes or js_event_listeners, where a big jump more strongly suggests a leak. If you do watch the JS heap, use a growthLimit that is higher than the usual spikes you see before a GC event, and use a long windowMillis. The inspect command is helpful as it visualizes some of these metrics over time.

Examples

These are full, runnable examples of properties and action generators you might need in your own testing with Bombadil. Think of them as design patterns for properties. Each example is a self-contained specification file.

Invariant: max notification count

This is a simple property checking that there are never more than five notifications shown.

import { extract, always } from "@antithesishq/bombadil";
export * from "@antithesishq/bombadil/browser/defaults";

const notificationCount = extract((state) => 
    state.document.body.querySelectorAll(".notification").length,
);

export const max_notifications_shown = always(() =>
    notificationCount.current <= 5,
);

Sliding window: constant notification count

This property checks that the notification count doesn’t change — that it is the same as in the first state. Note how this property evaluates notificationCount.current in the outer thunk, and then uses that in the inner thunk to compare against the current value.

import { extract, always, now, time } from "@antithesishq/bombadil";
export * from "@antithesishq/bombadil/browser/defaults";

const notificationCount = extract((state) =>
    state.document.body.querySelectorAll(".notification").length,
);

export const constantNotificationCount = now(() => {
    const initial = notificationCount.current;
    return always(() => 
        notificationCount.current === initial,
    );
});

Guarantee: error disappears

A guarantee property checks that something good eventually happens, within some time bound. Here is a property that checks that error messages disappear within five seconds.

import { extract, always, now, eventually } from "@antithesishq/bombadil";
export * from "@antithesishq/bombadil/browser/defaults";

const errorMessage = extract((state) => 
    state.document.body.querySelector(".error")?.textContent ?? null,
);

export const errorDisappears = always(
    now(() => errorMessage.current !== null).implies(
        eventually(() => errorMessage.current === null)
            .within(5, "seconds"),
    ),
);

Contextful guarantee: notification includes past value

This property checks that if there’s a non-blank name entered, and it is submitted, then eventually there will be a notification that includes the name. This example uses an outer thunk to force a cell value (nameEntered) at every state, and then closes over that value with the inner thunk passed to eventually.

import { extract, always, now, next, eventually } from "@antithesishq/bombadil";
export * from "@antithesishq/bombadil/browser/defaults";

const name = extract((state) => {
    const element = 
        state.document.body.querySelector("#name-field");
    return (element as HTMLInputElement | null)?.value ?? null;
});

const submitInProgress = extract((state) => 
    state.document.body.querySelector("submit.progress")
        !== null,
);

const notificationText = extract((state) =>
    state.document.body.querySelector(".notification")?.textContent 
        ?? null,
);

export const notificationIncludesMessage = always(() => {
    const nameEntered = name.current?.trim() ?? "";

    return now(() => nameEntered !== "")
        .and(next(() => submitInProgress.current))
        .implies(eventually(() => 
            notificationText.current?.includes(nameEntered) 
                ?? false,
        ).within(5, "seconds"));
});

State machine: counter

This property models a counter as a state machine, checking that the counter only transitions by staying the same, incrementing by 1, or decrementing by 1 (no invalid jumps allowed).

import { extract, always, now, next } from "@antithesishq/bombadil";
export * from "@antithesishq/bombadil/browser/defaults";

const counterValue = extract((state) => {
    const element = state.document.body.querySelector("#counter");
    return parseInt(element?.textContent ?? "0", 10);
});

const unchanged = now(() => {
    const current = counterValue.current;
    return next(() => counterValue.current === current);
});

const increment = now(() => {
    const current = counterValue.current;
    return next(() => counterValue.current === current + 1);
});

const decrement = now(() => {
    const current = counterValue.current;
    return next(() => counterValue.current === current - 1);
});

export const counterStateMachine = 
    always(unchanged.or(increment).or(decrement));

If this specification exports the reload action, the unchanged property becomes relevant.[4] Unless this application stored the state of the counter somehow, reloading the page would clear the counter, which this property would catch as a violation.

Workflows

This section describes how to run tests and debug violations with Bombadil. Each workflow is a building block in a composable set of tools for finding, understanding, and fixing bugs in user interfaces.

Reproducing violations

If Bombadil finds a bug in a project you’re working on, you might want to reproduce that test case when working on a bug fix. That is, have Bombadil perform the same sequence of actions to reach the same state.

Use the --reproduce option and point it to the trace file of the original test run:

bombadil browser test --reproduce=my-test http://example.com

Reproductions are not guaranteed to succeed. If they diverge, Bombadil fails with an error. For reproductions to succeed, it’s important to use the same options as in the original test. After a test run, Bombadil prints both the inspect and --reproduce commands you can use.

Shrinking violations

When Bombadil finds a violation, the trace leading up to it is often long and full of actions that have nothing to do with the bug. The shrink command takes such a trace and searches for a shorter one that still violates the same property.

Shrinking is experimental. The command-line options and output format may change between releases.

bombadil browser shrink --headless --trace my-test https://example.com

It’s important that the shrink invocation uses the same options as the original test or fuzz invocation, just as when reproducing violations.

Shrinking begins with a calibration phase that tries to assess the flakiness of reproducing the violation. Calibration can be controlled with --calibration-runs and --confirmation-runs-max if needed. At the end of shrinking, you get a new trace file, configured with --output-path and --output-path-overwrite, that can be reproduced or inspected.

Trace inputs are always files, never directories. For a single test or shrink, --output-path names the actual trace file and accepts any filename; its parent directory must already exist. Without it, Bombadil chooses a unique file in system temp. For fuzz, the option is a file base: run.bin writes sibling files run-0.bin, run-1.bin, and so on, without per-run directories. Browser downloads use a separate temporary directory logged before the run and removed afterwards. Shrinking permits a sibling output but rejects an input alias, including symbolic links and hard links. Use --output-path-overwrite to replace an existing file.

Inspecting test results

When you’ve run a test and found one or more violations, you likely want to understand what happened. The inspect tool shows a single trace using an interactive web view.

bombadil browser inspect my-test

This command automatically opens the web page in your browser. You will see the actions listed on the left, and timeline in the bottom, and in the main pane the transition caused by the selected action. A transition shows state before and state after. Along with screenshots, you see violations and all captured snapshot values per state.

To look at a trace in the terminal instead, bombadil trace lists its states with their actions, URLs and violations. With --screenshots, it also writes each state’s screenshot to a directory, named by the state’s index:

bombadil trace my-test --screenshots my-test-screenshots

Pick states with --state (--state 40..50 shows states 40 to 49), or print one JSON object per state with --json to process the trace with tools like jq. Running --screenshots again leaves the screenshots already written as they are.

Running with chrome-headless-shell

This is experimental.

By default, Bombadil runs a regular Chrome or Chromium. For higher throughput (up to 4x), consider using chrome-headless-shell instead:

bombadil browser test --chrome-variant headless-shell https://example.com

Bombadil does not download chrome-headless-shell for you. Put the chrome-headless-shell executable on your PATH, or point the CHROME environment variable at it.

You can get an executable using the following command:

npx @puppeteer/browsers install chrome-headless-shell@stable

As with other options, use the same --chrome-variant and executable when reproducing or shrinking a violation.

Reference

This section describes the technical details of the command-line interface and the TypeScript modules used when writing specifications. If you instead want instructions on how to set up your environment with Bombadil, see Installation and Typescript support.

Command-line interface

The primary way of using Bombadil, at least locally, is through the command-line interface (CLI). This section describes in detail what commands are available, and what options, flags, and arguments you can give them.

The general exit code semantics of the CLI is:

Code Meaning

   0 Test or fuzzing campaign completed normally (including time limit)
   1 Other error
   2 Property violation(s) detected

Property violations take precedence, so failed fuzz runs only cause the fuzzing campaign to exit with 1 if there are no violations found.

bombadil browser test

Run a test with a browser managed by Bombadil.

bombadil browser test [OPTIONS] [SPECIFICATION_FILE]

Arguments


Starting URL of the test. Without --allow-url, exploration stays on the origin’s scheme, host and port. For a file:// origin it stays on that exact file. With one or more --allow-url entries, those define the exploration boundary instead (include the origin there if it should remain allowed).

[SPECIFICATION_FILE]
A custom specification in TypeScript or JavaScript, using the @antithesishq/bombadil package on NPM.

Options

--width

Browser viewport width in pixels.

Default: 1024

--height

Browser viewport height in pixels.

Default: 768

--device-scale-factor

Scaling factor of the browser viewport, mostly useful on high-DPI monitors when in headed mode.

Default: 1

--instrument-javascript

What types of JavaScript to instrument for coverage tracking. Comma-separated list of: “files”, “inline”.

Default: files,inline

--chrome-grant-permissions

Comma-separated list of Chrome permissions to grant.

Default: local-network-access,local-network,loopback-network

--chrome-virtual-time-policy
Optional virtual time policy for Chrome, used to speed up execution of timer-heavy applications. One of: Advance, Pause, PauseIfNetworkFetchesPending.

--header
Extra HTTP header to send with all browser requests, in KEY=VALUE format. Can be specified multiple times.

--cookie
Cookie to set in the browser before testing. Accepts plain NAME=VALUE (scoped to the origin) or Set-Cookie syntax with attributes such as Domain, Path, Secure, and HttpOnly. Unlike --header, these become real browser cookies. Can be specified multiple times.

--allow-url
Exploration boundary as Chrome extension match patterns, e.g. ://.example.com/*. Replaces the implicit origin match pattern. For the pattern syntax, see Match patterns.

--output-path
Trace FILE to write (any filename), with embedded screenshots. For fuzz, a file base: run.bin writes run-0.bin, run-1.bin, etc. Defaults to a unique file/base in system temp. Parents must exist.

--output-path-overwrite
Overwrite any existing trace at --output-path. Without this flag, Bombadil refuses to replace an existing file.

--coverage-symbols
Write the table of instrumented coverage blocks that trace branches ids refer to (id, script, function, line) to this file, as JSON lines, as scripts are instrumented. The file must not exist, and its parent must. Without it no table is written.

--exit-on-violation
Whether to exit the test when first failing property is found (useful in development and CI).

--time-limit
Maximum time to run the test. Accepts a number with a unit suffix: s (seconds), m (minutes), h (hours), or d (days).

--reproduce
Reproduce a previous test run from a trace file, instead of random exploration. Mutually exclusive with --time-limit and --exit-on-violation.

--headless
Whether the browser should run in a visible window or not.

--no-sandbox
Disable Chromium sandboxing.

--chrome-variant

Which kind of Chrome/Chromium build to run. headless-shell (chrome-headless-shell) controls rendering frame by frame, which is faster but experimental, and implies --headless.

Default: full

-h, --help
Print help.

Examples

Test a website using the default specification:

bombadil browser test https://example.com

Use a custom specification and stop at the first violation:

bombadil browser test --exit-on-violation https://example.com spec.ts

Run headless for five minutes:

bombadil browser test --headless --time-limit 5m https://example.com

Grant specific Chrome permissions:

bombadil browser test --chrome-grant-permissions geolocation,notifications https://example.com

Speed up a timer-heavy app by automatically advancing virtual time in Chrome:

bombadil browser test --chrome-virtual-time-policy Advance https://example.com

Reproduce a test run (best-effort, fails on divergence):

bombadil browser test --reproduce my-test https://example.com

bombadil browser test-external

Run a test with an externally managed browser or Electron app (e.g. chromium --remote-debugging-port=9992).

bombadil browser test-external [OPTIONS] [SPECIFICATION_FILE]

Arguments


Starting URL of the test. Without --allow-url, exploration stays on the origin’s scheme, host and port. For a file:// origin it stays on that exact file. With one or more --allow-url entries, those define the exploration boundary instead (include the origin there if it should remain allowed).

[SPECIFICATION_FILE]
A custom specification in TypeScript or JavaScript, using the @antithesishq/bombadil package on NPM.

Options

--width

Browser viewport width in pixels.

Default: 1024

--height

Browser viewport height in pixels.

Default: 768

--device-scale-factor

Scaling factor of the browser viewport, mostly useful on high-DPI monitors when in headed mode.

Default: 1

--instrument-javascript

What types of JavaScript to instrument for coverage tracking. Comma-separated list of: “files”, “inline”.

Default: files,inline

--chrome-grant-permissions

Comma-separated list of Chrome permissions to grant.

Default: local-network-access,local-network,loopback-network

--chrome-virtual-time-policy
Optional virtual time policy for Chrome, used to speed up execution of timer-heavy applications. One of: Advance, Pause, PauseIfNetworkFetchesPending.

--header
Extra HTTP header to send with all browser requests, in KEY=VALUE format. Can be specified multiple times.

--cookie
Cookie to set in the browser before testing. Accepts plain NAME=VALUE (scoped to the origin) or Set-Cookie syntax with attributes such as Domain, Path, Secure, and HttpOnly. Unlike --header, these become real browser cookies. Can be specified multiple times.

--allow-url
Exploration boundary as Chrome extension match patterns, e.g. ://.example.com/*. Replaces the implicit origin match pattern. For the pattern syntax, see Match patterns.

--output-path
Trace FILE to write (any filename), with embedded screenshots. For fuzz, a file base: run.bin writes run-0.bin, run-1.bin, etc. Defaults to a unique file/base in system temp. Parents must exist.

--output-path-overwrite
Overwrite any existing trace at --output-path. Without this flag, Bombadil refuses to replace an existing file.

--coverage-symbols
Write the table of instrumented coverage blocks that trace branches ids refer to (id, script, function, line) to this file, as JSON lines, as scripts are instrumented. The file must not exist, and its parent must. Without it no table is written.

--exit-on-violation
Whether to exit the test when first failing property is found (useful in development and CI).

--time-limit
Maximum time to run the test. Accepts a number with a unit suffix: s (seconds), m (minutes), h (hours), or d (days).

--reproduce
Reproduce a previous test run from a trace file, instead of random exploration. Mutually exclusive with --time-limit and --exit-on-violation.

--remote-debugger
Address to the remote debugger’s server, e.g. http://localhost:9222.

--create-target
Whether Bombadil should create a new tab and navigate to the origin URL in it, as part of starting the test (this should probably be false if you test an Electron app).

-h, --help
Print help.

Examples

Start Chromium (or an Electron app) with remote debugging enabled, and launch a test against the existing open target:

chromium --remote-debugging-port=9222 https://example.com
bombadil browser test-external --remote-debugger http://localhost:9222 https://example.com

bombadil browser fuzz

(EXPERIMENTAL) Fuzz (running many tests) with a browser managed by Bombadil.

bombadil browser fuzz [OPTIONS] [SPECIFICATION_FILE]

Arguments


Starting URL of the test. Without --allow-url, exploration stays on the origin’s scheme, host and port. For a file:// origin it stays on that exact file. With one or more --allow-url entries, those define the exploration boundary instead (include the origin there if it should remain allowed).

[SPECIFICATION_FILE]
A custom specification in TypeScript or JavaScript, using the @antithesishq/bombadil package on NPM.

Options

--width

Browser viewport width in pixels.

Default: 1024

--height

Browser viewport height in pixels.

Default: 768

--device-scale-factor

Scaling factor of the browser viewport, mostly useful on high-DPI monitors when in headed mode.

Default: 1

--instrument-javascript

What types of JavaScript to instrument for coverage tracking. Comma-separated list of: “files”, “inline”.

Default: files,inline

--chrome-grant-permissions

Comma-separated list of Chrome permissions to grant.

Default: local-network-access,local-network,loopback-network

--chrome-virtual-time-policy
Optional virtual time policy for Chrome, used to speed up execution of timer-heavy applications. One of: Advance, Pause, PauseIfNetworkFetchesPending.

--header
Extra HTTP header to send with all browser requests, in KEY=VALUE format. Can be specified multiple times.

--cookie
Cookie to set in the browser before testing. Accepts plain NAME=VALUE (scoped to the origin) or Set-Cookie syntax with attributes such as Domain, Path, Secure, and HttpOnly. Unlike --header, these become real browser cookies. Can be specified multiple times.

--allow-url
Exploration boundary as Chrome extension match patterns, e.g. ://.example.com/*. Replaces the implicit origin match pattern. For the pattern syntax, see Match patterns.

--output-path
Trace FILE to write (any filename), with embedded screenshots. For fuzz, a file base: run.bin writes run-0.bin, run-1.bin, etc. Defaults to a unique file/base in system temp. Parents must exist.

--output-path-overwrite
Overwrite any existing trace at --output-path. Without this flag, Bombadil refuses to replace an existing file.

--coverage-symbols
Write the table of instrumented coverage blocks that trace branches ids refer to (id, script, function, line) to this file, as JSON lines, as scripts are instrumented. The file must not exist, and its parent must. Without it no table is written.

--exit-on-violation
Whether to exit the test when first failing property is found (useful in development and CI).

--swarm
Whether to apply swarm testing to actions. Otherwise all actions are enabled.

--parallelism

Number of test runs to execute in parallel.

Default: 1

--time-limit-fuzz
Default: 5m

--time-limit-run

Maximum time to run an individual linear run. Accepts a number with a unit suffix: s (seconds), m (minutes), h (hours), or d (days).

Default: 30s

--headless
Whether the browser should run in a visible window or not.

--no-sandbox
Disable Chromium sandboxing.

--chrome-variant

Which kind of Chrome/Chromium build to run. headless-shell (chrome-headless-shell) controls rendering frame by frame, which is faster but experimental, and implies --headless.

Default: full

-h, --help
Print help.

bombadil browser shrink

(EXPERIMENTAL) Shrink a trace with a property violation into a smaller one that still violates it (best-effort).

bombadil browser shrink [OPTIONS] [SPECIFICATION_FILE]

Arguments


Starting URL of the test. Without --allow-url, exploration stays on the origin’s scheme, host and port. For a file:// origin it stays on that exact file. With one or more --allow-url entries, those define the exploration boundary instead (include the origin there if it should remain allowed).

[SPECIFICATION_FILE]
A custom specification in TypeScript or JavaScript, using the @antithesishq/bombadil package on NPM.

Options

--width

Browser viewport width in pixels.

Default: 1024

--height

Browser viewport height in pixels.

Default: 768

--device-scale-factor

Scaling factor of the browser viewport, mostly useful on high-DPI monitors when in headed mode.

Default: 1

--instrument-javascript

What types of JavaScript to instrument for coverage tracking. Comma-separated list of: “files”, “inline”.

Default: files,inline

--chrome-grant-permissions

Comma-separated list of Chrome permissions to grant.

Default: local-network-access,local-network,loopback-network

--chrome-virtual-time-policy
Optional virtual time policy for Chrome, used to speed up execution of timer-heavy applications. One of: Advance, Pause, PauseIfNetworkFetchesPending.

--header
Extra HTTP header to send with all browser requests, in KEY=VALUE format. Can be specified multiple times.

--cookie
Cookie to set in the browser before testing. Accepts plain NAME=VALUE (scoped to the origin) or Set-Cookie syntax with attributes such as Domain, Path, Secure, and HttpOnly. Unlike --header, these become real browser cookies. Can be specified multiple times.

--allow-url
Exploration boundary as Chrome extension match patterns, e.g. ://.example.com/*. Replaces the implicit origin match pattern. For the pattern syntax, see Match patterns.

--trace
Trace FILE to shrink (any filename, not a directory).

--property
Name of the property to shrink for. Required if the trace has violations of more than one property.

--output-path
Trace FILE to write. Defaults to a unique file in system temp. Parent directories must already exist. Must not alias the input.

--output-path-overwrite
Overwrite any existing file at --output-path.

--time-limit
Maximum time to shrink for, after which the smallest trace found so far is kept. Accepts a number with a unit suffix: s (seconds), m (minutes), h (hours), or d (days).

--parallelism

Number of test runs to execute in parallel. Only use this if runs are isolated from each other (e.g. not sharing files or a backend).

Default: 1

--calibration-runs

Number of times to replay the original trace to measure how reliably it reproduces the violation.

Default: 3

--confirmation-runs-max

Maximum number of runs used to confirm that a smaller trace reproduces reliably enough.

Default: 5

--headless
Whether the browser should run in a visible window or not.

--no-sandbox
Disable Chromium sandboxing.

--chrome-variant

Which kind of Chrome/Chromium build to run. headless-shell (chrome-headless-shell) controls rendering frame by frame, which is faster but experimental, and implies --headless.

Default: full

-h, --help
Print help.

Examples

Shrink the trace in my-test, which violates a single property:

bombadil browser shrink --headless --trace my-test https://example.com

Shrink for a specific property, using four parallel browsers:

bombadil browser shrink --headless --trace my-test --property noErrors --parallelism 4 https://example.com spec.ts

bombadil browser inspect

Launch Bombadil Inspect to inspect a trace file.

bombadil browser inspect [OPTIONS]

Arguments


Trace FILE to inspect (any filename, not a directory).

Options

--port

Port to bind the inspect server to.

Default: 1073

--no-open
Skip auto-opening browser.

-h, --help
Print help.

Examples

Inspect the trace file named my-test:

bombadil browser inspect my-test

Serve on another port, without trying to open a browser:

bombadil browser inspect --port 8080 --no-open my-test

bombadil trace

Show the states of a binary trace file (any filename).

bombadil trace [OPTIONS]

Arguments


Trace FILE to read (any filename, not a directory).

Options

--state
Only show this state, or a range of states such as 40..50 (from 40 up to but not including 50), 40.. or ..50.

--json
Print one JSON object per state: its index, metadata and payload size, with –screen its screen (a string, or null without one), and with –screenshots the file its screenshot is in, if it has one.

--screen
Show each state’s screen (terminal traces).

--color
Show screens with their colors and styles, as ANSI escape sequences (implies –screen).

--screenshots
Write the screenshot of each state shown into this directory, as . (browser traces), or .bin for a format other than png and jpeg. A file already there is left as it is if it holds the same screenshot, and refused otherwise.

-h, --help
Print help.

TypeScript reference

These are all the ES modules, for use with TypeScript or JavaScript, exported by the @antithesishq/bombadil package.

@antithesishq/bombadil

Exports

Always

class Always extends Formula {
  boundMillis: number | null;
  subformula: Formula;
  constructor(boundMillis: number | null, subformula: Formula);
  within(n: number, unit: TimeUnit): Formula;
  toString(): string;
}

And

class And extends Formula {
  left: Formula;
  right: Formula;
  constructor(left: Formula, right: Formula);
  toString(): string;
}

CustomAction

Identifies a custom action and provides it with its arguments. This base action might not be supported by all drivers.

type CustomAction<Args> = {
  Custom: {
    name: string;
    args: Args;
  };
}

Eventually

class Eventually extends Formula {
  boundMillis: number | null;
  subformula: Formula;
  constructor(boundMillis: number | null, subformula: Formula);
  within(n: number, unit: TimeUnit): Formula;
  toString(): string;
}

Formula

class Formula {
  not(): Formula;
  and(that: IntoFormula): Formula;
  or(that: IntoFormula): Formula;
  implies(that: IntoFormula): Formula;
}

Implies

class Implies extends Formula {
  left: Formula;
  right: Formula;
  constructor(left: Formula, right: Formula);
  toString(): string;
}

Next

class Next extends Formula {
  subformula: Formula;
  constructor(subformula: Formula);
  toString(): string;
}

Not

class Not extends Formula {
  subformula: Formula;
  constructor(subformula: Formula);
  toString(): string;
}

Or

class Or extends Formula {
  left: Formula;
  right: Formula;
  constructor(left: Formula, right: Formula);
}

Pure

class Pure extends Formula {
  private pretty;
  value: boolean;
  constructor(pretty: string, value: boolean);
  toString(): string;
}

Thunk

class Thunk extends Formula {
  private pretty;
  apply: () => Formula;
  constructor(pretty: string, apply: () => Formula);
  toString(): string;
}

actions

function actions<A>(generate: () => Tree<A> | A[]): ActionGenerator<A>;

always

function always(x: IntoFormula): Always;

eventually

function eventually(x: IntoFormula): Eventually;

extract

function extract<
  S,
  T extends JSON
>(query: (state: S) => T): ExtractorCell<T, S>;

next

function next(x: IntoFormula): Formula;

not

function not(value: IntoFormula): Not;

now

function now(x: IntoFormula): Formula;

registerCustomAction

Register a new custom action, returning a function used to create action templates in generators. Name must be unique. Prefer using the export from the driver module, which has more a specific type.

function registerCustomAction<Args extends JSON[]>(name: string, handler: (...args: Args) => Promise<void>): (...args: Args) => CustomAction<Args>;

weighted

function weighted<A>(value: [number, A | ActionGenerator<A>][]): ActionGenerator<A>;

Reexports

export { Cell, JSON } from "@antithesishq/bombadil/internal";

export { ActionGenerator, Tree } from "@antithesishq/bombadil/actions";

@antithesishq/bombadil/actions

Exports

ActionDiscriminant

The discriminant in A, like "Click" or "Back".

type ActionDiscriminant<A> = A extends string ? A : keyof A

ActionGenerator

A generator of action templates. Instances of this type is what you need to export from your specification module in order for Bombadil to register your generators.

class ActionGenerator<A> {
  generate: () => Tree<A>;
  constructor(generate: () => Tree<A>);
  map<B>(f: (action: A) => B): ActionGenerator<B>;
  filter<B extends A>(predicate: (action: A) => action is B): ActionGenerator<B>;
  filter(predicate: (action: A) => boolean): ActionGenerator<A>;
  when(condition: boolean | Cell<boolean> | (() => boolean)): ActionGenerator<A>;
  flatMap<R extends readonly unknown[] | ActionGenerator<unknown>>(f: (action: A) => R): ActionGenerator<Flattened<R>>;
}

ActionOfDiscriminant

The actions in A of discriminant D.

type ActionOfDiscriminant<
  A,
  D
> = Extract<A, D> | Extract<A, Record<D & string, unknown>>

CharSet

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

namespace CharSet {
  type Entry = {
    Range: Range;
  } | {
    Literal: string;
  };
  namespace Entry {
    function is<D extends "Range" | "Literal">(entry: Entry, discriminant: D): entry is Extract<Entry, Record<D, unknown>>;
  }
  type Entries = Entry[];
  function fromRange(from: number, to: number): CharSet.Entries;
  function fromLiterals(...literals: string[]): CharSet.Entries;
  function union(...sets: CharSet.Entries[]): CharSet.Entries;
  function is(generator: StringGenerator): generator is CharSetStringGenerator;
}

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

type Entries = Entry[]

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

function fromRange(from: number, to: number): CharSet.Entries;

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

function fromLiterals(...literals: string[]): CharSet.Entries;

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

function union(...sets: CharSet.Entries[]): CharSet.Entries;

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

function is(generator: StringGenerator): generator is CharSetStringGenerator;

CharSetStringGenerator

Generates a string based on one or more charsets.

type CharSetStringGenerator = {
  CharSet: CharSet.Entries;
}

Flattened

The action type produced by a flatMap callback returning R.

type Flattened<R> = R extends ActionGenerator<infer B> ? B : R extends readonly (infer B)[] ? B : never

Range

type Range = number | [number, number]

RegexpStringGenerator

Generates a string based on a regular expression. Uses Rust regex semantics.

type RegexpStringGenerator = {
  Regexp: string;
}

StringGenerator

Generates a string to be used as a parameter in an action.

type StringGenerator = "Email" | TextGenerator | CharSetStringGenerator | RegexpStringGenerator

TextGenerator

Generates a random Unicode string within the given length range.

type TextGenerator = {
  Text: Range;
}

Tree

type Tree<T> = {
  value: T;
} | {
  branches: [number, Tree<T>][];
}

actions

function actions<A>(generate: () => Tree<A> | A[]): ActionGenerator<A>;

branch

function branch<T>(branches: [number, Tree<T>][]): Tree<T>;

isAction

Checks whether the action has the given discriminant and narrows the type if so.

function isAction<
  A extends string | object,
  D extends ActionDiscriminant<A>
>(action: A, discriminant: D): action is ActionOfDiscriminant<A, D> & A;

leaf

function leaf<T>(value: T): Tree<T>;

weighted

function weighted<A>(value: [number, A | ActionGenerator<A>][]): ActionGenerator<A>;

@antithesishq/bombadil/browser

Exports

Action

type Action<
  Number = number,
  String = string
> = CustomAction<JSON[]> | "Back" | "Forward" | "Reload" | "Wait" | {
  Click: {
    fingerprint: Fingerprint;
    point: Point<Number>;
  };
} | {
  DoubleClick: {
    fingerprint: Fingerprint;
    point: Point<Number>;
    delayMillis?: Range;
  };
} | {
  TypeText: {
    text: String;
    delayMillis?: Range;
  };
} | {
  PressKey: {
    code: number;
  };
} | {
  ScrollUp: {
    origin: Point;
    distance: Number;
  };
} | {
  ScrollDown: {
    origin: Point;
    distance: Number;
  };
} | {
  SetFileInputFiles: {
    selector: string;
    files: string[];
  };
} | {
  MouseDrag: {
    from: Point;
    to: Point;
    steps: Number;
    delayMillis: Number;
  };
} | {
  SetViewport: {
    width: Number;
    height: Number;
  };
}

ActionTemplate

type ActionTemplate = Action<Range, StringGenerator>

ConsoleEntry

type ConsoleEntry = {
  timestamp: number;
  level: "warning" | "error";
  args: JSON[];
}

Fingerprint

DOM element fingerprint. String fields are either non-blank or null, and structuralPath is set iff all other nullable fields are null.

type Fingerprint = {
  testId: string | null;
  id: string | null;
  role: string | null;
  accessibleName: string | null;
  tag: string;
  href: string | null;
  nameAttr: string | null;
  placeholder: string | null;
  inputType: string | null;
  textContent: string | null;
  structuralPath: string | null;
}

NavigationEntry

type NavigationEntry = {
  id: number;
  title: string;
  url: string;
}

Point

type Point<Number = number> = {
  x: Number;
  y: Number;
}

Resources

interface Resources {
  js_heap_used: number;
  js_heap_total: number;
  dom_nodes: number;
  documents: number;
  js_event_listeners: number;
  layout_objects: number;
  timestamp: number;
  thread_time: number;
  task_duration: number;
  script_duration: number;
}

State

interface State {
  document: HTMLDocument;
  window: Window;
  navigationHistory: {
    back: NavigationEntry[];
    current: NavigationEntry;
    forward: NavigationEntry[];
  };
  errors: {
    uncaughtExceptions: {
      text: string;
      line: number;
      column: number;
      url: string | null;
      remote_object: {
        type_name: string;
        subtype: string | null;
        class_name: string | null;
        description: string | null;
        value: unknown;
      } | null;
      stacktrace: {
        name: string;
        line: number;
        column: number;
        url: string;
      }[] | null;
    }[];
  };
  console: ConsoleEntry[];
  lastAction: Action | null;
  resources: Resources;
}

actions

function actions(generate: () => Tree<ActionTemplate> | ActionTemplate[]): ActionGenerator<ActionTemplate>;

extract

function extract<T extends JSON>(query: (state: State) => T): Cell<T>;

getFingerprint

function getFingerprint(element: Element): Fingerprint;

registerCustomAction

Register a new custom action, returning a function used to create action templates in generators. Name must be unique.

The first two parameters to the handler are Document and Window, and then any arguments passed to the function.

function registerCustomAction<Args extends JSON[]>(name: string, handler: (document: Document, window: Window, ...args: Args) => Promise<void>): (...args: Args) => ActionTemplate;

weighted

function weighted(value: [number, ActionTemplate | ActionGenerator<ActionTemplate>][]): ActionGenerator<ActionTemplate>;

@antithesishq/bombadil/browser/defaults

Exports

defaultActions

const defaultActions: ActionGenerator<ActionTemplate>

Reexports

export { noHttpErrorCodes, noUncaughtExceptions, noUnhandledPromiseRejections, noConsoleErrors } from "@antithesishq/bombadil/browser/defaults/properties";

@antithesishq/bombadil/browser/defaults/actions

Exports

back

const back: ActionGenerator<ActionTemplate>

clicks

const clicks: ActionGenerator<ActionTemplate>

forward

const forward: ActionGenerator<ActionTemplate>

inputs

const inputs: ActionGenerator<ActionTemplate>

lastAction

const lastAction: Cell<Action | null>

navigation

const navigation: ActionGenerator<ActionTemplate>

reload

const reload: ActionGenerator<ActionTemplate>

scroll

const scroll: ActionGenerator<ActionTemplate>

waitOnce

const waitOnce: ActionGenerator<ActionTemplate>

@antithesishq/bombadil/browser/defaults/properties

Exports

noConsoleErrors

const noConsoleErrors: Formula

noHttpErrorCodes

const noHttpErrorCodes: Formula

noUncaughtExceptions

const noUncaughtExceptions: Formula

noUnhandledPromiseRejections

const noUnhandledPromiseRejections: Formula

[1] See the property based testing guide for an introduction.

[2] You can also configure Bombadil to exit on the first found violation.

[3] Formally, the properties in Bombadil use a flavor of Linear Temporal Logic, if you’re into dense theoretical stuff.

[4] A state transition that allows for nothing to change is a way of making a property “stutter-invariant”, as it’s called in the literature.

官方手冊(Terminal 版純文字)(點開看完整手冊)

官方手冊(Terminal 版純文字)

來源:https://antithesishq.github.io/bombadil/terminal/bombadil-manual.txt

Introduction

Bombadil is property-based testing[1] for user interfaces. It autonomously explores and validates correctness properties, finding harder bugs earlier. It runs in your local developer environment, in CI, and inside Antithesis.

If want to learn more about the background and theory behind property-based testing and user interfaces, begin with Why Bombadil and How it works. If you’re already convinced and just want to get started, head over to Installation.

Why Bombadil

Or rather, why property-based testing? Because example-based testing, especially when testing terminal applications, is costly and limited:

  • Costly, because maintaining hand-written end-to-end test scripts takes a lot of work. Even in the age of AI, tests written and updated by coding agents can easily break and require your attention.

  • Limited, in that they only test very small parts of the state space; a bunch of happy cases, a set of regression tests, and maybe even some error handling cases that are important. But what about everything else — like all the stuff you or the agent didn’t think about testing?

This is where property-based testing, or fuzzing if you will, comes into play. By randomly and systematically searching the state space, Bombadil behaves in ways you didn’t think about testing for; unexpected sequences of actions, weird timings, strange inputs that you forgot could be entered.

How it works

Instead of describing “what good looks like” in terms of fixed test cases, you express general properties of your system, defining how it should behave in all cases. Bombadil checks each property as it explores your system in its chaotic ways, reporting back any violations.

To test a terminal application using Bombadil, you write a specification in TypeScript that exports properties and action generators. These can be domain-specific — to exercise and validate your application’s logic in custom ways — or be imported from Bombadil’s defaults. Bombadil drives any program that reads from stdin and writes to a terminal, whether it’s a traditional CLI, an interactive REPL, or a full TUI.

Conceptually, it runs in a loop doing the following:

  1. Extracts the current state from the terminal
  2. Checks all properties against the current state, recording violations[2]
  3. Selects the next action based on the current state, and performs it
  4. Waits for the next event (chunk of output bytes or timeout)
  5. Returns to step 1

Bombadil itself decides what is an interesting event and when to capture state. You provide the properties and actions, Bombadil does the rest!

Getting started

Bombadil runs on your development machine if you’re on macOS or Linux. Use it to validate changes to TypeScript specifications, and to run short tests while working on your system. Configure something like GitHub Actions or a cron job to continously run longer tests on your main branch or in a deployed staging environment. When you’re ready to put your system under extreme conditions, and test your full stack deterministically, run it inside Antithesis.

Installation

The most straightforward way for you to get started is downloading the executable for your platform:

npm
Install as a development dependency in your project:

npm install --save-dev @antithesishq/bombadil

Add a script to your package.json to run Bombadil:

{
  "scripts": {
    "test": "bombadil terminal test --time-limit=1m your-cli --arg value"
  }
}

Then run it with npm test. This also provides TypeScript type definitions for writing specifications.

macOS
Download the bombadil binary using curl (or wget) and make it executable:

curl -L -o bombadil https://github.com/antithesishq/bombadil/releases/download/v%version%/bombadil-aarch64-darwin
chmod +x bombadil

Put the binary somewhere on your PATH, like in ~/.local/bin if that is configured.

mv ./bombadil ~/.local/bin/bombadil

You should now be able to run it:

bombadil --version

Do not download the executable with your web browser. It will be blocked by GateKeeper.

Linux
Download the bombadil binary and make it executable:

curl -L -o bombadil https://github.com/antithesishq/bombadil/releases/download/v%version%/bombadil-x86_64-linux
chmod +x bombadil

Put the binary somewhere on your PATH, like in ~/.local/bin if that is configured.

mv ./bombadil ~/.local/bin/bombadil

You should now be able to run it:

bombadil --version

Nix (flake)
nix run github:antithesishq/bombadil/v%version% -- --version

GitHub Actions
- uses: antithesishq/bombadil-action@v2
with:
driver: terminal
command: your-cli --arg value
specification: ./bombadil/specification.ts
time-limit: 5m
exit-on-violation: true
output-path: bombadil-output

Docker
Releases are published as tags on Docker Hub:

docker run antithesishq/bombadil:%version% --version

If you want to compile from source, see Contributing.

TypeScript support

When writing specifications in TypeScript, you’ll want the types available. If you installed Bombadil via npm, you already have them — skip ahead to Your first test.

Otherwise, install the package with your package manager of choice:

npm
npm install --save-dev @antithesishq/bombadil

Yarn
yarn add --dev @antithesishq/bombadil

Bun
bun add --development @antithesishq/bombadil

Or use the files provided in the release package.

Your first test

With the CLI installed, let’s run a very simple terminal test just to see that things are working:

bombadil terminal test --output-path my-test head -n100

It’s likely it’ll type a Ctrl+D and have head exit before a hundred lines have been printed. As we didn’t use a custom specification with the --specification option, Bombadil used the default specification for terminal testing, which enters various Unicode input and some escape sequences. It also checks a few common properties, like that the program exits with a zero exit code and that it doesn’t print any byte sequences the terminal can’t render.

The test results are in the file my-test (any filename is accepted). Parent directories must already exist. To see what happened, show each state of the test with its screen:

bombadil trace my-test --screen

See Inspecting test results for more.

Specification language

To extend Bombadil with domain-specific knowledge, you write specifications. These are plain TypeScript or JavaScript modules that use the library provided by Bombadil to export properties and action generators.

Here’s how you run Bombadil with a custom specification:

bombadil terminal test --specification=example.ts example-command

For a full listing of CLI options, see the reference.

Structure

A specification is a regular ES module. The following examples use TypeScript, but you may also write them in JavaScript. If you do use TypeScript, you’ll want to install the types from @antithesishq/bombadil.

Both properties and action generators are exposed to Bombadil as exports:

export const myProperty = ...;

export const myAction = ...;

You may split up your specification into multiple modules and structure it the way you like, but the top-level specification you give to Bombadil must only export properties and action generators.

Importing modules and files

You can split your specification up into multiple modules and import them from the top level specification module:

import { thing } from "./lib/thing.ts";

If you install packages from NPM or similar, you may import those too:

import equal from "deep-equal";

The runtime is limited, so many existing packages might not work, e.g. if they import NodeJS packages.

Non-code files

You can import JSON, text, or binary data. This is useful for bootstrapping tests with reference data, dictionaries, configuration, etc. Use ES import attributes to specify the type of import:

import data from "./fixtures/data.json" with { type: "json" };
import contents from "./wordlist.txt" with { type: "text" };
import raw from "./snapshot.dat" with { type: "binary" };

When using "text" you get a string, and when using "binary" you get Uint8Array.

For JSON data, you can also just use the file extension:

import data from "./fixtures/data.json";

Default properties and action generators

Bombadil comes with a set of default properties and action generators for terminal testing. You’ll probably want to reexport all or at least most of these:

export * from "@antithesishq/bombadil/terminal/defaults";

In fact, these defaults are exactly what are used when running tests without a custom specification file. If you want to selectively pick just a subset of these, replace the * with the relevant names:

export {
    // Properties
    exitSuccess,
    noReplacementChars,
    // Actions
    typeBasicInput,
} from "@antithesishq/bombadil/terminal/defaults";

You may freely combine defaults with your own properties and action generators. All properties and action generators exported by the top-level module are used by Bombadil.

The terminal defaults are rather simple: things like expecting the program to terminate with exit code 0 and not print byte sequences that the terminal can’t handle properly. You likely want to extend the defaults with a custom specification.

Language features

The specification language of Bombadil, embedded in TypeScript or JavaScript, has a small set of central concepts. This section describes them in detail.

Properties

A property is a description of how the system under test should behave in general. This is different from example-based testing (e.g. TUI snapshot testing) where you describe how it behaves for particular cases.

The most intuitive kind of property, which you might have come across before, is an invariant: a condition that should always be true. In Bombadil, invariants are expressed using the always temporal operator:

always( 
    // some condition that should always be true
)

To instruct Bombadil to check your property, you must export it from your specification module. Its name is used in error reports, so give the export a meaningful name.

export const hasTitle = always( 
    // check that there's a title rendered somehow
);

You may export multiple properties, including the defaults, and they’ll all be checked independently. But how do you “check that there’s a title somehow”? You need access to the terminal, and for that, you use extractors.

Extractors

In order to describe a condition about the web page you’re testing, you first need to extract state. This is done with the extract function, which runs on every state that Bombadil decides to capture.

extract(state => ...)

You give it a function that takes the current browser state as an argument, and returns JSON-serializable data. The state object exposes the rendered screen contents, the cursor position, and other observable signals.

To extract the title from the first row of the terminal grid, you’d define this at the top level of your specification:

const title = extract(state => state.grid.rowText(0).trim());

The title value is not a string though — it’s a Cell, a stateful value that changes over time. For every new state captured by Bombadil, the extractor function gets run, and the cell is updated with its return value.

Using the title cell, you can define the property:

export const hasTitle = always(() => 
    title.current !== ""
);

Two things to note about this example:

  1. The expression passed to always is a function that takes no arguments — a thunk. This is because it needs to be evaluated in every state. It needs to always be true, not just once, and that’s why you need to supply the thunk rather than a boolean.
  2. To get the string value out of the cell, you use .current.

This is a custom property using the temporal operator called always. There are other temporal operators, described in Formulas below.

Transforming cells

A cell can be turned into a new cell with map, which applies a function to the value of the original cell in every state:

const titleLength = title.map((title) => title.length);

export const hasShortTitle = always(() =>
    titleLength.current < 80
);

Formulas

Formulas and temporal operators may sound scary, but fear not — they are essentially ways of expressing “conditions over time”. Here are some quick facts about formulas and temporal operators:

  • Temporal operators return formulas.
  • Every property in Bombadil is a formula (of the Formula type).
  • A temporal operator is a function that takes some subformula and evaluates it over time.
  • Different temporal operators evaluate their subformulas in different ways.
  • Bombadil evaluates formulas against a sequence of states to check if they hold true.

Temporal operator types include always, as discussed in the example in Extractors above, and also eventually and next. Here’s an informal[3] description of how they work:

  • always(x) holds if x holds in this and every future state
  • next(x) holds if x holds in the next state
  • eventually(x) holds if x holds in this or any future state

They accept subformulas as arguments. You’ll notice in the example with always above, the argument was a thunk. This still works, because the operators automatically convert thunks into formulas. In fact, there’s an operator for doing that explicitly, called now:

always(now(() => title.current !== ""))

You normally don’t have to use the now operator, unless you want to use logical connectives at the formula level. They are defined as methods on formulas:

  • x.and(y) holds if x holds and y holds
  • x.or(y) holds if x holds or y holds
  • x.implies(y) holds if x doesn’t hold or y holds

There’s also negation, both as a function and as a method on formulas, i.e. not(x) and x.not().

The now operator is useful when expressing single-state preconditions. The following property checks that submitting a command shows a loading indicator that is eventually hidden:

const commandSubmitted = extract(() => ...);
const loadingShown = extract(() => ...);

now(() => commandSubmitted.current).implies(
    now(() => loadingShown.current)
        .and(eventually(() => !loadingShown.current))
)

You can build more advanced formulas, and even include nested temporal operators, but the basics are often powerful enough. See the examples at the bottom for more inspiration.

Action generators

In addition to exporting properties in a specification, you export action generators. A generator is an object of the ActionGenerator class. An action generator generates values of type Tree.

Like with default properties, there are default action generators provided by Bombadil. These will get you a long way, but there are times where you’ll need to define your own action generators.

For every state that Bombadil captures, all action generators are run, contributing to a tree structure of possible action templates. These are called action templates and are parameterized by ranges of values. Bombadil then randomly picks one in that tree, and picks random values within the ranges for the parameters. Why a tree, though? It’s because the branches are weighted — equally, by default. But you can override this to control the probability of an action being picked.

To define a custom action generator, you use the actions function, which takes a thunk that returns an array of action templates:

export const myAction = actions(() => {
    return [
        ...
    ];
});

In the returned array, each element is a value of the ActionTemplate type, provided by the NPM package. See the TypeScript source for reference.

Here’s a generator that sends either a help command or an incr command with an numeric argument:

export const sendCommand = actions(() => {
    return [
        { TypeText: { Regexp: "help\n" } },
        { TypeText: { Regexp: "incr \d{2,4}\n" } },
    ];
});

The actions you return must be possible to perform in the current state. Your action generators should therefore depend on cells and validate your actions before returning them.

To give actions different weights, use the weighted combinator and wrap each subgenerator in an array with the weight as the first element:

export const inputs = weighted([
  [10, typeFromSet(CharSets.UNICODE_SAFE)],
  [1, typeFromSet(CharSets.CONTROL_COMMON)],
]);

Transforming action generators

Rather than writing a generator from scratch, you can often adapt an existing one, such as the ones provided as defaults. Action generators have map, filter, and flatMap methods that work similarly to those in Array. Weights are preserved when transforming a generator. Use isAction to check what kind of action you’re dealing with, which also narrows its type.

The difference between the two mapping methods is what the function returns. With map, each action is replaced by a single other action. With flatMap, each action is replaced by an array of actions, picked uniformly, or by another action generator. Returning an empty array from flatMap drops the action.

Here’s the default typeBasicInput generator, never typing Enter. It uses flatMap to drop actions whose charset ends up empty:

import { CharSet, isAction } from "@antithesishq/bombadil/actions";
import { typeBasicInput } from "@antithesishq/bombadil/terminal/defaults";

export const typeWithoutEnter = typeBasicInput.flatMap((action) => {
    if (!(isAction(action, "TypeText") && CharSet.is(action.TypeText))) {
        return [action];
    }
    const set = action.TypeText.CharSet.filter(
        (entry) =>
            !(CharSet.Entry.is(entry, "Literal") && entry.Literal === "\r"),
    );
    return set.length > 0 ? [{ TypeText: { CharSet: set } }] : [];
});

Only export the transformed typeBasicInput and not the original definition. Otherwise Bombadil will still be able to type Enter.

To enable a generator only in certain states, use when with a boolean, a cell, or a function returning a boolean. When the condition is false, the generator isn’t run at all:

import { extract } from "@antithesishq/bombadil/terminal";
import { typeBasicInput } from "@antithesishq/bombadil/terminal/defaults";

const idle = extract(
    (state) =>
        !state.grid.rowText(state.grid.size.rows - 1).includes("Loading"),
);

export const typeWhenIdle = typeBasicInput.when(idle);

Custom actions

Custom actions are not supported by the terminal driver.

Optional properties

In addition to the default properties, there’s a set of extras modules with properties that you can use. These are not included in the defaults and need to be specifically used and exported in your top-level specification module.

There are currently only extras modules for the browser driver, and none for the terminal driver.

Examples

These are full, runnable examples of properties and action generators you might need in your own testing with Bombadil. Think of them as design patterns for properties. Each example is a self-contained specification file.

Successful exit

A simple property that fails if the process terminates with a non-zero exit code. This is one of the default properties for the terminal.

import { not, always, Formula } from "@antithesishq/bombadil";
import { extract } from "@antithesishq/bombadil/terminal";

const exitStatus = extract((state) => state.exitStatus);

export const exitSuccess: Formula = always(
  not(
    () =>
      !!exitStatus.current &&
      exitStatus.current.signal == null &&
      exitStatus.current.code > 0,
  ),
);

No replacement chars

A property that checks whether or not a replacement unicode character (U+FFFD) has been detected. That character is what a terminal shows when a program emits malformed UTF-8. This is one of the default properties for the terminal.

import { always, Formula } from "@antithesishq/bombadil";
import { extract } from "@antithesishq/bombadil/terminal";

function toHex(str: string): string {
  var result = "";
  for (var i = 0; i < str.length; i++) {
    result += str.charCodeAt(i).toString(16);
  }
  return result;
}

const replacementChars = extract((state) => {
  const result = [];
  for (let i = 0; i < state.grid.size.rows; i++) {
    for (const match of state.grid.rowText(i).matchAll(/\uFFFD/g)) {
      result.push({
        row: i,
        column: match.index,
        contents: match[0],
        hex: toHex(match[0]),
      });
    }
  }
  return result;
});

export const noReplacementChars: Formula = always(
  () => (replacementChars.current ?? []).length === 0,
);

Output matching

A property that checks that certain text is generated while running the test. The code also defines an action generator that mixes typing “hello world” into the default input, so the property can be satisfied.

import { eventually } from "@antithesishq/bombadil";
import { ActionGenerator, branch, leaf } from "@antithesishq/bombadil/actions";
import { ActionTemplate, extract } from "@antithesishq/bombadil/terminal";
import { typeBasicInput } from "@antithesishq/bombadil/terminal/defaults";

const nonBlankLines = extract((state) => {
  const lines = [];
  for (let index = 0; index < state.grid.size.rows; index++) {
    const text = state.grid.rowText(index).trim();
    if (text) {
      lines.push(text);
    }
  }
  return lines;
});

export const eventuallyHelloWorld = eventually(
  () =>
    nonBlankLines.current.filter((line) => line.includes("hello world"))
      .length > 5,
).within(5, "seconds");

export const typeHelloWorld = new ActionGenerator(() =>
  branch([
    [10, typeBasicInput.generate()],
    [1, leaf({ TypeText: { Regexp: "hello world" } } as ActionTemplate)],
  ]),
);

Workflows

This section describes how to run tests and debug violations with Bombadil. Each workflow is a building block in a composable set of tools for finding, understanding, and fixing bugs in user interfaces.

Reproducing violations

If Bombadil finds a bug in a project you’re working on, you might want to reproduce that test case when working on a bug fix. That is, have Bombadil perform the same sequence of actions to reach the same state.

Use the --reproduce option and point it to the trace file of the original test run:

bombadil terminal test --reproduce=my-test your-cli

Reproductions are not guaranteed to succeed. If they diverge, Bombadil fails with an error. For reproductions to succeed, it’s important to use the same options as in the original test. After a test run, Bombadil prints both the inspect and --reproduce commands you can use.

Shrinking violations

When Bombadil finds a violation, the trace leading up to it is often long and full of actions that have nothing to do with the bug. The shrink command takes such a trace and searches for a shorter one that still violates the same property.

Shrinking is experimental. The command-line options and output format may change between releases.

bombadil terminal shrink --trace my-test your-cli

It’s important that the shrink invocation uses the same options as the original test or fuzz invocation, just as when reproducing violations.

Shrinking begins with a calibration phase that tries to assess the flakiness of reproducing the violation. Calibration can be controlled with --calibration-runs and --confirmation-runs-max if needed. At the end of shrinking, you get a new trace file, configured with --output-path and --output-path-overwrite, that can be reproduced or inspected.

Trace inputs are always files, never directories. For a single test or shrink, --output-path names the actual trace file and accepts any filename; its parent directory must already exist. Without it, Bombadil chooses a unique file in system temp. For fuzz, the option is a file base: run.bin writes sibling files run-0.bin, run-1.bin, and so on, without per-run directories. Browser downloads use a separate temporary directory logged before the run and removed afterwards. Shrinking permits a sibling output but rejects an input alias, including symbolic links and hard links. Use --output-path-overwrite to replace an existing file.

Inspecting test results

When you’ve run a test and found one or more violations, you likely want to understand what happened. The bombadil trace command shows a trace in the terminal, one state at a time:

bombadil trace my-test --screen

Each state lists the action that led to it, the time since the first state, and the properties it violated. With --screen, you also see the terminal screen as the properties saw it. Pick states with --state (--state 40..50 shows states 40 to 49), keep the screen’s colors with --color, or print one JSON object per state with --json (with --screen, including the screen) to process the trace with tools like jq.

Reference

This section describes the technical details of the command-line interface and the TypeScript modules used when writing specifications. If you instead want instructions on how to set up your environment with Bombadil, see Installation and Typescript support.

Command-line interface

The primary way of using Bombadil, at least locally, is through the command-line interface (CLI). This section describes in detail what commands are available, and what options, flags, and arguments you can give them.

The general exit code semantics of the CLI is:

Code Meaning

   0 Test or fuzzing campaign completed normally (including time limit)
   1 Other error
   2 Property violation(s) detected

Property violations take precedence, so failed fuzz runs only cause the fuzzing campaign to exit with 1 if there are no violations found.

bombadil terminal test

(EXPERIMENTAL) Test the given program against a TypeScript specification.

bombadil terminal test [OPTIONS] [COMMAND]...

Arguments

[COMMAND]...
The command to run as the system under test. Everything after -- is forwarded as program + arguments.

Options

--specification
Path to a TypeScript specification file (uses the @antithesishq/bombadil/terminal API). Unless specified, Bombadil will use the default specification for terminal UIs.

--exit-on-violation
Whether to exit the test when first failing property is found (useful in development and CI).

--time-limit
Maximum time to run the test. Accepts a number with a unit suffix: s (seconds), m (minutes), h (hours), or d (days).

--columns

Terminal columns at startup.

Default: 100

--rows

Terminal rows at startup.

Default: 40

--scrollback-lines-max

Maximum line count to keep in scrollback buffer.

Default: 100

--quiescence-timeout-ms

How long to wait (in milliseconds) for the program to stop emitting output before extracting the next state. Lower values increase throughput but risk sampling mid-render; higher values give the program more time to finish drawing.

Default: 5

--output-path
Trace FILE to write (any filename). Defaults to a unique file in system temp. Parent directories must already exist.

--output-path-overwrite
Overwrite any existing trace at --output-path. Without this flag, Bombadil refuses to replace an existing file.

--reproduce
Reproduce a previous test run from a trace file, not a directory. Replays the recorded actions in order instead of generating new ones.

-h, --help
Print help.

Examples

Test a program using the default specification:

bombadil terminal test my-tui --arg value

Use a custom specification and stop after one minute:

bombadil terminal test --specification tui.spec.ts --time-limit 1m my-tui

Reproduce a previous test run (best-effort, fails on divergence):

bombadil terminal test --reproduce my-test my-tui --arg value

bombadil terminal shrink

(EXPERIMENTAL) Shrink a trace with a property violation into a smaller one that still violates it (best-effort, as with reproduce).

bombadil terminal shrink [OPTIONS] [COMMAND]...

Arguments

[COMMAND]...
The command to run as the system under test. Everything after -- is forwarded as program + arguments.

Options

--trace
Trace FILE to shrink (any filename, not a directory).

--property
Name of the property to shrink for. Required if the trace has violations of more than one property.

--output-path
Trace FILE to write. Defaults to a unique file in system temp. Parent directories must already exist. Must not alias the input.

--output-path-overwrite
Overwrite any existing file at --output-path.

--time-limit
Maximum time to shrink for, after which the smallest trace found so far is kept. Accepts a number with a unit suffix: s (seconds), m (minutes), h (hours), or d (days).

--parallelism

Number of test runs to execute in parallel. Only use this if runs are isolated from each other (e.g. not sharing files or a backend).

Default: 1

--calibration-runs

Number of times to replay the original trace to measure how reliably it reproduces the violation.

Default: 3

--confirmation-runs-max

Maximum number of runs used to confirm that a smaller trace reproduces reliably enough.

Default: 5

--specification
Path to a TypeScript specification file (uses the @antithesishq/bombadil/terminal API). Unless specified, Bombadil will use the default specification for terminal UIs.

--columns

Terminal columns at startup.

Default: 100

--rows

Terminal rows at startup.

Default: 40

--scrollback-lines-max

Maximum line count to keep in scrollback buffer.

Default: 100

--quiescence-timeout-ms

How long to wait (in milliseconds) for the program to stop emitting output before extracting the next state. Lower values increase throughput but risk sampling mid-render; higher values give the program more time to finish drawing.

Default: 5

-h, --help
Print help.

Examples

Shrink the trace in my-test, which violates a single property:

bombadil terminal shrink --trace my-test my-tui --arg value

Shrink for a specific property, running four programs in parallel:

bombadil terminal shrink --trace my-test --property noCrash --parallelism 4 --specification tui.spec.ts my-tui

bombadil terminal fuzz

(EXPERIMENTAL) Fuzz (running many short test runs) the given program against a TypeScript specification.

bombadil terminal fuzz [OPTIONS] [COMMAND]...

Arguments

[COMMAND]...
The command to run as the system under test. Everything after -- is forwarded as program + arguments.

Options

--specification
Path to a TypeScript specification file (uses the @antithesishq/bombadil/terminal API). Unless specified, Bombadil will use the default specification for terminal UIs.

--exit-on-violation
Whether to exit the test when first failing property is found (useful in development and CI).

--time-limit-run

Maximum time to run an individual test run. Accepts a number with a unit suffix: s (seconds), m (minutes), h (hours), or d (days).

Default: 10s

--time-limit-fuzz

Maximum time to run the full fuzzing campaign. Accepts a number with a unit suffix: s (seconds), m (minutes), h (hours), or d (days).

Default: 5m

--swarm
Whether to apply swarm testing to actions. Otherwise all actions are enabled.

--parallelism

Number of test runs to execute in parallel.

Default: 1

--columns

Terminal columns at startup.

Default: 100

--rows

Terminal rows at startup.

Default: 40

--scrollback-lines-max

Maximum line count to keep in scrollback buffer.

Default: 100

--quiescence-timeout-ms

How long to wait (in milliseconds) for the program to stop emitting output before extracting the next state. Lower values increase throughput but risk sampling mid-render; higher values give the program more time to finish drawing.

Default: 5

--output-path
Trace file base: run.bin writes sibling files run-0.bin, run-1.bin, etc. Defaults to a unique base in system temp.

--output-path-overwrite
Overwrite any existing trace at --output-path. Without this flag, Bombadil refuses to replace an existing numbered file.

-h, --help
Print help.

bombadil trace

Show the states of a binary trace file (any filename).

bombadil trace [OPTIONS]

Arguments


Trace FILE to read (any filename, not a directory).

Options

--state
Only show this state, or a range of states such as 40..50 (from 40 up to but not including 50), 40.. or ..50.

--json
Print one JSON object per state: its index, metadata and payload size, with –screen its screen (a string, or null without one), and with –screenshots the file its screenshot is in, if it has one.

--screen
Show each state’s screen (terminal traces).

--color
Show screens with their colors and styles, as ANSI escape sequences (implies –screen).

--screenshots
Write the screenshot of each state shown into this directory, as . (browser traces), or .bin for a format other than png and jpeg. A file already there is left as it is if it holds the same screenshot, and refused otherwise.

-h, --help
Print help.

TypeScript reference

These are all the ES modules, for use with TypeScript or JavaScript, exported by the @antithesishq/bombadil package.

@antithesishq/bombadil

Exports

Always

class Always extends Formula {
  boundMillis: number | null;
  subformula: Formula;
  constructor(boundMillis: number | null, subformula: Formula);
  within(n: number, unit: TimeUnit): Formula;
  toString(): string;
}

And

class And extends Formula {
  left: Formula;
  right: Formula;
  constructor(left: Formula, right: Formula);
  toString(): string;
}

CustomAction

Identifies a custom action and provides it with its arguments. This base action might not be supported by all drivers.

type CustomAction<Args> = {
  Custom: {
    name: string;
    args: Args;
  };
}

Eventually

class Eventually extends Formula {
  boundMillis: number | null;
  subformula: Formula;
  constructor(boundMillis: number | null, subformula: Formula);
  within(n: number, unit: TimeUnit): Formula;
  toString(): string;
}

Formula

class Formula {
  not(): Formula;
  and(that: IntoFormula): Formula;
  or(that: IntoFormula): Formula;
  implies(that: IntoFormula): Formula;
}

Implies

class Implies extends Formula {
  left: Formula;
  right: Formula;
  constructor(left: Formula, right: Formula);
  toString(): string;
}

Next

class Next extends Formula {
  subformula: Formula;
  constructor(subformula: Formula);
  toString(): string;
}

Not

class Not extends Formula {
  subformula: Formula;
  constructor(subformula: Formula);
  toString(): string;
}

Or

class Or extends Formula {
  left: Formula;
  right: Formula;
  constructor(left: Formula, right: Formula);
}

Pure

class Pure extends Formula {
  private pretty;
  value: boolean;
  constructor(pretty: string, value: boolean);
  toString(): string;
}

Thunk

class Thunk extends Formula {
  private pretty;
  apply: () => Formula;
  constructor(pretty: string, apply: () => Formula);
  toString(): string;
}

actions

function actions<A>(generate: () => Tree<A> | A[]): ActionGenerator<A>;

always

function always(x: IntoFormula): Always;

eventually

function eventually(x: IntoFormula): Eventually;

extract

function extract<
  S,
  T extends JSON
>(query: (state: S) => T): ExtractorCell<T, S>;

next

function next(x: IntoFormula): Formula;

not

function not(value: IntoFormula): Not;

now

function now(x: IntoFormula): Formula;

registerCustomAction

Register a new custom action, returning a function used to create action templates in generators. Name must be unique. Prefer using the export from the driver module, which has more a specific type.

function registerCustomAction<Args extends JSON[]>(name: string, handler: (...args: Args) => Promise<void>): (...args: Args) => CustomAction<Args>;

weighted

function weighted<A>(value: [number, A | ActionGenerator<A>][]): ActionGenerator<A>;

Reexports

export { Cell, JSON } from "@antithesishq/bombadil/internal";

export { ActionGenerator, Tree } from "@antithesishq/bombadil/actions";

@antithesishq/bombadil/actions

Exports

ActionDiscriminant

The discriminant in A, like "Click" or "Back".

type ActionDiscriminant<A> = A extends string ? A : keyof A

ActionGenerator

A generator of action templates. Instances of this type is what you need to export from your specification module in order for Bombadil to register your generators.

class ActionGenerator<A> {
  generate: () => Tree<A>;
  constructor(generate: () => Tree<A>);
  map<B>(f: (action: A) => B): ActionGenerator<B>;
  filter<B extends A>(predicate: (action: A) => action is B): ActionGenerator<B>;
  filter(predicate: (action: A) => boolean): ActionGenerator<A>;
  when(condition: boolean | Cell<boolean> | (() => boolean)): ActionGenerator<A>;
  flatMap<R extends readonly unknown[] | ActionGenerator<unknown>>(f: (action: A) => R): ActionGenerator<Flattened<R>>;
}

ActionOfDiscriminant

The actions in A of discriminant D.

type ActionOfDiscriminant<
  A,
  D
> = Extract<A, D> | Extract<A, Record<D & string, unknown>>

CharSet

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

namespace CharSet {
  type Entry = {
    Range: Range;
  } | {
    Literal: string;
  };
  namespace Entry {
    function is<D extends "Range" | "Literal">(entry: Entry, discriminant: D): entry is Extract<Entry, Record<D, unknown>>;
  }
  type Entries = Entry[];
  function fromRange(from: number, to: number): CharSet.Entries;
  function fromLiterals(...literals: string[]): CharSet.Entries;
  function union(...sets: CharSet.Entries[]): CharSet.Entries;
  function is(generator: StringGenerator): generator is CharSetStringGenerator;
}

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

type Entries = Entry[]

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

function fromRange(from: number, to: number): CharSet.Entries;

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

function fromLiterals(...literals: string[]): CharSet.Entries;

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

function union(...sets: CharSet.Entries[]): CharSet.Entries;

Encodes characther ranges or literal strings for use in action templates, where Bombadil will generate concrete strings based on the charsets.

function is(generator: StringGenerator): generator is CharSetStringGenerator;

CharSetStringGenerator

Generates a string based on one or more charsets.

type CharSetStringGenerator = {
  CharSet: CharSet.Entries;
}

Flattened

The action type produced by a flatMap callback returning R.

type Flattened<R> = R extends ActionGenerator<infer B> ? B : R extends readonly (infer B)[] ? B : never

Range

type Range = number | [number, number]

RegexpStringGenerator

Generates a string based on a regular expression. Uses Rust regex semantics.

type RegexpStringGenerator = {
  Regexp: string;
}

StringGenerator

Generates a string to be used as a parameter in an action.

type StringGenerator = "Email" | TextGenerator | CharSetStringGenerator | RegexpStringGenerator

TextGenerator

Generates a random Unicode string within the given length range.

type TextGenerator = {
  Text: Range;
}

Tree

type Tree<T> = {
  value: T;
} | {
  branches: [number, Tree<T>][];
}

actions

function actions<A>(generate: () => Tree<A> | A[]): ActionGenerator<A>;

branch

function branch<T>(branches: [number, Tree<T>][]): Tree<T>;

isAction

Checks whether the action has the given discriminant and narrows the type if so.

function isAction<
  A extends string | object,
  D extends ActionDiscriminant<A>
>(action: A, discriminant: D): action is ActionOfDiscriminant<A, D> & A;

leaf

function leaf<T>(value: T): Tree<T>;

weighted

function weighted<A>(value: [number, A | ActionGenerator<A>][]): ActionGenerator<A>;

@antithesishq/bombadil/terminal

Exports

Action

type Action<
  Number = number,
  String = string
> = {
  TypeText: String;
} | {
  Resize: Size<Number>;
} | {
  Click: {
    row: Range;
    column: Range;
  };
} | {
  ScrollUp: {};
} | {
  ScrollDown: {};
}

ActionTemplate

type ActionTemplate = Action<Range, StringGenerator>

Attributes

enum Attributes {
  Bold = 1,
  Italic = 2,
  Blink = 4,
  Inverse = 8,
  Strikethrough = 16,
  Dim = 32,
  Invisible = 64,
  Overline = 128
}

namespace Attributes {
  function has(style: Style, attribute: Attributes): boolean;
}

Color

type Color = "None" | {
  Palette: number;
} | {
  RGB: {
    r: number;
    g: number;
    b: number;
  };
}

Cursor

interface Cursor {
  position: CursorPosition;
  visible: boolean;
  blinking: boolean;
  visualStyle: CursorVisualStyle;
  color: Color;
}

CursorPosition

interface CursorPosition {
  column: number;
  row: number;
}

CursorVisualStyle

type CursorVisualStyle = "Bar" | "Block" | "Underline" | "BlockHollow" | "Unknown"

Grid

interface Grid {
  size: Size;
  row(index: number): GridCell[];
  rowText(index: number): string;
}

GridCell

interface GridCell {
  contents: string;
  wide: boolean;
  style: Style;
}

Size

type Size<Number = number> = {
  columns: Number;
  rows: Number;
}

State

interface State {
  grid: Grid;
  scrollback: Grid;
  scrollOffset: number;
  cursor: Cursor;
  exitStatus: {
    code: number;
    signal: string | null;
  } | null;
  lastAction: Action | null;
}

Style

interface Style {
  foregroundColor: Color;
  backgroundColor: Color;
  underlineColor: Color;
  underline: Underline;
  attributes: number;
}

Underline

type Underline = "None" | "Single" | "Double" | "Curly" | "Dotted" | "Dashed"

actions

function actions(generate: () => Tree<ActionTemplate> | ActionTemplate[]): ActionGenerator<ActionTemplate>;

extract

function extract<T extends JSON>(query: (state: State) => T): Cell<T>;

weighted

function weighted(value: [number, ActionTemplate | ActionGenerator<ActionTemplate>][]): ActionGenerator<ActionTemplate>;

@antithesishq/bombadil/terminal/defaults

Exports

typeBasicInput

const typeBasicInput: ActionGenerator<ActionTemplate>

Reexports

export { exitSuccess, noReplacementChars } from "@antithesishq/bombadil/terminal/defaults/properties";

@antithesishq/bombadil/terminal/defaults/actions

Exports

CharSets

namespace CharSets {
  const CONTROL_COMMON: CharSet.Entries;
  const CONTROL_EDITING: CharSet.Entries;
  const CONTROL_ARROWS: CharSet.Entries;
  const CONTROL_ARROWS_MODIFIED: CharSet.Entries;
  const CONTROL_EDITING_ALT: CharSet.Entries;
  const CONTROL_NAVIGATION: CharSet.Entries;
  const CONTROL_ALL: CharSet.Entries;
  const FUNCTION_KEYS: CharSet.Entries;
  const ASCII_PRINTABLE: CharSet.Entries;
  const UNICODE_LATIN_EXTENDED: CharSet.Entries;
  const UNICODE_GREEK: CharSet.Entries;
  const UNICODE_CYRILLIC: CharSet.Entries;
  const UNICODE_CJK: CharSet.Entries;
  const UNICODE_HANGUL: CharSet.Entries;
  const UNICODE_EMOTICONS: CharSet.Entries;
  const UNICODE_SYMBOLS_PICTOGRAPHS_SAFE: CharSet.Entries;
  const UNICODE_SAFE: CharSet.Entries;
}

lastAction

const lastAction: Cell<Action | null>

pasteText

function pasteText(text: string): ActionGenerator<ActionTemplate>;

typeFromSet

function typeFromSet(set: CharSet.Entries): ActionGenerator<ActionTemplate>;

@antithesishq/bombadil/terminal/defaults/properties

Exports

exitSuccess

const exitSuccess: Formula

noReplacementChars

const noReplacementChars: Formula

[1] See the property based testing guide for an introduction.

[2] You can also configure Bombadil to exit on the first found violation.

[3] Formally, the properties in Bombadil use a flavor of Linear Temporal Logic, if you’re into dense theoretical stuff.