Add a TAP test suite alongside mocha

Tests live in tests/, mirroring each package's src, and in
plugins/*/test/*.test.ts. They are TypeScript run by Node's type stripping,
so the @tapjs/typescript plugin is disabled and `pnpm install` runs tap build
to apply that.

The first tests cover the largest lib files: link, subscriptions, config
classes and prometheus. A shared helper checks the JSON serialisable class
pattern, and one test runs it on every serialisable class lib exports, with
samples generated from each class's schema.

Known bugs the new tests found are marked todo. Mocha, codecov and the
existing CI matrix are unchanged; tap.yml runs the new suite on the latest
Node.js and Factorio.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-11-24 22:21:09 +00:00
1 parent bbcb64d411
commit b73b584d2d
16 files changed
+5348 -5

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
# TAP test suite, run alongside the mocha suite in node.js.yml until it reaches
# similar coverage. Only the latest Node.js and Factorio are tested here.
name: TAP tests
on:
push:
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }}
cancel-in-progress: true
env:
NODE_VERSION: 26.x
FACTORIO_VERSION: 2.1.17
jobs:
changes:
uses: ./.github/workflows/ci-changes.yml
test:
needs: changes
if: ${{ !cancelled() && needs.changes.outputs.build_and_test != 'false' }}
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- name: Prepare and install
uses: ./.github/actions/pnpm-install
with:
node-version: ${{ env.NODE_VERSION }}
- name: Use Factorio ${{ env.FACTORIO_VERSION }}
run: wget -q -O factorio.tar.gz https://www.factorio.com/get-download/${{ env.FACTORIO_VERSION }}/headless/linux64 && tar -xf factorio.tar.gz && rm factorio.tar.gz
- name: Type check tests
run: pnpm run test:typecheck
- name: Run tests
run: pnpm run test:tap
+1
View File
@@ -12,6 +12,7 @@ lib-cov
# Coverage directories used by tools like c8 and codecov # Coverage directories used by tools like c8 and codecov
coverage coverage
/.tap/
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt .grunt
+6
View File
@@ -0,0 +1,6 @@
# Node.js strips the types itself, see tests/README.md
plugin:
- "!@tapjs/typescript"
include:
- "tests/**/*.test.ts"
- "plugins/*/test/**/*.test.ts"
+5 -1
View File
@@ -50,6 +50,7 @@ Clusterio manages distributed Factorio servers through a controller, hosts, and
| `packages/host/modules/` | Lua modules injected into saves. | | `packages/host/modules/` | Lua modules injected into saves. |
| `packages/host/lua/` | Factorio mod sources, including `clusterio_lib`. | | `packages/host/lua/` | Factorio mod sources, including `clusterio_lib`. |
| `test/` | Root test suite, fixtures, helpers, integration harness, and manual tests. Plugin tests also live under `plugins/*/test/`. | | `test/` | Root test suite, fixtures, helpers, integration harness, and manual tests. Plugin tests also live under `plugins/*/test/`. |
| `tests/` | TAP test suite replacing `test/`, see [its readme](tests/README.md). |
Start with [how it works](../how-it-works.md), [communication](communication.md), and the [config system](config-system.md) for architecture. Start with [how it works](../how-it-works.md), [communication](communication.md), and the [config system](config-system.md) for architecture.
See [writing plugins](writing-plugins.md) and [developing for Clusterio](developing-for-clusterio.md) for plugin and Factorio contracts. See [writing plugins](writing-plugins.md) and [developing for Clusterio](developing-for-clusterio.md) for plugin and Factorio contracts.
@@ -213,6 +214,9 @@ NODE_EXTRA_CA_CERTS="$PWD/test/file/tls/cert.pem" pnpm exec mocha \
``` ```
Replace the example file with the relevant test; use `--grep` to narrow it further. Replace the example file with the relevant test; use `--grep` to narrow it further.
A TAP suite in `tests/` is replacing the Mocha suite one area at a time.
New unit tests go there; see [the TAP test readme](tests/README.md) for layout, conventions and commands.
Preserve the test TLS CA configuration for HTTPS integration tests. Preserve the test TLS CA configuration for HTTPS integration tests.
Use `--require ./test/setup_logging.js` when an isolated test needs the shared logger configured. Use `--require ./test/setup_logging.js` when an isolated test needs the shared logger configured.
Some tests import `test/integration/index.js`, which installs root hooks and starts a controller and host even for a targeted invocation. Some tests import `test/integration/index.js`, which installs root hooks and starts a controller and host even for a targeted invocation.
@@ -234,7 +238,7 @@ Inspect `node scripts/clean.js --help` and preview the selected scope with `--dr
| Command | Removal scope | | Command | Removal scope |
| --- | --- | | --- | --- |
| `node scripts/clean.js --dry-run` | Preview workspace package/plugin build output and Vite dependency caches; omit `--dry-run` to clean, or use `pnpm clean`. | | `node scripts/clean.js --dry-run` | Preview workspace package/plugin build output and Vite dependency caches; omit `--dry-run` to clean, or use `pnpm clean`. |
| `node scripts/clean.js tests --dry-run` | Also preview root `.nyc_output/`, `coverage/`, the whole `temp/` directory, and `static/`. | | `node scripts/clean.js tests --dry-run` | Also preview root `.nyc_output/`, `.tap/`, `coverage/`, the whole `temp/` directory, and `static/`. |
| `node scripts/clean.js all --dry-run` | Also preview runtime databases, instances, logs, mods, local configs, `FactorioAdminToken.txt`, and `plugin-list.json`. | | `node scripts/clean.js all --dry-run` | Also preview runtime databases, instances, logs, mods, local configs, `FactorioAdminToken.txt`, and `plugin-list.json`. |
`all` deletes cluster runtime data, including configurations and saves; back up anything you want to keep before using it. `all` deletes cluster runtime data, including configurations and saves; back up anything you want to keep before using it.
+11 -3
View File
@@ -15,10 +15,17 @@
"cover": "c8 pnpm test", "cover": "c8 pnpm test",
"fast-cover": "FAST_TEST=y c8 pnpm test", "fast-cover": "FAST_TEST=y c8 pnpm test",
"ci-cover": "c8 --reporter=lcovonly pnpm test", "ci-cover": "c8 --reporter=lcovonly pnpm test",
"lint": "oxlint packages plugins test", "test:tap": "pnpm run build && tap --disable-coverage",
"lint-fix": "oxlint --fix packages plugins test", "test:unit": "pnpm run build && tap --disable-coverage \"tests/!(integrations|shared)/**/*.test.ts\"",
"test:integration": "pnpm run build && tap --disable-coverage tests/integrations",
"test:plugins": "pnpm run build && tap --disable-coverage \"plugins/*/test/**/*.test.ts\"",
"test:coverage": "pnpm run build && tap --allow-incomplete-coverage --coverage-report=text --coverage-report=html --no-browser",
"test:typecheck": "tsc -p tests",
"lint": "oxlint packages plugins test tests",
"lint-fix": "oxlint --fix packages plugins test tests",
"clean": "node ./scripts/clean.js", "clean": "node ./scripts/clean.js",
"bundle-dependencies": "bundle-dependencies" "bundle-dependencies": "bundle-dependencies",
"prepare": "tap build"
}, },
"c8": { "c8": {
"exclude": [ "exclude": [
@@ -49,6 +56,7 @@
"jsonwebtoken": "catalog:", "jsonwebtoken": "catalog:",
"mocha": "^12.0.3", "mocha": "^12.0.3",
"oxlint": "^1.88.0", "oxlint": "^1.88.0",
"tap": "^21.8.1",
"typescript": "catalog:", "typescript": "catalog:",
"yargs": "catalog:", "yargs": "catalog:",
"yauzl": "catalog:", "yauzl": "catalog:",
+3
View File
@@ -47,3 +47,6 @@ autoInstallPeers: false
linkWorkspacePackages: true linkWorkspacePackages: true
shellEmulator: true shellEmulator: true
allowBuilds:
'@swc/core': false
+1 -1
View File
@@ -62,7 +62,7 @@ async function removeBuildArtifacts() {
*/ */
async function removeTestArtifacts() { async function removeTestArtifacts() {
const artifacts = [ const artifacts = [
".nyc_output", "coverage", "temp", "static", ".nyc_output", ".tap", "coverage", "temp", "static",
]; ];
await Promise.all(artifacts.map(artifact => tryRemove(path.resolve(artifact)))); await Promise.all(artifacts.map(artifact => tryRemove(path.resolve(artifact))));
+104
View File
@@ -0,0 +1,104 @@
# TAP tests
This suite uses [node-tap](https://node-tap.org/) and runs next to the Mocha suite in `test/`.
Mocha is removed once this suite has similar coverage.
Write new unit tests here.
Tests are TypeScript, run by Node.js directly with type stripping.
The `@tapjs/typescript` plugin is disabled in `.taprc`, so only [erasable syntax](https://www.typescriptlang.org/tsconfig/#erasableSyntaxOnly) works: no enums, parameter properties or namespaces.
Relative imports use the `.ts` extension.
Packages are imported by name, which resolves to their compiled output, so build before running.
## Layout
```
tests/
├── integrations/ # Cross-package and host integration tests
├── <package>/ # Unit tests, mirroring the package's src/
└── shared/ # Test utilities and fixtures
plugins/
└── <plugin>/
└── test/ # Plugin-owned tests, named *.test.ts
```
Only files ending in `.test.ts` are run.
For example the tests for `packages/lib/src/link/link.ts` are in `tests/lib/link/link.test.ts`.
## Writing tests
Nest tests as `file > class > method > test name`, or `file > function > test name` for plain functions.
Name the imported instance `t` and the nested contexts `t1`, `t2`, `t3`.
```ts
import t from "tap";
import * as lib from "@clusterio/lib";
t.test("RoleMapping", async t1 => {
t1.test("add()", async t2 => {
t2.test("adds a role", async t3 => {
// ...
});
});
t1.test("remove()", async t2 => {
t2.test("removes an existing role", async t3 => {
// ...
});
});
});
```
- Use the real classes wherever practical.
- Mock single functions and methods with `t.intercept`, `t.capture` or `t.mockImport`, not whole classes.
- Mock external boundaries such as the network, timers and other nondeterministic sources.
- Each test creates the mutable state it needs.
No test may depend on another test having run or passed.
- Share immutable fixtures and expensive read-only resources at module scope.
- Mark known bugs with `{ todo: "reason" }` so they show up without failing the run.
Each test file runs in its own process, in parallel with the others.
Keep files independent of each other.
Parallel subtests (`t.jobs`) are for independent asynchronous work within one file.
Tests that need an exclusive resource such as a fixed port go in a directory marked with `serial` in `.taprc`.
### Common tests
`shared/` builds tests that apply to many classes.
`shared/json_serialisable.ts` tests the [JSON serialisable class pattern](../docs/devs/json-serialisable-classes.md): a value survives `JSON.stringify` and `fromJSON`, and the serialised form matches `jsonSchema`.
Samples are generated from the schema, with and without optional properties.
`lib/data/json_serialisable.test.ts` runs it for every serialisable class exported by `@clusterio/lib`, so new data classes and messages are covered without adding a test.
Schemas the generator cannot satisfy, such as strings that must parse as a mod dependency, get hand written samples in that file.
## Running
| Command | Runs |
| --- | --- |
| `pnpm test:tap` | Every TAP test in one shared worker pool, as CI does. |
| `pnpm test:unit` | `tests/<package>/`. |
| `pnpm test:integration` | `tests/integrations/`. |
| `pnpm test:plugins` | `plugins/*/test/**/*.test.ts`. |
| `pnpm test:coverage` | Every TAP test with a text and HTML coverage report in `.tap/report/`. |
| `pnpm test:typecheck` | `tsc` over the tests. |
These scripts build first.
For a single package or file, build and call tap directly:
```sh
pnpm build
pnpm exec tap --disable-coverage tests/lib
pnpm exec tap --disable-coverage tests/lib/link/link.test.ts
```
`--grep` selects subtests by name, one pattern per level.
`--jobs=<n>` sets the number of test files run at once, which defaults to the number of CPUs.
Run tap from the root rather than through `pnpm -r`, which would run a worker pool per package.
`pnpm install` runs `tap build` to apply the plugin list in `.taprc`.
Run it again after changing that list.
CI runs this suite in `.github/workflows/tap.yml` on the latest Node.js and Factorio only.
Coverage reported to Codecov still comes from the Mocha suite.
File diff suppressed because it is too large. Load diff
+48
View File
@@ -0,0 +1,48 @@
import t from "tap";
import * as lib from "@clusterio/lib";
import {
type KnownSamples, jsonSamples, jsonSerialisableClasses, testJsonSerialisable,
} from "../../shared/json_serialisable.ts";
// Every JSON serialisable class exported by lib gets the common tests, so new
// classes are covered without adding anything here. Schemas the sample
// generator cannot satisfy get hand written samples, minimal first.
const known: KnownSamples = new Map<object, unknown[]>([
[lib.ModInfo.jsonSchema, [
{ name: "a", version: "1.0.0", title: "A", author: "b" },
{
name: "a", version: "1.0.0", title: "A", author: "b", contact: "c", homepage: "h", description: "d",
factorio_version: "2.0", dependencies: ["base >= 2.0", "? b", "! c", "(?) d", "~ e"],
size: 1, mtime_ms: 2, sha1: "s", updated_at_ms: 3, is_deleted: true,
},
]],
[lib.ModDependency.jsonSchema, ["base", "? a > 1.0.0"]],
[lib.ModVersionEquality.jsonSchema, ["= 1.0.0", ">= 2.1.0"]],
[lib.SubscriptionRequest.jsonSchema, [
["InstanceDetailsUpdatesEvent", "subscribe", 0],
["InstanceDetailsUpdatesEvent", "replace", 10, ["a", "b"]],
]],
]);
// Classes whose fromJSON needs more than the JSON value, they have their own tests.
const excluded = new Set([
"Config",
"ControllerConfig",
"CtlConfig",
"HostConfig",
"InstanceConfig",
]);
// Known failures, reported as todo until fixed.
const todo = new Map([
["InstanceDetailsChangedEvent", "has no toJSON, so it serialises as { details } instead of InstanceDetails"],
]);
for (const [name, Class] of jsonSerialisableClasses(lib)) {
if (excluded.has(name)) {
continue;
}
t.test(name, { todo: todo.get(name) }, async t1 => {
testJsonSerialisable(t1, Class, jsonSamples(Class, known));
});
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+192
View File
@@ -0,0 +1,192 @@
import type { Test } from "tap";
import { compile } from "@clusterio/lib";
/** A class following the JSON serialisable data class pattern, see docs/devs/json-serialisable-classes.md */
export interface JsonSerialisableClass {
name: string;
jsonSchema: object;
fromJSON(json: any): any;
}
export function isJsonSerialisableClass(value: unknown): value is JsonSerialisableClass {
return typeof value === "function"
&& typeof (value as any).jsonSchema === "object"
&& typeof (value as any).fromJSON === "function";
}
/**
* Collect the JSON serialisable classes exported by a module, including the
* Response classes of messages that are not exported on their own.
*
* @param module - Module namespace to search.
* @returns Map of display name to class.
*/
export function jsonSerialisableClasses(module: Record<string, unknown>) {
const classes = new Map<string, JsonSerialisableClass>();
const exported = new Set(Object.values(module));
for (const [name, value] of Object.entries(module)) {
if (isJsonSerialisableClass(value)) {
classes.set(name, value);
}
const response = (value as any)?.Response;
if (typeof value === "function" && isJsonSerialisableClass(response) && !exported.has(response)) {
classes.set(`${name}.Response`, response);
}
}
return classes;
}
/** Hand written JSON samples keyed by the schema object they match, minimal first and full last */
export type KnownSamples = Map<object, unknown[]>;
// Strings tried in order for a schema with a pattern
const patternCandidates = ["a", "1", "1.0", "1.0.0", "a-b", "a.b", "a_b", "A", "ffffff", "0.0.0"];
/**
* Create a JSON value matching a JSON schema.
*
* Only required properties are created unless `full` is set, in which case
* every declared property is created. Throws for schemas it cannot satisfy,
* these need a hand written sample in `known` instead.
*
* @param schema - JSON schema to create a value for.
* @param full - Include optional properties.
* @param known - Samples to use for specific schema objects, wherever they appear.
* @returns Value matching the schema.
*/
export function sampleFromSchema(schema: any, full = false, known?: KnownSamples): unknown {
if (known?.has(schema)) {
const samples = known.get(schema)!;
return structuredClone(full ? samples.at(-1) : samples[0]);
}
if (schema === true || schema === undefined || Object.keys(schema).length === 0) {
return null;
}
if ("const" in schema) {
return schema.const;
}
if (schema.enum) {
return schema.enum[0];
}
if ("default" in schema) {
return structuredClone(schema.default);
}
for (const key of ["anyOf", "oneOf"]) {
if (schema[key]) {
// Prefer a branch that is not null so the sample says more
const branch = schema[key].find((s: any) => s.type !== "null") ?? schema[key][0];
return sampleFromSchema(branch, full, known);
}
}
if (schema.allOf) {
return Object.assign({}, ...schema.allOf.map((s: any) => sampleFromSchema(s, full, known)));
}
const type = Array.isArray(schema.type) ? schema.type.find((t: string) => t !== "null") : schema.type;
switch (type) {
case "null":
return null;
case "boolean":
return false;
case "integer":
case "number":
return schema.minimum ?? (schema.exclusiveMinimum !== undefined ? schema.exclusiveMinimum + 1 : 0);
case "string":
return sampleString(schema);
case "array":
return sampleArray(schema, full, known);
case "object":
return sampleObject(schema, full, known);
default:
throw new Error(`Unsupported schema ${JSON.stringify(schema)}`);
}
}
function sampleString(schema: any) {
if (schema.pattern) {
const pattern = new RegExp(schema.pattern, "u");
const match = patternCandidates.find(c => pattern.test(c));
if (match === undefined) {
throw new Error(`No sample string matches pattern ${schema.pattern}`);
}
return match;
}
if (schema.format) {
throw new Error(`No sample string for format ${schema.format}`);
}
return "a".repeat(schema.minLength ?? 0);
}
function sampleArray(schema: any, full: boolean, known?: KnownSamples) {
if (Array.isArray(schema.items) || schema.prefixItems) {
const items: any[] = schema.prefixItems ?? schema.items;
const count = full ? items.length : schema.minItems ?? 0;
return items.slice(0, count).map(item => sampleFromSchema(item, full, known));
}
const count = Math.max(schema.minItems ?? 0, full ? 1 : 0);
return Array.from({ length: count }, () => sampleFromSchema(schema.items, full, known));
}
function sampleObject(schema: any, full: boolean, known?: KnownSamples) {
const required = new Set<string>(schema.required ?? []);
const result: Record<string, unknown> = {};
for (const [key, property] of Object.entries(schema.properties ?? {})) {
if (full || required.has(key)) {
result[key] = sampleFromSchema(property, full, known);
}
}
return result;
}
/**
* Minimal and full JSON samples for a class generated from its schema.
*
* @param Class - Class to create samples for.
* @param known - Hand written samples for schemas that cannot be generated.
* @returns Named JSON samples.
*/
export function jsonSamples(Class: JsonSerialisableClass, known?: KnownSamples) {
return [
["minimal sample", sampleFromSchema(Class.jsonSchema, false, known)],
["full sample", sampleFromSchema(Class.jsonSchema, true, known)],
] as const;
}
/**
* Common tests for a JSON serialisable class.
*
* Each sample is deserialised with fromJSON, serialised with JSON.stringify,
* then checked against the class schema and deserialised again.
*
* @param t - Test to add the fromJSON() and toJSON() subtests to.
* @param Class - Class under test.
* @param samples - Named JSON samples, see {@link jsonSamples}.
*/
export function testJsonSerialisable(
t: Test,
Class: JsonSerialisableClass,
samples: ReadonlyArray<readonly [string, unknown]>,
) {
const validate = compile(Class.jsonSchema as any);
const serialise = (value: unknown) => JSON.parse(JSON.stringify(value));
t.test("toJSON()", async t1 => {
for (const [name, json] of samples) {
t1.test(`matches jsonSchema for ${name}`, async t2 => {
const serialised = serialise(Class.fromJSON(structuredClone(json)));
t2.ok(validate(serialised), "serialised value is valid", { errors: validate.errors, serialised });
});
}
});
t.test("fromJSON()", async t1 => {
for (const [name, json] of samples) {
t1.test(`round trips ${name}`, async t2 => {
const original = Class.fromJSON(structuredClone(json));
const reconstructed = Class.fromJSON(serialise(original));
t2.strictSame(reconstructed, original);
t2.same(serialise(reconstructed), serialise(original));
});
}
});
}
+72
View File
@@ -0,0 +1,72 @@
import events from "node:events";
import * as lib from "@clusterio/lib";
export const addr = lib.Address.fromShorthand;
/**
* Link on one end of a VirtualConnector pair with nothing but a recorder on
* the other end.
*
* @param src - Address of the link.
* @param dst - Address of the other end.
* @returns the link, its connector, the peer connector and the messages
* that arrived at the peer.
*/
export function recordedLink(src: lib.Address, dst: lib.Address) {
const [connector, peer] = lib.VirtualConnector.makePair(src, dst);
const link = new lib.Link(connector);
const sent: any[] = [];
peer.on("message", message => { sent.push(message); });
return { link, connector, peer, sent };
}
/** VirtualConnector which sends messages through JSON like a WebSocket would */
export class JsonVirtualConnector extends lib.VirtualConnector {
send(message: lib.Message) {
this.other.emit("message", lib.Message.fromJSON(JSON.parse(JSON.stringify(message))));
}
}
/**
* Two links joined by a JsonVirtualConnector pair.
*
* @param src - Address of the first link.
* @param dst - Address of the second link.
* @returns both links.
*/
export function linkPair(src: lib.Address, dst: lib.Address) {
const [connector, peerConnector] = JsonVirtualConnector.makePair(src, dst);
return { link: new lib.Link(connector), peer: new lib.Link(peerConnector) };
}
/**
* WebSocket connector with the socket replaced by an array of sent text.
* Starts out closed, set `_state` to "connected" to give it a session.
*/
export class TestWebSocketConnector extends lib.WebSocketBaseConnector {
sentText: string[] = [];
constructor(src: lib.Address, dst: lib.Address) {
super(src, dst);
this._socket = { send: (text: string) => { this.sentText.push(text); } } as any;
}
setClosing() {
this._closing = true;
}
async close() {
this._state = "closed";
}
}
/** Resolves with the next message to arrive at a connector */
export async function nextMessage(connector: lib.BaseConnector): Promise<any> {
const [message] = await events.once(connector as events.EventEmitter, "message");
return message;
}
/** Resolves once pending promise callbacks and I/O callbacks have run */
export function settle() {
return new Promise(resolve => { setImmediate(resolve); });
}
+15
View File
@@ -0,0 +1,15 @@
// Type checks the TAP tests, which Node.js runs directly by stripping the types.
{
"extends": "../tsconfig.node.json",
"compilerOptions": {
"composite": false,
"declaration": false,
"declarationMap": false,
"incremental": false,
"noEmit": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
},
"include": ["./**/*.ts", "../plugins/*/test/**/*.test.ts"],
}