Zig 测试
可以在一个或多个 test 声明内编写代码,用于确认行为符合预期:
const std = @import("std");
test "expect addOne adds one to 41" {
// 标准库包含帮助编写测试的实用函数。
// `expect` 用于验证参数为 true。
// 参数为 false 时会返回错误,表示测试失败。
// `try` 用于向测试运行器返回错误,通知它测试失败。
try std.testing.expect(addOne(41) == 42);
// 不过,多数情况下使用 `expectEqual` 等更具体的函数更方便。
// 这样测试失败时会得到更清晰、更有帮助的错误信息。
try std.testing.expectEqual(42, addOne(41));
}
test addOne {
// 测试名称也可以使用标识符。
// 这是文档测试,用于说明 `addOne`。
try std.testing.expectEqual(42, addOne(41));
}
/// 函数 `addOne` 将参数所给的数加一。
fn addOne(number: i32) i32 {
return number + 1;
}$ zig test testing_introduction.zig
1/2 testing_introduction.test.expect addOne adds one to 41...OK
2/2 testing_introduction.decltest.addOne...OK
All 2 tests passed.
testing_introduction.zig 代码示例测试函数 addOne,确认输入 41 时返回 42。从该测试的角度看,addOne 函数称为被测代码。
zig test 是创建并运行测试构建的工具。默认情况下,它会构建并运行一个可执行程序,以 Zig 标准库提供的默认测试运行器作为主入口点。构建期间,在解析给定 Zig 源文件时发现的 test 声明会纳入测试,由默认测试运行器执行并报告结果。
上面的命令行输出在 zig test 命令之后显示了两行内容。这些内容由默认测试运行器写入标准错误流:
- 1/2 testing_introduction.test.expect addOne adds one to 41...
- 这样的行表示总共多少个测试中正在执行哪一个。此处 1/2 表示共两个测试,正在运行第一个。注意,当测试运行器的标准错误流输出到终端时,测试成功后会清除相应行。
- 2/2 testing_introduction.decltest.addOne...
- 测试名称为标识符时,默认测试运行器显示 decltest 而不是 test。
- All 2 tests passed.
- 这一行表示通过测试的总数。
测试声明
测试声明由关键字 test 开始,随后是可选名称(写作字符串字面量或标识符),最后是一个块,其中可包含函数内部允许的任意合法 Zig 代码。
未命名的测试块在测试构建中始终运行,不受跳过测试规则影响。
测试声明与函数类似,具有返回类型和代码块。test 的隐式返回类型固定为错误联合类型 anyerror!void,不可修改。未使用 zig test 工具构建 Zig 源文件时,测试声明不会纳入构建。
测试声明可以写在被测代码所在文件中,也可以写在独立的 Zig 源文件中。测试声明属于顶层声明,与顺序无关,可以位于被测代码之前或之后。
另见:
文档测试
使用标识符命名的测试声明是文档测试。该标识符必须引用作用域内的另一条声明。与文档注释类似,文档测试也是关联声明的说明,会出现在为该声明生成的文档中。
有效的文档测试应当自包含,并专注于被测试的声明,回答新用户可能对接口或预期用法产生的疑问,同时避免不必要或容易引起混淆的细节。文档测试不能替代文档注释,而是其补充与配套,提供可执行、以代码表达的示例,并由 zig test 验证。
测试失败
默认测试运行器会检查测试是否返回错误。测试返回错误即视为失败,并将其错误返回追踪输出到标准错误流。全部测试结束后会报告失败总数。
const std = @import("std");
test "expect this to fail" {
try std.testing.expect(false);
}
test "expect this to succeed" {
try std.testing.expect(true);
}$ zig test testing_failure.zig
1/2 testing_failure.test.expect this to fail...FAIL (TestUnexpectedResult)
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/testing.zig:584:14: 0x124e969 in expect (std.zig)
if (!ok) return error.TestUnexpectedResult;
^
/home/alexrp/Sources/ziglang/zig/doc/langref/testing_failure.zig:4:5: 0x124ea59 in test.expect this to fail (testing_failure.zig)
try std.testing.expect(false);
^
2/2 testing_failure.test.expect this to succeed...OK
1 passed; 0 skipped; 1 failed.
error: the following test command failed with exit code 1:
/home/alexrp/Sources/ziglang/zig/.zig-cache/o/f50fc6a1df094887bb6a3fb9f19b6078/test --seed=0xce0cf7fc
跳过测试
跳过测试的一种方式是通过 zig test 的命令行参数 --test-filter [text] 过滤测试。这样测试构建只纳入名称包含指定过滤文本的测试。注意,即使使用 --test-filter [text] 命令行参数,未命名测试仍然运行。
若要以编程方式跳过测试,让 test 返回错误 error.SkipZigTest,默认测试运行器便会将该测试视为已跳过。全部测试结束后会报告跳过的测试总数。
test "this will be skipped" {
return error.SkipZigTest;
}$ zig test testing_skip.zig
1/1 testing_skip.test.this will be skipped...SKIP
0 passed; 1 skipped; 0 failed.
报告内存泄漏
当代码通过 Zig 标准库的测试分配器 std.testing.allocator 分配内存时,默认测试运行器会报告该分配器检测到的所有内存泄漏:
const std = @import("std");
test "detect leak" {
const gpa = std.testing.allocator;
var list: std.ArrayList(u21) = .empty;
// 缺少 `defer list.deinit(gpa);`
try list.append(gpa, '☔');
try std.testing.expectEqual(1, list.items.len);
}$ zig test testing_detect_leak.zig
1/1 testing_detect_leak.test.detect leak...OK
[SafeAllocator] (err): leaked [addr: 7d9d890fc010, len: 132 (0x84) align: 4] allocated at:
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/array_list.zig:1375:56: 0x124faf1 in ensureTotalCapacityPrecise (std.zig)
const new_memory = try gpa.alignedAlloc(T, alignment, new_capacity);
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/array_list.zig:1349:51: 0x124f739 in ensureTotalCapacity (std.zig)
return self.ensureTotalCapacityPrecise(gpa, growCapacity(new_capacity));
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/array_list.zig:1406:41: 0x124ed1d in addOne (std.zig)
try self.ensureTotalCapacity(gpa, newlen);
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/array_list.zig:1027:49: 0x124ebb7 in append (std.zig)
const new_item_ptr = try self.addOne(gpa);
^
/home/alexrp/Sources/ziglang/zig/doc/langref/testing_detect_leak.zig:7:20: 0x124ea18 in test.detect leak (testing_detect_leak.zig)
try list.append(gpa, '☔');
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/compiler/test_runner.zig:295:25: 0x1202c41 in mainTerminal (test_runner.zig)
if (test_fn.func()) |_| {
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/compiler/test_runner.zig:74:28: 0x1202422 in main (test_runner.zig)
return mainTerminal(init);
^
(additional stack frames may have been skipped...)
All 1 tests passed.
1 errors were logged.
1 tests leaked memory.
error: the following test command failed with exit code 1:
/home/alexrp/Sources/ziglang/zig/.zig-cache/o/2831f33bedc7b584b08df3695aa558e2/test --seed=0x5feb182b
另见:
检测测试构建
使用编译变量 @import("builtin").is_test 检测测试构建:
const std = @import("std");
const builtin = @import("builtin");
const expect = std.testing.expect;
test "builtin.is_test" {
try expect(isATest());
}
fn isATest() bool {
return builtin.is_test;
}$ zig test testing_detect_test.zig
1/1 testing_detect_test.test.builtin.is_test...OK
All 1 tests passed.
测试输出与日志
默认测试运行器和 Zig 标准库的测试命名空间都向标准错误流输出消息。
测试命名空间
Zig 标准库的 testing 命名空间包含有助于编写测试的函数。除 expect 函数外,本文档还使用以下示例中的其他函数:
const std = @import("std");
test "expectEqual demo" {
const expected: i32 = 42;
const actual = 42;
// `expectEqual` 的第一个参数是已知的预期结果。
// 第二个参数是某个表达式的实际结果。
// 实际结果的类型会转换为预期结果的类型。
try std.testing.expectEqual(expected, actual);
}
test "expectError demo" {
const expected_error = error.DemoError;
const actual_error_union: anyerror!void = error.DemoError;
// 实际错误与预期错误不同时,
// `expectError` 会失败。
try std.testing.expectError(expected_error, actual_error_union);
}$ zig test testing_namespace.zig
1/2 testing_namespace.test.expectEqual demo...OK
2/2 testing_namespace.test.expectError demo...OK
All 2 tests passed.
Zig 标准库还包含比较切片、字符串等内容的函数。更多可用函数请参见 Zig 标准库中 std.testing 命名空间的其余内容。
测试工具文档
zig test 提供若干影响编译过程的命令行参数。完整列表参见 zig test --help。