KScript 文档
ZH

测试

检查

expect 首先接收要检查的值(不带名称),然后接收一项检查:expect($total, equals: 3)。每项检查的值都是一个表达式,因此文本需要加引号:equals: 'hello'。

检查项 通过条件
expect($x, equals: 5) 当值相等时通过,比较方式与 == 相同:'5' 等于 5。列表和映射会逐项比较,失败时会指出差异所在。
not_equals: 5 它们不相等。
same: 5 它们严格相等(===):类型和值都相同。
contains: 'Joan' 列表返回其项,文本返回其文本,映射返回其键。
not_contains: 'Joan' 相反的情况。
matches: '^\d+$' 文本与正则表达式匹配。
type: list 该值是 string、number、bool、list、map、date、fn 或 null。
count: 3 列表或映射包含这么多项,或文本包含这么多字符。
count_at_most: 4 列表或映射最多包含这么多项,或文本最多包含这么多字符。使用 @queries() 时,它会检查测试发送了多少次查询。
close_to: 0.3 数字在此值的 within: 范围内(除非另行指定,否则为 0.000000001):expect(0.1 + 0.2, close_to: 0.3)、expect($average, close_to: 4.33, within: 0.01)。用于金钱、统计及其他浮点数无法精确表示的数学计算。
has: { status: 'paid' } 映射包含以下键及其对应的值,也可以包含其他键。嵌套的映射以相同的方式检查。对于列表,每一项都必须包含这些键。

在任何检查中,message: … 会替换常规消息。

has: 适用于 API 应答中测试只关心少数几个字段的情况:

<let name="order" value="{ id: 7, status: 'paid', total: 30, customer: { name: 'Ann', email: 'ann@example.com' } }" />
<expect value="$order" has="{ status: 'paid', customer: { name: 'Ann' } }" />
<expect value="[{ id: 1, active: true }, { id: 2, active: true }]" has="{ active: true }" />
$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?) 用于检查条件,可以单独成行,也可以放在表达式内部,例如 lambda 中。当比较失败时,它会显示两边的值:

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

@fail(message?) 会立即测试失败。

错误

expect_error { } 在其主体未以错误结束时失败。type 检查错误类型(继承该类型的错误类型同样匹配),contains 检查消息,as 保留该错误(type、message、line、file、status、cause 及其字段)以供后续检查:

<expect_error type="Validation" contains="positive" as="err">
  <do>@set_age(-1)</do>
</expect_error>
<expect value="$err.line" type="number" />
expect_error(type: Validation, contains: 'positive', as: err) {
  @set_age(-1)
}
expect($err.line, type: number)

对于单个表达式,throws写法更简短:当求值过程因该类型的错误而终止时,此表达式即判定为通过。

<error name="PersonNotFound" extends="NotFound" />

<fn name="find_person" params="id: int">
  <throw type="PersonNotFound">No person with id {$id}</throw>
</fn>

<expect value="@find_person(99)" throws="PersonNotFound" />
<expect value="'nope'->convert(from: json)" throws="Format" /> <!-- Json extends Format -->
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

测试主体中失败的检查仍会被报告为失败,而不会被当作预期的错误。

输出和输入

capture(into: out) { } 运行其代码体,并将其输出的内容放入 $out(行以 \n 结尾,最后一行除外)。input 为诸如 input 之类的提示提供回答,回答可以是文本,也可以是多行列表:

<capture into="out" input="['Joan', 'yes']">
  <do>@sign_up()</do>
</capture>
<expect value="$out" contains="'Welcome, Joan'" />
capture(into: out, input: ['Joan', 'yes']) {
  @sign_up()
}
expect($out, contains: 'Welcome, Joan')

整个脚本

@run_script(path, { args, input }) 独立运行另一个脚本,就像 kscript path args… 那样,并返回 { output, code, error }:其输出的内容、退出码(出错停止时为 3),以及错误信息或 null。路径相对于测试文件。该脚本可使用项目的包,但无法使用 KScript.Test。

<test name="hello.kscript greets the name it is given">
  <let name="run" value="@run_script('../scripts/hello.kscript', options: { args: ['Ellie'] })" />
  <expect value="$run.code" equals="0" />
  <expect value="$run.output" equals="'Hello, Ellie!'" />
</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!')
}

用于在顶层执行工作或调用 exit 的脚本。自行调用 exit 的测试会失败。

@check_script(path) 检查另一个脚本的方式与 kscript check 相同,但不会运行它,并按出现顺序返回其中的问题:一个 { line, column, end_line, end_column, severity, code, message, fixes } 列表,其中 fixes 保存编辑器为该问题提供的快速修复标题。用它来说明编辑器和 kscript check 能发现哪些错误。请将有意包含错误的脚本放在 lint.exclude 会忽略的文件夹中(参见 Projects),这样项目上的 kscript check 结果保持干净。@check_script() 仍会检查该文件:

<test name="a map is not a flag">
  <let name="problems" value="@check_script('mistakes/flags.kscript')" />
  <expect value="$problems" count="1" /> <!-- one mistake gets one report -->
  <expect value="$problems[0].line" equals="2" />
  <expect value="$problems[0].message" contains="'needs true or false, but this is a map'" />
</test>
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')
}

页面

@visit(path)(来自 KScript.Web)会按浏览器获取页面的方式渲染项目中的一个页面,就像 kscript serve 响应请求那样:先处理项目的路由(即 view: 路由,或返回 @view(...) 的控制器,连同它们的中间件),然后再处理最近的 kscript.json 中 serve.root 下的文件页面。其实时处理程序在服务器上运行,与在浏览器中的行为一致,因此测试可以模拟点击页面:

  • ->click(text) 会运行带有该文本的按钮或链接(或 aria-label 或 title)的点击处理程序。
  • ->change(text) 会运行 <label> 带有该文本的输入框(例如复选框)的 on-change 处理程序。
  • ->fill(field, value)会在绑定到该字段的输入框中输入内容,->submit(text?)则执行表单的提交事件处理程序。
  • .text 是页面上的文字,.html 是其 HTML,->classes(text) 是该元素的类名,该元素即为这段文字本身所在的元素。

这些方法每个都会返回页面,因此可以链式调用。如果页面不存在,则会出现 NotFound 错误。处理程序通过 @emit_event()(或 emit:)发送的事件会像在浏览器中一样,传递给其他块的 on-event 监听器:由 target: 指定的块,或所有监听该事件的块。

访问某个路由时会保留应用设置的 Cookie(访客 Cookie、会话),供后续点击使用,并像浏览器一样跟随重定向:.path 是最终到达的位置。@acting_as() 会以该访问的身份登录,@api(/...) 也是如此,@visit(path, { headers: { Cookie: 'guest=abc' } }) 会发送它自己的请求头(bearer: 发送一个令牌):

<import package="KScript.Web" />
<import package="KScript.Auth" />

<test name="a guest is sent to sign in">
  <expect value="@visit('/account').path" equals="'/login'" />
</test>

<test name="the account page makes a token">
  <do>@acting_as(@register('ada@example.test', 'correct-horse-battery-9'))</do>
  <let name="page" value="@visit('/account')->fill('name', 'laptop')->submit('Make a token')" />
  <expect value="$page.text" contains="'Your new token is'" />
</test>
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 package="KScript.Web" />

<test name="adding a task clears the box">
  <let name="page" value="@visit('/tasks')->fill('draft', 'Write the docs')->submit()" />
  <expect value="$page.text" contains="'Write the docs'" />
  <expect value="$page->classes('Write the docs')" not_contains="'done'" />
</test>
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 中有一个页面,其按钮全部使用处理函数简写形式,并且每个按钮都有对应的测试。