Testing scripts: kscript test

Introduction

Tests let you change code without worrying that you broke something. KScript has a test framework built in, so there is nothing to install. Tests are KScript files whose names end in .test.kscript or .test.ks.xml, usually kept in a tests/ folder, and kscript test runs them.

Here is a test file for a slugify function:

// tests/strings.test.kscript
kscript {
  import "../lib/strings.kscript"

  describe(name: 'slugify') {
    test(name: 'lower-cases and joins words with dashes') {
      expect(@slugify('Hello World'), equals: 'hello-world')
    }

    $cases = [
      { text: 'One', slug: 'one' },
      { text: 'Two Words', slug: 'two-words' },
    ]
    for case in $cases {
      test(name: "slug of '{$case.text}'") {
        expect(@slugify($case.text), equals: $case.slug)
      }
    }
  }
}

Run kscript test, and each test’s result is listed, with what went wrong for a failure:

$ kscript test
tests/strings.test.kscript
  ✓ slugify › lower-cases and joins words with dashes (1 ms)
  ✓ slugify › slug of 'One' (0 ms)
  ✗ slugify › slug of 'Two Words' (0 ms)
      Expected @slugify($case.text) to equal 'two-words', but it was 'two words'.
      at tests/strings.test.kscript:14:7

Tests: 1 failed, 2 passed, 3 total
Files: 1 failed, 1 total
Time:  0.08s

The exit code is 0 when every test passed. It is 1 when a test failed, a test file couldn’t run, no tests matched, or the folder has no test files. It is 2 when the command line or kscript.json is wrong, such as an unknown option or a path that isn’t there. So kscript test can gate a CI job. Exit codes are the same for every command.

Writing tests

Test files and folders

A test file is a normal script named name.test.kscript or name.test.ks.xml. The examples here use the .kscript format: switch them to XML to see <describe>, <test> and <expect>. Test files may use KScript.Test without an import, and so may the editor.

kscript make test checkout creates tests/checkout.test.kscript in the project (--syntax xml for .test.ks.xml). kscript make project starts new projects with the rules of a small to-do app in lib/, a script, and tests for both.

How a test file runs

Each file runs in its own interpreter, in two steps:

  1. The file’s top-level code runs once: its imports, variables, fn functions and describe blocks. Each test it reaches is noted, not run.
  2. Each test then runs on its own, in a new scope inside the one it was written in. It sees the file’s variables and functions, and the variables of the describe blocks around it.

A test passes if its body finishes. It fails at the first check that doesn’t hold, or at any error, and the remaining tests still run. Variables a test declares belong to that test. Variables declared outside the tests are shared, so reset them in before_each.

What a test prints with echo is kept, and shown under the test only when it fails.

Groups and hooks

describe(name: …) { } groups tests. Its name goes in front of each test’s name (a shopping cart › adds items), and its hooks apply to every test inside. Groups may nest.

before_each { } runs before every test in its file or describe, in the test’s own scope, and outer hooks run first. after_each { } runs after every test, even one that failed, and inner hooks run first. Use it to delete files a test made:

describe(name: 'a shopping cart') {
  $cart = []
  before_each {
    $cart = ['apple']
  }

  test(name: 'starts with one item') {
    expect($cart, count: 1)
  }

  test(name: 'adds items') {
    $cart = $cart->push('pear')
    expect($cart, equals: ['apple', 'pear'])
  }
}

Tests from data

A test inside a for loop makes one test per item. The loop’s variables may be used in the test’s name and its body, as in the slugify example above. In XML, write <for each="case" at="i" in="$cases"><test name="…">.

Skipping, focusing and timeouts

skip on a test or describe doesn’t run it, and it is reported as skipped, with skip: 'reason' giving the reason. While you work on something, only runs just the tests marked only in that file. timeout: 30s fails a test that runs longer than 30 seconds:

test(name: 'imports a large file', timeout: 30s) {
  expect([1, 2, 3]->sum(), equals: 6)
}

test(name: 'sends the weekly email', skip: 'the mail server is down') {
  expect(true, equals: true)
}

Checks

expect takes the value to check first, without a name, and one check: expect($total, equals: 3). Every check’s value is an expression, so text needs quotes: equals: 'hello'.

Check Passes when
expect($x, equals: 5) The values are equal, as == compares them: '5' equals 5. Lists and maps are compared item by item, and a failure says where they differ.
not_equals: 5 They aren’t equal.
same: 5 They are strictly equal (===): same type and value.
contains: 'Joan' A list has the item, text has the text, or a map has the key.
not_contains: 'Joan' The opposite.
matches: '^\d+$' Text matches the regular expression.
type: list The value is a string, number, bool, list, map, date, fn or null.
count: 3 A list or map has that many items, or text has that many characters.
count_at_most: 4 A list or map has at most that many items, or text has at most that many characters. With @queries(), it checks how many queries a test sent.
close_to: 0.3 A number is within within: of this (0.000000001 unless given): expect(0.1 + 0.2, close_to: 0.3), expect($average, close_to: 4.33, within: 0.01). Use it for money, statistics and other maths that floats can’t hold exactly.
has: { status: 'paid' } A map has these keys with these values, and may have others. A nested map is checked the same way. For a list, every item must have them.

message: … on any check replaces the usual message.

has: suits an API answer, where a test cares about a few fields:

$order = { id: 7, status: 'paid', total: 30, customer: { name: 'Ann', email: 'ann@example.com' } }
expect($order, has: { status: 'paid', customer: { name: 'Ann' } })
expect([{ id: 1, active: true }, { id: 2, active: true }], has: { active: true })

@assert(condition, message?) checks a condition, on a line of its own or inside an expression such as a lambda. When a comparison fails it shows the value of each side:

Expected $order.total == 30 to be true.
  $order.total is 25

@fail(message?) fails the test straight away.

Errors

expect_error { } fails unless its body stops with an error. type checks the error type (an error type that extends it counts too), contains checks the message, and as keeps the error (type, message, line, file, status, cause and its fields) for more checks:

expect_error(type: Validation, contains: 'positive', as: err) {
  @set_age(-1)
}
expect($err.line, type: number)

For one expression, throws is shorter: it passes when working out the value stops with an error of that type.

error PersonNotFound extends NotFound

fn find_person(id: int) {
  throw PersonNotFound "No person with id {$id}"
}

expect(@find_person(99), throws: PersonNotFound)
expect('nope'->convert(from: json), throws: Format) // Json extends Format

A failed check inside the body is still reported as a failure, not taken as the expected error.

Output and input

capture(into: out) { } runs its body and puts what it printed in $out (lines end in \n, without the last one). input gives prompts such as input their answers, as text or a list of lines:

capture(into: out, input: ['Joan', 'yes']) {
  @sign_up()
}
expect($out, contains: 'Welcome, Joan')

Whole scripts

@run_script(path, { args, input }) runs another script on its own, as kscript path args… would, and returns { output, code, error }: what it printed, its exit code (3 when it stopped with an error), and the error or null. The path is relative to the test file. The script gets the project’s packages, but not KScript.Test.

test(name: 'hello.kscript greets the name it is given') {
  $run = @run_script('../scripts/hello.kscript', options: { args: ['Ellie'] })
  expect($run.code, equals: 0)
  expect($run.output, equals: 'Hello, Ellie!')
}

Use it for scripts that do their work at the top level or call exit. A test that calls exit itself fails.

@check_script(path) checks another script as kscript check does, without running it, and returns its problems in the order they appear: a list of { line, column, severity, code, message }. Use it to say which mistakes the editor and kscript check catch. Keep scripts with mistakes made on purpose in a folder that lint.exclude leaves out (see Projects), so kscript check on the project stays clean. @check_script() checks the file anyway:

test(name: 'a map is not a flag') {
  $problems = @check_script('mistakes/flags.kscript')
  expect($problems, count: 1)       // one mistake gets one report
  expect($problems[0].line, equals: 2)
  expect($problems[0].message, contains: 'needs true or false, but this is a map')
}

Pages

@visit(path) (from KScript.Web) renders a page of the project as a browser gets it, the way kscript serve answers it: the project’s routes first (a view: route, or a controller that returns @view(...), with their middleware), then the file pages under serve.root in the nearest kscript.json. Its live handlers run on the server as they would in a browser, so a test can click through a page:

  • ->click(text) runs the on-click handler of the button or link with that text (or aria-label or title).
  • ->change(text) runs the on-change handler of the input whose <label> has that text, such as a checkbox.
  • ->fill(field, value) types into the input bound to that field, and ->submit(text?) runs a form’s on-submit.
  • .text is the words on the page, .html its HTML, and ->classes(text) the classes of the element whose own text that is.

Each of these returns the page, so they chain. A page that isn’t there is a NotFound error. Events a handler sends with @emit_event() (or emit:) reach the other blocks’ on-event listeners, as they do in the browser: the block named by target:, or every block that listens.

A visit to a route keeps the cookies the app sets (a guest cookie, the session) for its clicks, and follows redirects as a browser does: .path is where it ended up. @acting_as() signs the visit in, as it does for @api(/...), and @visit(path, { headers: { Cookie: 'guest=abc' } }) sends headers of its own (bearer: sends a token):

import KScript.Web
import KScript.Auth

test(name: 'a guest is sent to sign in') {
  expect(@visit('/account').path, equals: '/login')
}

test(name: 'the account page makes a token') {
  @acting_as(@register('ada@example.test', 'correct-horse-battery-9'))
  $page = @visit('/account')->fill('name', 'laptop')->submit('Make a token')
  expect($page.text, contains: 'Your new token is')
}
import KScript.Web

test(name: 'adding a task clears the box') {
  $page = @visit('/tasks')->fill('draft', 'Write the docs')->submit()
  expect($page.text, contains: 'Write the docs')
  expect($page->classes('Write the docs'), not_contains: 'done')
}

samples/task-board has a page whose buttons are all handler shorthands, with a test for each.

Running tests

kscript test with no paths runs every test file in the current project: the folder of the nearest kscript.json, or the current folder if there isn’t one. Folders whose names start with ., and node_modules, bin and obj, are skipped. You may also name folders and files, or pick tests by name:

kscript test                              # the project's tests a change can affect
kscript test --all                        # every test in the project
kscript test --failed                     # only the tests that failed last time
kscript test --changed                    # the tests your uncommitted changes can affect
kscript test --changed master             # the tests this branch's changes can affect
kscript test --watch                      # run the affected tests each time you save
kscript test tests/cart tests/api.test.kscript   # a folder and a file
kscript test --filter "cart › adds"       # only tests whose full name contains the text (any case)
kscript test --timeout 30                 # seconds per test (0: no limit)
kscript test --junit test-results.xml     # also write a JUnit XML report

kscript tests/cart.test.kscript runs one file too.

Colours are used when the output is a terminal; set NO_COLOR to turn them off or FORCE_COLOR to keep them. Ctrl+C stops the run after the current test.

--junit writes the results in the JUnit XML format that GitHub Actions reporters, GitLab, Jenkins and Azure Pipelines can show. A failed check is a <failure>, another error is an <error>, and a file that couldn’t run is reported as an <error> on a test named (load).

Running only what changed

A big project has a lot of tests, and most changes affect only a few of them. So in a project, kscript test runs just the tests that a change since the last run can affect. Change a model’s method, and only the tests that called that method run again; change a service, and only the tests that went through it run.

kscript test        # first run: every test, and kscript notes what each one reached
# edit lib/billing.kscript's total()
kscript test        # runs the 3 tests that called total(), directly or through other code
   PASS  tests/checkout.test.kscript
  ✓ charges the total (12 ms)
  ✓ adds tax (4 ms)
  ✓ applies a discount (5 ms)

  Tests:    3 passed, 241 unchanged since the last run, 244 total

While each test runs, kscript notes what it reaches: every function and method it calls, every type, model, enum, error and job it uses, every script it loads and every file read for it (pages, config, test data). Each of those has a fingerprint of its own text, kept in .kscript/cache/tests.json (the folder ignores itself, so git never sees it). A test runs again when:

  • it is new, or its own block changed;
  • it failed last time (it keeps running until it passes);
  • a function, method, type or other declaration it reached changed;
  • a script it loaded changed outside its declarations (its imports, constants or top-level code), or a file read for it changed.
  • it used the test database and a migration changed (or, in a project with no migrations, a model the database is made from).

Because it’s what each test actually ran that counts, a test file can import half the project and a test still only depends on the code it went through.

Every test runs when there’s no record of a run yet, when kscript itself changed, when kscript.json or a .env file changed, and when a new script appears (it may be picked up by convention, such as an extension or a route file). The first line of the output says why.

Some runs always run everything they name, and still update the record:

  • kscript test --all;
  • naming files (kscript test tests/cart.test.kscript) or using --filter;
  • CI, where the CI variable is set (GitHub Actions and most CI services set it).

kscript test --failed runs only the tests that failed in the last run.

Testing a git diff

--changed asks git what changed instead of comparing with the last run. On its own it takes the changes you haven’t committed yet; with a base, such as a branch, a tag or a commit, it takes everything since then, committed or not:

kscript test --changed                    # tests your uncommitted changes can affect
kscript test --changed master             # tests this branch can affect, before you open a pull request
kscript test --changed HEAD~3             # tests the last three commits can affect

kscript compares each changed file as it was at the base with the file now, declaration by declaration, and runs the tests that reached a part that differs, along with new tests and tests the diff changed. It still needs a record of an earlier run to know what each test reaches; without one, it runs every test.

Watching

kscript test --watch runs the tests, then keeps watching the project. Each time you save, it runs only the tests that reach what you changed. Save a file no test reaches, such as a README, and nothing runs. At a terminal each run replaces the last one on screen, so the results you see are always the latest; when the output goes to a file or a pipe, or with --no-ansi, each run is added below the last. Press Ctrl+C to stop.

kscript test --watch                      # run the affected tests each time you save

Settings in kscript.json

{
  "packages": ["KScript.IO"],            // imported by every script, including tests
  "test": {
    "include": ["tests/**/*.test.kscript"],  // default: **/*.test.kscript and **/*.test.ks.xml
    "exclude": ["tests/slow"],              // default: _templates, node_modules, .git
    "timeout": 10,                          // seconds per test; 0 for no limit (default 10)
    "packages": ["KScript.Terminal"],       // imported by test files only
    "env": "test",                          // the environment tests run in (KSCRIPT_ENV)
    "database": "memory"                    // KScript.Data: a database in memory per test file, or config
  }
}

timeout: … on a test wins over --timeout, which wins over test.timeout.

test.env is the environment the tests run in, so kscript.test.json is laid over kscript.json’s settings (see Settings). The API and fullstack project templates use it to give tests an in-memory database.

kscript test --env staging and a KSCRIPT_ENV that is already set win over test.env.

Tests that use KScript.Data get a database of their own in memory whatever the config says, unless test.database is config. Each test’s changes are undone when it ends. This includes users backed by a model in http.auth.users. A route a test calls with @api() uses the same database, in the test’s transaction: the route sees the records the test made, the test sees what the route saved, and both are undone together.

Each test file also gets temporary app folders for file-backed auth, including configured http.auth.folder stores, and for @storage(). Commands and local @api() calls share those folders within the file. The runner removes them when the file finishes, including on failure. Use a fixture inside the test file or a setup hook when tests need seeded users or files.

Testing an API

@api(/api/notes) sends a request to the project’s own routes without starting a server (see Calling your own API), so a test checks what a client would get:

import KScript.Net

test(name: 'a note is saved') {
  $added = @api(/api/notes, post: { title: 'Ship it' })
  expect($added.status, equals: 201)
  expect(@api(/api/notes/$added->convert(from: json).id)->convert(from: json).title, equals: 'Ship it')
}

Faking a language model

Code that asks Claude through @llm, llm or $chat->ask() can be tested without a key or the network. @fake_llm(replies) answers every question for the rest of the run, and keeps what was asked. Give it a list of answers, used in order, or a function that is given each prompt. A map answers a question asked with a schema:

import KScript.AI

fn triage(report: string) => @llm("Triage this report: { $report }", schema: { category: 'bug|feature|question' })

test(name: 'a crash report is a bug') {
  $fake = @fake_llm([{ category: 'bug' }])
  expect(@triage('The app crashes on start'), has: { category: 'bug' })
  expect($fake->prompts(), equals: ['Triage this report: The app crashes on start'])
}

test(name: 'the reply can depend on the prompt') {
  @fake_llm(fn(prompt) => $prompt->contains('French') ? 'Bonjour' : 'Hello')
  expect(@llm('Say hello in French'), equals: 'Bonjour')
}

$fake->count() says how many times the model was asked. When a list runs out, the next question fails with the prompt that had no answer.

Testing who may do what

@acting_as() from KScript.Auth sets who @user(), @can() and @authorize() ask about, until the test ends. Pass null to act as a guest. Routes the test calls with @api(/...) see the same user, including routes behind auth, auth:session or auth:token middleware, so a signed-in route needs no token in a test:

import KScript.Auth
import KScript.Net

test(name: 'the dashboard greets me') {
  @acting_as(@register('ada@example.test', 'correct-horse-battery-9'))
  expect(@api(/dashboard).status, equals: 200)
}

To test cookie-keyed behaviour, such as a guest’s board or a remembered preference, send the cookie yourself: @api(/, options: { headers: { Cookie: 'sb_guest=0f8f' } }). The response’s .cookies shows the cookies it set.

import KScript.Auth
import KScript.Data
import "../models/post.kscript"

test(name: 'only the author may update a post') {
  $post = Post->create(title: 'Mine', author_id: 1)

  @acting_as({ id: 1 })
  expect(@can(update, $post), equals: true)

  @acting_as({ id: 2 })
  expect(@can(update, $post), equals: false)
}

Learning from the language tests

KScript’s own repository tests the language with test scripts that are also good examples. Run kscript test samples/scripts/tests/language to run all of them, or pass one file. They also appear in VS Code’s Test Explorer, and CI compares the tests the language server finds with the interpreter’s results. Browse all language test scripts

What to try Runnable examples
Follow argument binding, recursive calls, and variable scope Named and piped calls · Recursion and scope
Step through an expression or a nested loop Operator precedence · Ranges and loop metadata
Give data a type and validate it at the boundary Custom literals · Records parsed from text · Joined types
Transform collections and text List transformations · Map updates · Regular expressions · Multiline strings
Use native values and add methods to a type Dates and durations · Money and rounding · Extension methods
Follow an error through nested handlers Guarded throws · Catch propagation

The repository tracks coverage gaps, combination targets and shared CLI, language-server and editor checks in the language test plan.

Run kscript test samples/scripts/tests/language/checkout-workflow.test.kscript to follow a mixed-currency invoice from line validation through discounts, settlement and refunds. The tests assert amounts in both currencies, recover the original error from a missing quote and check the penny retained after a partial refund. Checkout script

Run kscript test samples/scripts/tests/language/dispatch-workflow.test.kscript to follow incoming JSON through typed records, team-name normalization, priority sorting and queue selection. The same policy handles an unknown team by selecting a fallback or propagating the lookup error. Dispatch script

The refined string suite checks bare static keys, quoted interpolation, trimming and pattern failures. The license issuer suite exercises three validation guards and checks what the caller sees on success and failure.

In the editor

The language server treats *.test.kscript and *.test.ks.xml files as importing KScript.Test, so test, expect and the rest get completion, hover and checking, and the variables of a for loop round a test are known inside it. In VS Code, KScript: Run Tests runs kscript test for the workspace, and test files have a run button in the editor title bar.

expect, @assert and capture also work in ordinary scripts that import KScript.Test: a failed check stops the script with an Assertion error. test and describe only work under kscript test.

Comparing checker and editor diagnostics

Use kscript check path/to/script.kscript --output json for the diagnostic code, message, severity and source range on disk. In VS Code, Problems shows diagnostics for the current buffer, including unsaved edits. Set "kscript.trace.server": "verbose" to see the language server’s textDocument/publishDiagnostics notifications in the trace output. CLI lines and columns start at one. LSP lines and columns start at zero.

From the repository root, after building KScript in Release mode and installing the extension’s npm dependencies, run the same protocol checks as CI:

node editors/vscode/test/smoke.js KScriptApp/bin/Release/net8.0/KScript.dll

The test opens every language suite and helper. For the diagnostic fixtures, it checks the expected source spans, compares the server’s messages and severities to the CLI report, and verifies that a correction clears the old diagnostics before saving the file.

Edit this page on GitHub