KScript 文档
ZH

KScript.Test

由 kscript test 运行的测试:<test>、<describe>、<expect>、<expect_error>、<capture> 和 @assert()。

在脚本顶部导入:

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

KScript.Test 通过 kscript test 运行,因此其示例无法在文档中直接运行。请将其中一个复制到 .ks.xml 文件中,然后使用 kscript 运行它。

元素语句

#<after_each>after_each

在其文件或 <describe> 中的每个测试之后运行,即使测试失败也会运行。用于清理测试所生成的文件。在其文件或 describe 中的每个测试之后运行,即使测试失败也会运行。用于清理测试所生成的文件。

容纳语句。在 { } 中容纳语句。仅限脚本使用。

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

#<before_each>before_each

在其所在文件或 <describe> 中的每个测试之前运行,作用域为该测试自身。可用 <set> 重置共享变量。在其所在文件或 describe 中的每个测试之前运行,作用域为该测试自身。可用 $name += value 重置共享变量。

容纳语句。在 { } 中容纳语句。仅限脚本使用。

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

#<capture>capture

运行其主体,并将其打印的内容保存到变量中,而不是直接显示。input为其提供要读取的行。

容纳语句。在 { } 中容纳语句。仅限脚本使用。

属性选项值说明
into 必填新变量的名称用于接收输出的变量(换行符为 \n,末尾不含换行)。
input表达式<input> 等提示所读取的内容:文本,或多行列表。input 等提示所读取的内容:文本,或多行列表。
示例
<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

一组测试。它的名称会加在每个测试名称的前面,其 <before_each> 和 <after_each> 适用于组内的每个测试。一组测试。它的名称会加在每个测试名称的前面,其 before_each 和 after_each 适用于组内的每个测试。

容纳语句。在 { } 中容纳语句。仅限脚本使用。

属性选项值说明
name 必填带有 { } 的 string该组测试的说明。
skip带有 { } 的 string跳过:skip="true",或给出原因,如 skip="needs a network"。
onlytrue 或 falsetrue 表示在本文件中只运行标记为 only 的测试,便于你调试时专注于这些测试。
示例
<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

检查一个值,若检查不成立则测试失败。提供该值和一项检查,例如 equals="5"。

自闭合。独立的语句。 仅适用于脚本。

属性选项值说明
value required表达式要检查的值。
equals表达式它等于此值(文本和数字用 ==,列表和映射则逐项比较)。
not_equals表达式它不等于此值。
same表达式它严格相等(===):类型和值都相同。
contains表达式列表包含此项,文本包含此文本,或映射包含此键。
not_contains表达式列表不包含此项,文本不包含此文本,或映射不包含此键。
matches表达式文本匹配此正则表达式,例如 '^\d+$'。
type'string'|'number'|'bool'|'list'|'map'|'date'|'fn'|error|null其类型为此类型。
count表达式列表、映射或文本的项数或字符数为此值。
count_at_most表达式列表、映射或文本的项数或字符数至多为此值:expect(@queries(), count_at_most: 4)。
close_to表达式数字与此值的差在 within 以内(用于浮点数无法精确表示的计算):expect(0.1 + 0.2, close_to: 0.3)。
within表达式数字与 close_to 的最大允许差值(默认 0.000000001):expect($average, close_to: 4.33, within: 0.01)。
has表达式映射包含这些键和对应值,也可以有其他键;对于列表,每一项都必须满足:expect($order, has: { status: 'paid' })。嵌套映射也按同样方式检查。
throws错误类型求值时出现此类型的错误,或扩展该类型的错误,则停止:throws="NotFound"。
message带有 { } 的 string失败时显示的消息,用于替代默认消息。
示例
<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

若其代码块未出错则测试失败。type 和 contains 检查错误类型,as 用于进行更多检查。

容纳语句。在 { } 中容纳语句。仅限脚本使用。

属性选项值说明
type错误类型应出现的错误类型(或其扩展类型),例如 Validation、FileNotFound 或 <error>。应出现的错误类型(或其扩展类型),例如 Validation、FileNotFound 或 error。
contains带有 { } 的 string错误消息中应包含的文本。
as新变量的名称错误的变量(类型、消息、行号以及 <throw> 的字段),在该元素之后声明。错误的变量(类型、消息、行号以及 throw 的字段),在该元素之后声明。
示例
<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

一个测试。当 kscript test 运行该文件时,其代码块单独运行;若其中没有任何失败,则测试通过。在 <for> 循环内,每个项各对应一个测试。一个测试。当 kscript test 运行该文件时,其代码块单独运行;若其中没有任何失败,则测试通过。在 for item in list 循环内,每个项各对应一个测试。

容纳语句。在 { } 中容纳语句。仅限脚本使用。

属性选项值说明
name 必填带有 { } 的 string测试检查的内容,会显示在结果中。在 <for> 循环中,{ } 可以使用循环变量。测试检查的内容,会显示在结果中。在 for item in list 循环中,{ } 可以使用循环变量。
skip带有 { } 的 string跳过:skip="true",或给出原因,如 skip="needs a network"。
onlytrue 或 falsetrue 表示在本文件中只运行标记为 only 的测试,便于你调试时专注于这些测试。
timeout表达式若测试运行时间超过此值则失败:30s、2m(默认为 10s,或 kscript.json 中的 test.timeout)。纯数字单位为秒。
示例
<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)
  }
}

命令

命令可通过 @ 调用,可用于任何表达式:@name(arguments)。

#@assert(condition, message?) → bool

若条件不成立则测试失败。比较失败时会显示两边的值。message 用于指定替代的失败消息。

参数可以命名:@assert(…, message: …)。

示例
<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)

检查 HTTP 响应的状态、响应头、重定向或 JSON。可选的类型用于校验响应体。
参数接受
response 必填任意值
status 可选数字
headers 可选map
redirect 可选string
json 可选任意值
as 可选type

参数可以命名:@assert_response(…, status: …, headers: …)。

示例
<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.
参数接受
path 必需string
示例
<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?)

立即使测试失败。
示例
<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

单独运行另一个脚本并返回其结果:{ output, code, error }。output 是它打印的内容,code 是其退出码(因错误而停止时为 3),error 是错误,若无则为 null。

参数可以命名:@run_script(…, options: …)。

示例
<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

在固定使用给定日期作为 @now() 和 @today() 的情况下运行工作。
参数接受
time 必填date
work 必填fn

参数可以命名:@with_clock(…, work: …)。

示例
<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

在覆盖 @env() 和 $env 的情况下运行工作。null 值会在此作用域内隐藏该变量。
参数接受
values 必填map
work 必填fn

参数可以命名:@with_environment(…, work: …)。

示例
<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')
}