KScript docs
EN

KScript.Test

Tests run by kscript test: <test>, <describe>, <expect>, <expect_error>, <capture> and @assert().

Import it at the top of a script:

<import package="KScript.Test" />
import KScript.Test

KScript.Test runs with kscript test, so its examples can't run inside the docs. Copy one into a .ks.xml file and run it with kscript.

ElementsStatements

#<after_each>after_each

Runs after every test in its file or <describe>, even when the test fails. Use it to tidy up files a test made.Runs after every test in its file or describe, even when the test fails. Use it to tidy up files a test made.

Holds statements.Holds statements in { }. Scripts only.

Example
<after_each>
  <set name="cart" value="[]" />
</after_each>
after_each {
  $cart = []
}

#<before_each>before_each

Runs before every test in its file or <describe>, in the test's own scope. Use it to reset shared variables with <set>.Runs before every test in its file or describe, in the test's own scope. Use it to reset shared variables with $name += value.

Holds statements.Holds statements in { }. Scripts only.

Example
<let name="cart" value="[]" />
<before_each>
  <set name="cart" value="[]" />
</before_each>
$cart = []
before_each {
  $cart = []
}

#<capture>capture

Runs its body and keeps what it prints in a variable instead of showing it. input gives it lines to read.

Holds statements.Holds statements in { }. Scripts only.

AttributeOptionValueDescription
into requireda new variable's nameThe variable that receives the output (line endings are \n, without the last one).
inputexpressionWhat <input> and other prompts read: text, or a list of lines.What input and other prompts read: text, or a list of lines.
Example
<capture into="out">
  <call fn="greet" args="'Joan'" />
</capture>
<expect value="$out" equals="'Hello, Joan!'" />
capture(into: out) {
  @greet('Joan')
}
expect($out, equals: 'Hello, Joan!')

#<describe>describe

A group of tests. Its name goes in front of each test's name, and its <before_each> and <after_each> apply to every test inside.A group of tests. Its name goes in front of each test's name, and its before_each and after_each apply to every test inside.

Holds statements.Holds statements in { }. Scripts only.

AttributeOptionValueDescription
name requireda string with { }What the group is about.
skipa string with { }Skip it: skip="true", or a reason such as skip="needs a network".
onlytrue or falsetrue runs only the tests marked only in this file, while you work on them.
Example
<describe name="lists">
  <test name="push adds to the end">
    <expect value="[1]->push(2)" equals="[1, 2]" />
  </test>
</describe>
describe(name: 'lists') {
  test(name: 'push adds to the end') {
    expect([1]->push(2), equals: [1, 2])
  }
}

#<expect>expect

Checks a value and fails the test if the check doesn't hold. Give the value and one check, such as equals="5".

Self-closing.A statement on its own. Scripts only.

AttributeOptionValueDescription
value requiredexpressionThe value to check.
equalsexpressionIt equals this (== for text and numbers, item by item for lists and maps).
not_equalsexpressionIt doesn't equal this.
sameexpressionIt is strictly equal (===): same type and value.
containsexpressionA list has this item, text has this text, or a map has this key.
not_containsexpressionA list doesn't have this item, text doesn't have this text, or a map doesn't have this key.
matchesexpressionText matches this regular expression, such as '^\d+$'.
type'string'|'number'|'bool'|'list'|'map'|'date'|'fn'|error|nullIts type is this.
countexpressionA list, map or text has this many items or characters.
count_at_mostexpressionA list, map or text has at most this many items or characters: expect(@queries(), count_at_most: 4).
close_toexpressionA number is within within of this, for maths that floats can't hold exactly: expect(0.1 + 0.2, close_to: 0.3).
withinexpressionHow far from close_to the number may be (0.000000001 by default): expect($average, close_to: 4.33, within: 0.01).
hasexpressionA map has these keys with these values, and may have others; for a list, every item does: expect($order, has: { status: 'paid' }). Nested maps are checked the same way.
throwsan error typeWorking out the value stops with an error of this type, or one that extends it: throws="NotFound".
messagea string with { }What to say when it fails, instead of the usual message.
Example
<expect value="2 + 3" equals="5" />
<expect value="$names" contains="'Joan'" />
<expect value="$id" matches="'^[a-z0-9-]+$'" />
<expect value="'nope'->convert(from: json)" throws="Json" />
expect(2 + 3, equals: 5)
expect($names, contains: 'Joan')
expect($id, matches: '^[a-z0-9-]+$')
expect('nope'->convert(from: json), throws: Json)

#<expect_error>expect_error

Fails the test unless its body stops with an error. type and contains check which error; as keeps it for more checks.

Holds statements.Holds statements in { }. Scripts only.

AttributeOptionValueDescription
typean error typeThe error type it should be (or a type that extends it), such as Validation, FileNotFound or an <error>.The error type it should be (or a type that extends it), such as Validation, FileNotFound or an error.
containsa string with { }Text the error message should contain.
asa new variable's nameA variable for the error (type, message, line, and the fields of <throw>), declared after the element.A variable for the error (type, message, line, and the fields of throw), declared after the element.
Example
<expect_error type="Validation" contains="positive">
  <call fn="set_age" args="-1" />
</expect_error>
expect_error(type: Validation, contains: 'positive') {
  @set_age(-1)
}

#<test>test

A test. Its body runs on its own when kscript test runs the file, and it passes if nothing in it fails. Inside a <for> loop it is one test per item.A test. Its body runs on its own when kscript test runs the file, and it passes if nothing in it fails. Inside a for item in list loop it is one test per item.

Holds statements.Holds statements in { }. Scripts only.

AttributeOptionValueDescription
name requireda string with { }What the test checks, shown in the results. In a <for> loop, { } can use the loop's variables.What the test checks, shown in the results. In a for item in list loop, { } can use the loop's variables.
skipa string with { }Skip it: skip="true", or a reason such as skip="needs a network".
onlytrue or falsetrue runs only the tests marked only in this file, while you work on them.
timeoutexpressionFail the test if it runs longer than this: 30s, 2m (the default is 10s, or test.timeout in kscript.json). A plain number is seconds.
Example
<fn name="add" params="a, b" value="$a + $b" />
<test name="adds two numbers">
  <expect value="@add(2, 3)" equals="5" />
</test>
<for each="n" in="[1, 2, 3]">
  <test name="doubles {$n}">
    <expect value="@add($n, $n)" equals="$n * 2" />
  </test>
</for>
fn add(a, b) => $a + $b
test(name: 'adds two numbers') {
  expect(@add(2, 3), equals: 5)
}
for n in [1, 2, 3] {
  test(name: "doubles {$n}") {
    expect(@add($n, $n), equals: $n * 2)
  }
}

Commands

Commands are called with @, in any expression: @name(arguments).

#@assert(condition, message?) → bool

Fails the test unless the condition is true. A failed comparison shows the value of each side. message is what to say instead.

Arguments can be named: @assert(…, message: …).

Example
<do>@assert(2 + 3 eq 5)</do>
<do>@assert([1, 2]->count() gt 0, 'The cart should not be empty')</do>
@assert(2 + 3 == 5)
@assert([1, 2]->count() > 0, 'The cart should not be empty')

#@assert_response(response, status?: number, headers?: map, redirect?: string, json?, as?: type)

Checks an HTTP response's status, headers, redirect or JSON. An optional type validates the body.
ParameterTakes
response requiredany value
status optionalnumber
headers optionalmap
redirect optionalstring
json optionalany value
as optionaltype

Arguments can be named: @assert_response(…, status: …, headers: …).

Example
<test name="the API lists people">
  <do>@assert_response(@api('http://localhost:8080/api/people'), status: 200, headers: { 'Content-Type': 'application/json' })</do>
</test>
test(name: 'the API lists people') {
  @assert_response(@api('http://localhost:8080/api/people'), status: 200, headers: { 'Content-Type': 'application/json' })
}

#@check_script(path: string) → list

Checks another script as kscript check does, without running it, and returns its problems: a list of { line, column, severity, code, message }, in the order they appear. The path is relative to the test file. The script is checked even when lint.exclude leaves it out, so mistakes kept on purpose for a test can sit in an excluded folder.
ParameterTakes
path requiredstring
Example
<let name="problems" value="@check_script('mistakes/flags.kscript')" />
<expect value="$problems[0].message" contains="'needs true or false'" />
$problems = @check_script('mistakes/flags.kscript')
expect($problems[0].message, contains: 'needs true or false')

#@fail(message?)

Fails the test now.
Example
<test name="every price is positive">
  <for each="price" in="[3, 5, 8]">
    <if $price le 0>
      <do>@fail('Found a price of {$price}')</do>
    </if>
  </for>
</test>
test(name: 'every price is positive') {
  for price in [3, 5, 8] {
    if $price <= 0 {
      @fail('Found a price of {$price}')
    }
  }
}

#@run_script(path, options?) → map

Runs another script on its own and returns what happened: { output, code, error }. output is what it printed, code its exit code (3 when it stopped with an error) and error the error, or null.

Arguments can be named: @run_script(…, options: …).

Example
<let name="result" value="@run_script('../scripts/hello.ks.xml', { args: ['Joan'], input: ['yes'] })" />
<expect value="$result.output" contains="'Hello, Joan'" />
<expect value="$result.code" equals="0" />
$result = @run_script('../scripts/hello.ks.xml', { args: ['Joan'], input: ['yes'] })
expect($result.output, contains: 'Hello, Joan')
expect($result.code, equals: 0)

#@with_clock(time: date, work: fn) → any

Runs work with @now() and @today() fixed to the given date.
ParameterTakes
time requireddate
work requiredfn

Arguments can be named: @with_clock(…, work: …).

Example
<test name="a new year starts on 1 January">
  <let name="year" value="@with_clock('2027-01-01'->to_date(), fn() => @today().year)" />
  <expect value="$year" equals="2027" />
</test>
test(name: 'a new year starts on 1 January') {
  $year = @with_clock('2027-01-01'->to_date(), fn() => @today().year)
  expect($year, equals: 2027)
}

#@with_environment(values: map, work: fn) → any

Runs work with overrides for @env() and $env. A null value hides a variable in this scope.
ParameterTakes
values requiredmap
work requiredfn

Arguments can be named: @with_environment(…, work: …).

Example
<test name="reads the region from the environment">
  <let name="region" value="@with_environment({ REGION: 'eu-west' }, fn() => @env('REGION'))" />
  <expect value="$region" equals="'eu-west'" />
</test>
test(name: 'reads the region from the environment') {
  $region = @with_environment({ REGION: 'eu-west' }, fn() => @env('REGION'))
  expect($region, equals: 'eu-west')
}