Skip to content

Writing and running tests

Audience: editors and language authors · ~10 min read · Prerequisites: Models, roots and imports

The Tests pane after a successful run, with numbered controls

What it is

A test is a small statement about your model that must be true, such as "this check fires" or "this function returns 15". Tests are written in the model itself, in a test suite (a group of named test cases, each holding assertions), usually in a root file of its own beside the code under test. The Tests pane runs every suite of the open model and lists what passed and failed. Which languages can hold tests depends on the installed test languages: the bundled Test Language (TestSuite, TestCase, Assert...) is available in every project, and the KernelF test language adds its own suite syntax.

When you'd use it

  • You want a safety net while you change a model.
  • You are writing a language and want to test its checks, types, generator output and editor behaviour.
  • You work through an exercise book (see below).

The quick way: Pin Current Behaviour

You do not have to create the tests root or learn the assertion kinds first:

  1. Run > Execute > Pin Current Behaviour as Test adds a case to the model's test suite asserting what the model does right now. If the model has no tests root yet it creates one (a second root named <model>_tests with one suite) and opens it; the same is available as Add test suite in the model's Explorer context menu. It needs a language that has a test language installed (Core and the languages built on it do). The case asserts assert no checks (or one assert checks per current check result) and assert generates with the current generated text. The case passes now and fails as soon as the behaviour changes, which makes it a safety net for changes you did not mean to make. Pin again later for a second case (current behaviour (2)).
  2. To write a suite yourself, import the test language into the model (Edit > Add Language Import…) and add a root node of its suite concept; there is no separate "Add Test Suite" menu entry.
  3. To pin one value instead of the whole model, put the cursor on an expression (for example the call gcd(48, 18)) and press Alt+Enter > Pin current value as test. The expression is evaluated the way a test run would (the model's other statements run first), and a case assert eval <expression> == <value> is added to the suite. Only numbers, text and true/false can be pinned; for anything else (a list, an error) a message says why.

After Run Tests, each assertion in the tests root is marked (green bar = passed, red bar and tint = failed), and a failed comparison shows Expected and Actual side by side in the Tests pane.

Writing a test (Test Language)

  1. Add a second root to the model (see Models, roots and imports), or open a sample that has one. The Decision table sample has decision-table.tests.model.py next to the code.
  2. In that root write a suite. In the text form it looks like this:
TestSuite("constraints showcase",
    TestCase("flags division by literal zero",
        AssertChecks("error", "Division by zero")),
    TestCase("sum 1..5 evaluates to 15",
        AssertEvaluatesTo(1 + 2 + 3 + 4 + 5, 15)))
  1. In the projectional editor, press Enter inside a suite to add things; a suite takes test cases, and a case takes assertions. Use the Add case and Add assertion intentions (Alt+Enter) when Enter does not offer one, then Ctrl+Space to pick the assertion kind.
  2. Run the tests (below). Assertions that analyse "the subject" use the model's first (primary) root; assertions that evaluate code run the model's other statements first, so a def in the code root can be called from a test.
Assertion Passes when
assert checks <severity>: <message> the checks report an issue of that severity with that message
assert no checks the checks report nothing
assert type <type> the inferred type of the subject equals the given text
assert generates <text> the generator produces exactly that text
assert eval <expr> == <expected> both evaluate to the same value (the expression can call functions defined in the model)
assert wait for <expr> every <m> ms, timeout <n> ms the expression becomes true before the timeout (for timers or other threads)
assert same structure <a> == <b> two model fragments are equal node by node (ids ignored); a failure names the first difference
assert keypress <key> in <before> generates <text> typing the key at the marked node (TestCaret) turns the fragment into that text
assert intention <name> in <before> generates <text> applying the named intention at the marked node gives that text

The keypress and intention assertions drive the real editor, so they test editing behaviour exactly as a user meets it. The Test Language sample (keypress-demo) shows them.

Running tests

To run the tests together with the checks and a generator dry run, use Run > Execute > Verify Model (Overview); its one-line verdict is also shown at the top of the Tests pane, and each verified model gets a ✓ / ○ / ✗ badge in the Explorer (○ = passed, but no tests yet).

  1. Choose Run > Execute > Run Tests (Ctrl/Cmd+K, R, T), click the flask icon in the top toolbar, or open View > Tool Windows > Bottom > Tests and click Run All Tests. (The Run menu appears only while a model tab is active.)
  2. The pane shows a badge (2 passed, or 1 failed / 3 total), then each suite and each assertion with its duration. A failed assertion shows the reason underneath (cut at 400 characters).
  3. Click an assertion to jump to it in the editor.
  4. Below the results a Coverage of the code under test bar shows how many expressions and branches the tests reached; the first 20 that never ran are listed. Click one to jump to it. See Mutation runs and coverage. Core programs have no such bar (their assertions run on Python); use Run with Coverage there.
  5. Export JUnit XML saves test-results.xml, the format CI systems read.

All roots of the active model are scanned, so a suite in a dedicated root runs against the model's primary root. Results belong to the document that was active when you pressed Run; switching tabs while the pane opens does not change which model is tested. Starting a project change clears stale results.

Tests written in JavaScript

A test can also be a small JavaScript program that calls the workbench API: it can edit a copy of your model, run the checks, the program and the generator, and expect what comes back. Use it when a test needs more than the assertion kinds above, for example "after this edit the model still has no problems".

The tests live in a root of their own in the model, in the language JS Tests (jstest), next to the code they test. The code can be in any language: a model's roots may each have their own language (Models, roots and imports). The root is stored as plain JavaScript (calculator.tests.model.js), and you edit it in the projectional editor like any other root.

describe("Calculator model", () => {
  it("has no problems", async () => {
    expect(workbench.checks.run()).toHaveNoChecks();
  });
  it("prints the answer", async () => {
    expect(await workbench.run.run()).toPrint("42");
  });
  it("adds a statement in one undoable step", async () => {
    const stmt = workbench.model.of(workbench.surface.parse("bonus = result + 1\n")).roots()[0].children("stmts")[0];
    workbench.transaction(() => workbench.model.root().append("stmts", stmt));
    expect(workbench.model.root().children("stmts")).toHaveLength(4);
  });
});

The JS tests sample (File > Load Sample…) is a runnable version of this.

What a test sees. workbench is the workbench API, working on the model's other roots (the code under test). Each it gets its own copy, so a test can edit freely and the next one starts from the original. it("name", { shared: true }, fn) runs on one copy that all shared tests use and that is restored after each of them (faster when the setup is expensive). beforeEach and afterEach run around every test of their suite, outer to inner; afterEach also runs after a failure. it("name", { timeout: 5000 }, fn) sets the time limit (60 seconds otherwise). Top-level statements and the body of a describe run once, to collect the tests.

The editor. workbench.editor works in a test too: the first time a test touches it, a private editor is opened on that test's copy of the code (never on your open tab, and your cursor stays where it is), and from then on workbench.model, workbench.transaction and undo go through it, so workbench.editor.addChild, setConcept, wrap, undo and redo behave as they do for you, with the editor's own rules and undo history. You can also drive it the way a person does: await workbench.editor.select(nodeId) puts the caret on a cell (select(callId, 0) for a value a call holds itself, such as the 21 in double(21); an unfilled __Empty__ node selects the empty cell), await workbench.editor.key("Enter") or key("z", { ctrl: true }) presses a key, await workbench.editor.type("42", { replace: true }) types into the cell (and commits it), and await workbench.editor.complete("whi") opens completion, returns the names it offers and await workbench.editor.choose("while") picks one. The keys go to the editor's own key handler, not through the page, so they never reach the IDE's shortcuts. They are synthetic: a behaviour that depends on a trusted browser event still needs a check in the real editor. On the command line the private editor needs the editor's renderer, which only the IDE and the test runner have, so key tests are for the IDE and npm test.

Values and hand-built nodes. workbench.run.format(value) prints a run value the way the language's own grammar writes it (a KernelF list as list(1, 2)), so a test compares a result with text instead of carrying its own printer. workbench.model.node(head, ...children) builds a node by head (a real concept instance, not a bare object) to print, wrap with workbench.model.of or put into a tree. A test has no file system, debugger or shell.

expect. The usual matchers (toBe, toEqual, toBeTruthy, toContain, toHaveLength, toBeGreaterThan, toMatch, toMatchObject, toThrow, toBeInstanceOf, ... with .not, .resolves and .rejects) and some for the workbench's results: toHaveNoChecks() and toHaveCheck(text) (for workbench.checks.run()), toGenerate(text) (for workbench.generator.text()), toRunTo(value) and toPrint(...lines) (for workbench.run.run()), toHaveKind(head) (for a node). Snapshots, mocks and fake timers are not available.

Run just one. On a describe or an it, Alt+Enter (or the lightbulb) offers Run just this suite or test, which runs only that part against the open model and shows the verdict in the status line (asking first if the JavaScript was never approved).

A failing test shows the matcher's message with both sides of a comparison, and clicking it in the Tests pane jumps to the expect(...) call (or the statement that threw).

Trust. A JS test root is JavaScript that can call the whole workbench API, so it can edit your models and files. The Tests pane asks before it runs a root the first time and again after you change it. Verify never asks: it runs only roots you have approved before, and reports the others as not run. On the command line strukts test runs the tests of a bundled sample, and those of any other folder only with --trust-project-code. Nothing sandboxes the code.

Add one. Import JS Tests into the model (Language > Import), then Add root node in the Explorer and choose that language: the new root is a JavaScript file in which describe, it, beforeEach and afterEach are available from completion. Run > Execute > Pin Current Behaviour as Test adds a case that asserts what the model does now (no check issues, or the current ones, and the generated text) when the open root is a JS test root.

Good to know. Write const/let for your own variables (the code runs in strict mode). JS Tests imports the JavaScript language, so switch, loops with labels, a?.b, classes, generators, destructuring and the rest are real structure you can edit, and a function () {} callback stays a function (it is not rewritten to an arrow). Several declarators in one statement (const a = 1, b = 2;) are kept as one declaration each, { a, b } as { "a": a, "b": b }, and 0xff, 1e3 and 1_000 keep their value. Anything the language has no concept for is kept as its own source text in a raw cell, saved and run as written. (a || b).map(f) keeps its parentheses.

Exercise books

The Exercises language (lang-exercises) uses the same pane: each exercise is one suite, each task a case and each requirement an assertion, checked against your own work in another root or model. An unmet requirement fails with its hint. The Exercises Walkthrough sample shows the layout.

Running tests without the IDE

strukts test runs the same suites headlessly and can write the same JUnit file; JS tests need --trust-project-code (see above). See The strukts CLI.

Every control

# Button/Option What it does Shortcut Gotcha
1 Run All Tests (pane) Runs every suite of the active model — Disabled while running; reads "Running…"
2 Mutation test (pane) Changes the code under test one spot at a time and checks tests notice — Only KernelF tests support it (the button is greyed out, with a tooltip, otherwise); see Mutation runs and coverage
3 Badge (N passed / N failed / M total) Summary of the last run — Shows Cancelled beside it if you stopped the run
4 Export JUnit XML (pane) Saves the results as test-results.xml — Hidden after a run that ended in an error
5 Cancel (pane) Stops a running test or mutation run — Visible only while running; counts reflect what ran so far
6 Coverage block Shows reached/total expressions and branches — Click a ○ (never evaluated) or ◐ (branch never ran) line to jump there
7 Run > Execute > Run Tests Opens the Tests pane and runs Ctrl/Cmd+K, R, T Only enabled when the model contains a runnable suite
8 Toolbar flask icon Same as Run Tests —
9 View > Tool Windows > Tests Shows the pane — Under the Bottom group
10 An assertion row Jumps to the assertion Click