测试机制

断言(Asserts)

基础断言验证表达式为真:

mut arr := [20]
modify_array(mut arr)
assert arr[0] < 4  // 失败时打印左右值对比

高级特性:

  1. 带消息的断言
assert i*2 < 100, 'i=${i}时断言失败' 
  1. 非中断断言
@[assert_continues] // 函数级标记
fn validate(n int) {
    assert n % 2 == 0  // 失败仅打印不终止
}

全局启用:编译时添加 -assert continues 参数生产环境:-prod 编译自动移除所有断言

测试文件规则

  1. 文件命名*_test.v 后缀
  2. 函数命名test_ 前缀标识测试函数
  3. 模块声明:与待测模块相同(内部测试)/导入模块(外部测试)

内部测试示例:

// main_test.v
module main  // 与被测模块相同

fn test_hello() {
    assert hello() == 'Hello world'  // 可访问私有函数
}

外部测试示例:

// math_test.v
module tests

import math  // 导入被测模块

fn test_add() {
    assert math.add(2,3) == 5  // 仅测试公开API
}

特殊测试函数

fn testsuite_begin() { /* 所有测试前执行 */ }
fn testsuite_end()  { /* 所有测试后执行 */ }
fn test_error() ! {  // 错误传播使测试失败
    parse_number('abc')! 
}

测试运行方式

# 单测试文件
v foo_test.v

# 模块测试
v test mymodule

# 递归测试当前目录
v test . -stats  # 查看详细数据

测试数据管理

创建 testdata 目录存放测试资源:

project/
├── src/
├── tests/
│   ├── parser_test.v
│   └── testdata/      # 专用目录
│       ├── invalid.v
│       └── cases.json

子测试执行

fn test_subprocess() {
    res := os.execute('${@VEXE} other_test.v')  // @VEXE获取编译器路径
    assert res.output.contains('success')
}