KScript 文档
ZH

测试

编写测试

测试文件和文件夹

测试文件是一个普通脚本,名为 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/ 中的小型待办事项应用规则以及两者的测试来启动新项目,其中包含一个脚本。

测试文件的运行方式

每个文件在各自的解释器中运行,分两步:

  1. 文件的顶层代码运行一次:其导入、变量、fn 函数和 describe 块。它遇到的每个 test 只会被记录,不会运行。
  2. 然后每个测试单独运行,位于其所在作用域内的一个新作用域中。它能看到文件的变量和函数,以及其外层 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)
}