测试脚本:kscript test
简介
测试让你修改代码时无需担心破坏了什么。KScript 内置了测试框架,因此无需安装任何东西。测试是文件名以 .test.kscript 或 .test.ks.xml 结尾的 KScript 文件,通常放在 tests/ 文件夹中,并通过 kscript test 运行。
这是一个用于 slugify 函数的测试文件:
<!-- tests/strings.test.kscript -->
<kscript>
<import path="../lib/strings.kscript" />
<describe name="slugify">
<test name="lower-cases and joins words with dashes">
<expect value="@slugify('Hello World')" equals="'hello-world'" />
</test>
<let name="cases">[
{ text: 'One', slug: 'one' },
{ text: 'Two Words', slug: 'two-words' },
]</let>
<for each="case" in="$cases">
<test name="slug of '{$case.text}'">
<expect value="@slugify($case.text)" equals="$case.slug" />
</test>
</for>
</describe>
</kscript>// 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)
}
}
}
}运行 kscript test,每个测试的结果都会列出;失败的测试会说明出错原因:
$ 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退出代码为 0 表示所有测试均通过。为 1 表示有测试失败、某个测试文件无法运行、没有匹配的测试,或文件夹中没有测试文件。为 2 表示命令行或 kscript.json 有误,例如选项未知或路径不存在。因此 kscript test 可以作为 CI 作业的门禁。退出代码在所有命令中含义相同。
编写测试
测试文件和文件夹
测试文件是一个普通脚本,名为 name.test.kscript 或 name.test.ks.xml。这里的示例使用 .kscript 格式:切换为 XML 即可看到 <describe>、<test> 和 <expect>。测试文件可以不带 import 使用 KScript.Test,编辑器也是如此。
kscript make test checkout 会在项目中创建 tests/checkout.test.kscript(对于 .test.ks.xml 则为 --syntax xml)。kscript make project 会用 lib/ 中的小型待办事项应用规则以及两者的测试来启动新项目,其中包含一个脚本。
测试文件的运行方式
每个文件在各自的解释器中运行,分两步:
- 文件的顶层代码运行一次:其导入、变量、
fn函数和describe块。它遇到的每个test只会被记录,不会运行。 - 然后每个测试单独运行,位于其所在作用域内的一个新作用域中。它能看到文件的变量和函数,以及其外层
describe块的变量。
如果测试的主体执行完毕则通过。它会在第一个不成立的检查或任何错误处失败,其余测试仍会继续运行。测试声明的变量属于该测试本身。在测试外部声明的变量是共享的,因此应在 before_each 中重置它们。
测试中用 echo 输出的内容会被保留,并且只在测试失败时显示在该测试下方。
分组与钩子
describe(name: …) { } 用于对测试分组。其名称会加在每个测试名称(a shopping cart › adds items)之前,其钩子适用于组内每个测试。分组可以嵌套。
before_each { } 在其文件或 describe 中的每个测试之前运行,位于该测试自身的作用域内,外层钩子先运行。after_each { } 在每个测试之后运行,即使测试失败也会运行,内层钩子先运行。用它删除测试创建的文件:
<describe name="a shopping cart">
<let name="cart" value="[]" />
<before_each>
<set name="cart" value="['apple']" />
</before_each>
<test name="starts with one item">
<expect value="$cart" count="1" />
</test>
<test name="adds items">
<set name="cart" value="$cart->push('pear')" />
<expect value="$cart" equals="['apple', 'pear']" />
</test>
</describe>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'])
}
}由数据生成的测试
for 循环内的 test 会为每个条目生成一个测试。循环变量可用于测试名称及其主体,如上面 slugify 示例所示。在 XML 中,请写作 <for each="case" at="i" in="$cases"><test name="…">。
跳过、聚焦与超时
test 或 describe 上的 skip 不会运行它,并会将其报告为已跳过,skip: 'reason' 给出原因。在处理某些内容时,only 只运行该文件中标记为 only 的测试。timeout: 30s 会使运行超过 30 秒的测试失败:
<test name="imports a large file" timeout="30s">
<expect value="[1, 2, 3]->sum()" equals="6" />
</test>
<test name="sends the weekly email" skip="the mail server is down">
<expect value="true" equals="true" />
</test>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)
}检查
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 排除的文件夹中(参见 项目),这样项目上的 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?)则执行表单的提交事件处理程序。- 在普通的 HTML 表单中,若没有实时处理程序,
->fill(name, value)会在带有该name的字段中输入内容,而->submit(text?)会像浏览器一样提交表单:页面中每个已命名的字段(隐藏字段、CSRF_token、已勾选的复选框、下拉框所选的选项)及你输入的内容,以及带有该文本的按钮,都会提交到表单的action并附带其method。若没有文本,则提交你所输入的表单。响应中的重定向会被跟随,因此.path即为浏览器最终会到达的位置。 .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 中有一个页面,其按钮全部使用处理函数简写形式,并且每个按钮都有对应的测试。
运行测试
不带路径的 kscript test 会运行当前项目中的每个测试文件:即最近的 kscript.json 所在文件夹,如果没有则为当前文件夹。名称以 . 开头的文件夹,以及 node_modules、bin 和 obj,都会被跳过。你也可以指定文件夹和文件,或按名称挑选测试:
| 命令 | 作用 |
|---|---|
kscript test | 项目中可能受改动影响的测试。 |
kscript test --all | 项目中的每个测试。 |
kscript test --failed | 仅上次失败的测试。 |
kscript test --changed | 你未提交的更改可能影响到的测试。 |
kscript test --changed master | 本分支的更改可能影响到的测试。 |
kscript test --watch | 每次保存时运行受影响的测试。 |
kscript test tests/cart tests/api.test.kscript | 一个文件夹和一个文件。 |
kscript test --filter "cart › adds" | 仅运行全名包含该文本的测试(不区分大小写) |
kscript test --timeout 30 | 每个测试的秒数(0:不限制) |
kscript test --junit test-results.xml | 同时写入 JUnit XML 报告。 |
kscript tests/cart.test.kscript 也可运行单个文件。
当输出为终端时使用颜色;设置 NO_COLOR 可关闭颜色,设置 FORCE_COLOR 可保留颜色。按 Ctrl+C 可在当前测试结束后停止运行。
--junit 以 JUnit XML 格式写入结果,GitHub Actions 报告工具、GitLab、Jenkins 和 Azure Pipelines 均可显示。失败的检查记为 <failure>,其他错误记为 <error>,无法运行的文件记为名为 (load) 的测试,并附带 <error>。
仅运行有变化的部分
大型项目包含大量测试,而大多数改动只影响其中少数几个。因此在项目中,kscript test 只运行自上次运行以来的改动可能影响到的测试。修改某个模型的方法,只有调用过该方法的测试会重新运行;修改某个服务,只有经过该服务的测试会重新运行。
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每个测试运行时,kscript 都会记录它触及的内容:调用的每个函数和方法,使用的每个类型、模型、枚举、错误和任务,加载的每个脚本,以及为其读取的每个文件(页面、配置、测试数据)。每一项都有其自身文本的指纹,保存在 .kscript/cache/tests.json 中(该文件夹会忽略自身,因此 git 不会看到它)。在以下情况下测试会重新运行:
- 它是新的,或者它自身的代码块发生了变化;
- 它上次失败了(会一直运行直到通过);
- 它触及的某个函数、方法、类型或其他声明发生了变化;
- 它加载的某个脚本在其声明之外(导入、常量或顶层代码)发生了变化,或者为它读取的某个文件发生了变化。
- 它使用了测试数据库,且某个迁移发生了变化(或者在没有迁移的项目中,生成数据库所依据的某个模型发生了变化)。
由于真正起作用的是每个测试实际运行过的内容,因此测试文件可以导入项目的一半代码,而某个测试仍然只依赖它实际经过的代码。
当还没有运行记录时、当 kscript 自身发生变化时、当 kscript.json 或 .env 文件发生变化时,以及当出现新脚本时(它可能按约定被识别,例如扩展或路由文件),所有测试都会运行。输出的第一行会说明原因。
某些运行总是会运行它们指定的全部内容,并同时更新记录:
kscript test --all;- 指定文件(
kscript test tests/cart.test.kscript)或使用--filter; - 在 CI 中,即设置了
CI变量的情况(GitHub Actions 和大多数 CI 服务都会设置该变量)。
kscript test --failed 只运行上次运行中失败的测试。
测试一个 git diff
--changed 会向 git 询问哪些内容发生了变化,而不是与上次运行进行比较。单独使用时,它会获取你尚未提交的更改;若指定基准(例如分支、标签或提交),则会获取自该基准以来的所有更改,无论是否已提交:
| 命令 | 作用 |
|---|---|
kscript test --changed | 测试你未提交的更改可能影响到的内容。 |
kscript test --changed master | 测试本分支可能影响到的内容,以便在打开拉取请求之前检查。 |
kscript test --changed HEAD~3 | 测试最近三次提交可能影响到的内容。 |
kscript 会按声明逐一比较每个变更文件在基准处的版本与当前版本,并运行触及有差异部分的测试,以及新增的测试和被 diff 改动的测试。它仍然需要一份之前运行的记录,才能知道每个测试触及了什么;没有记录时,它会运行所有测试。
监视
kscript test --watch 会先运行测试,然后持续监视项目。每次保存时,它只运行触及你所改动内容的测试。保存一个没有任何测试触及的文件(例如 README)时,不会运行任何内容。在终端中,每次运行都会替换屏幕上的上一次结果,因此你看到的总是最新结果;当输出被导向文件或管道时,或使用 --no-ansi 时,每次运行的结果会追加在上一次之后。按 Ctrl+C 停止。
| 命令 | 作用 |
|---|---|
kscript test --watch | 每次保存时运行受影响的测试。 |
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: … 优先于 --timeout,后者又优先于 test.timeout。
test.env 是测试运行的环境,因此 kscript.test.json 会覆盖 kscript.json 的设置(参见 设置)。API 和全栈项目模板使用它为测试提供内存数据库。
kscript test --env staging 以及已设置的 KSCRIPT_ENV 优先于 test.env。
使用 KScript.Data 的测试无论配置如何,都会在内存中获得各自的数据库,除非 test.database 为 config。每个测试的更改在结束时都会被撤销。这也包括在 http.auth.users 中由模型支持的用户。测试使用 @api() 调用的路由共用同一个数据库,并处于该测试的事务中:路由能看到测试创建的记录,测试也能看到路由保存的内容,两者会一起撤销。
每个测试文件还会为基于文件的认证(包括已配置的 http.auth.folder 存储)以及 @storage() 创建临时应用文件夹。同一文件内的命令和本地 @api() 调用共享这些文件夹。文件结束时(包括失败时)运行器会将其删除。当测试需要预置的用户或文件时,请在测试文件内使用 fixture 或 setup 钩子。
测试 API
@api(/api/notes) 无需启动服务器即可向项目自身的路由发送请求(参见 调用你自己的 API),从而测试客户端会得到的结果:
<import package="KScript.Net" />
<test name="a note is saved">
<let name="added" value="@api(/api/notes, post: { title: 'Ship it' })" />
<expect value="$added.status" equals="201" />
<expect value="@api(/api/notes/$added->convert(from: json).id)->convert(from: json).title" equals="'Ship it'" />
</test>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')
}伪造语言模型
可以在没有密钥或网络的情况下测试通过 @llm、llm 或 $chat->ask() 向 Claude 提问的代码。@fake_llm(replies) 会在本次运行的其余部分回答每个问题,并保存所提的问题。可以传入按顺序使用的答案列表,也可以传入一个为每个提示词调用的函数。对于带有 schema 的提问,则使用映射来作答:
<import package="KScript.AI" />
<fn name="triage" params="report: string" value="@llm("Triage this report: { $report }", schema: { category: 'bug|feature|question' })" />
<test name="a crash report is a bug">
<let name="fake" value="@fake_llm([{ category: 'bug' }])" />
<expect value="@triage('The app crashes on start')" has="{ category: 'bug' }" />
<expect value="$fake->prompts()" equals="['Triage this report: The app crashes on start']" />
</test>
<test name="the reply can depend on the prompt">
<do>@fake_llm(fn(prompt) => $prompt->contains('French') ? 'Bonjour' : 'Hello')</do>
<expect value="@llm('Say hello in French')" equals="'Bonjour'" />
</test>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() 表示模型被询问的次数。当列表用完时,下一次询问会以没有答案的提示失败。
测试谁能做什么
来自 KScript.Auth 的 @acting_as() 会在测试结束前设定 @user()、@can() 和 @authorize() 所查询的用户身份。传入 null 可以以访客身份操作。测试通过 @api(/...) 调用的路由会看到同一用户,包括位于 auth、auth:session 或 auth:token 中间件之后的路由,因此登录后的路由在测试中无需令牌:
<import package="KScript.Auth" />
<import package="KScript.Net" />
<test name="the dashboard greets me">
<do>@acting_as(@register('ada@example.test', 'correct-horse-battery-9'))</do>
<expect value="@api(/dashboard).status" equals="200" />
</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)
}要测试基于 Cookie 的行为,例如访客的看板或记住的偏好,请自行发送 Cookie:@api(/, options: { headers: { Cookie: 'sb_guest=0f8f' } })。响应中的 .cookies 会显示它设置的 Cookie。
<import package="KScript.Auth" />
<import package="KScript.Data" />
<import path="../models/post.kscript" />
<test name="only the author may update a post">
<let name="post" value="Post->create(title: 'Mine', author_id: 1)" />
<do>@acting_as({ id: 1 })</do>
<expect value="@can(update, $post)" equals="true" />
<do>@acting_as({ id: 2 })</do>
<expect value="@can(update, $post)" equals="false" />
</test>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)
}从语言测试中学习
KScript 自身的仓库用一组测试脚本来测试这门语言,这些脚本同时也是很好的示例。运行 kscript test samples/scripts/tests/language 可以执行全部测试,或者传入某个文件。它们也会显示在 VS Code 的测试资源管理器中,并且 CI 会比对语言服务器找到的测试与解释器的运行结果。浏览所有语言测试脚本
| 可以尝试的内容 | 可运行的示例 |
|---|---|
| 跟踪参数绑定、递归调用和变量作用域 | 命名调用与管道调用 · 递归与作用域 |
| 逐步查看表达式或嵌套循环 | 运算符优先级 · 范围与循环元数据 |
| 为数据定义类型,并在边界处进行校验 | 自定义字面量 · 从文本解析记录 · 联合类型 |
| 转换集合与文本 | 列表转换 · Map 更新 · 正则表达式 · 多行字符串 |
| 使用原生值,并为类型添加方法 | 日期与时长 · 金额与舍入 · 扩展方法 |
| 跟踪错误穿过嵌套处理器的路径 | 受保护的 throw · catch 传播 |
仓库在 语言测试计划中跟踪覆盖缺口、组合目标以及共享的 CLI、语言服务器和编辑器检查。
运行 kscript test samples/scripts/tests/language/checkout-workflow.test.kscript 可以跟踪一张多币种发票,从行校验、折扣、结算到退款。测试会断言两种币种下的金额,从缺失报价中还原原始错误,并检查部分退款后保留的零头。结账脚本
运行 kscript test samples/scripts/tests/language/dispatch-workflow.test.kscript 可以跟踪传入的 JSON 如何经过类型化记录、团队名称规范化、优先级排序和队列选择。同一策略会在遇到未知团队时选择回退方案,或者传播查找错误。调度脚本
精炼字符串套件检查裸静态键、带引号的插值、去除空白以及模式匹配失败的情况。许可证签发套件测试三个校验守卫,并检查调用方在成功和失败时看到的结果。
在编辑器中
语言服务器会将 *.test.kscript 和 *.test.ks.xml 文件视为导入了 KScript.Test,因此 test、expect 等文件可获得补全、悬停提示和检查,并且 for 循环中测试用例周围的变量在其内部也能被识别。在 VS Code 中,KScript: Run Tests 会为工作区运行 kscript test,测试文件的编辑器标题栏中也有运行按钮。
expect、@assert 和 capture 同样适用于普通脚本,这些脚本import KScript.Test:检查失败时,脚本会因Assertion错误而停止。test 和 describe 仅在 kscript test 下生效。
对比检查器与编辑器的诊断信息
使用 kscript check path/to/script.kscript --output json 将诊断代码、消息、严重级别和源范围保存到磁盘。在 VS Code 中,问题 会显示当前缓冲区的诊断信息,包括未保存的编辑。将 "kscript.trace.server": "verbose" 设为开启,即可在跟踪输出中查看语言服务器的 textDocument/publishDiagnostics 通知。命令行的行号和列号从 1 开始。LSP 的行号和列号从 0 开始。
在仓库根目录下,完成 KScript 的 Release 模式构建并安装扩展的 npm 依赖后,运行与 CI 相同的协议检查:
node editors/vscode/test/smoke.js KScriptApp/bin/Release/net8.0/KScript.dll该测试会打开每个语言套件和辅助程序。对于诊断固件,它会检查预期的源码范围,将服务器的消息和严重级别与 CLI 报告进行比较,并验证在保存文件之前,修正操作会清除旧的诊断信息。