builtinstdIoEnvironassertmathrandom_seedFailingAllocatorfailing_allocatorfailing_allocator_instancebase_allocator_instanceallocator_instanceallocatorio_instanceioenvironlog_levelbackend_can_printfailPrintexpectEqualexpectEqualInnerexpectApproxEqAbsexpectApproxEqAbsInnerexpectApproxEqRelexpectApproxEqRelInnerexpectEqualSlicesfailEqualSlicesSliceDifferBytesDifferexpectEqualSentinelexpectTmpDirtmpDirexpectErrorreturnErrorUnionexpectFmtexpectEqualStringsexpectStringStartsWithexpectStringEndsWithexpectEqualDeepexpectEqualDeepInnerfooformatABCfailPrintIndicatorLinefailPrintWithVisibleNewlinesfailPrintLinecheckAllAllocationFailuresCheckAllAllocationFailuresExtraArgsffrefAllDeclsSmithFuzzInputOptionsfuzzReaderReaderIndirectWriterIndirect
std.testing.A
容器
字段
std.testing.allocator
常量
std.testing.allocator_instance
变量
std.heap.SafeAllocator
std.testing.assert
别名
别名目标 std.debug.assert
std.testing.B
命名空间
std.testing.backend_can_print
常量
std.testing.base_allocator_instance
变量
std.testing.builtin
常量
std.testing.BytesDiffer
容器
字段
std.testing.BytesDiffer.terminal
函数
fn terminal(self: *const BytesDiffer, writer: *Io.Writer) Io.Terminal
参数
self: *const BytesDiffer
writer: *Io.Writer
std.testing.BytesDiffer.write
函数
pub fn write(self: BytesDiffer, writer: *Io.Writer) !void
参数
self: BytesDiffer
writer: *Io.Writer
std.testing.BytesDiffer.writeDiff
函数
fn writeDiff(self: BytesDiffer, writer: *Io.Writer, comptime fmt: []const u8, args: anytype, diff: bool) !void
参数
std.testing.C
容器
字段
a: *const A
std.testing.checkAllAllocationFailures
函数
穷举检查 test_fn 内的分配失败是否均得到处理,且不会
引入内存泄漏。若将 testing.allocator 用作 backing_allocator,
还可在启用运行时安全检查时检测重复释放等问题。
提供的 test_fn 必须以 std.mem.Allocator 作为第一个参数,
返回类型必须为 !void。test_fn 的其他参数
可通过 extra_args 元组提供。
test_fn 多次运行之间共享的所有相关状态,必须在 test_fn 内重置。
采用的策略如下:
- 首先运行测试函数一次,获取分配总次数。
- 然后迭代并额外运行函数 X 次,每次迭代 递增发生失败的分配索引;X 为此前 确定的分配总次数。
要求 test_fn 的内存分配次数具有确定性:
- 若某次
test_fn运行中人为使一次分配失败,但test_fn没有返回error.OutOfMemory,则返回error.SwallowedOutOfMemoryError, 此错误由checkAllAllocationFailures返回。是否忽略此错误, 取决于被测代码是否包含从error.OutOfMemory恢复的策略。 - 若预期发生分配失败的一次
test_fn运行实际结束时 未触发分配失败,则返回error.NondeterministicMemoryUsage。 此错误表示本函数使用的策略无法测试 某些分配点,即某些运行中的分配点 多于首次运行test_fn时检测到的分配点。
以下简单测试在分配 bar 失败时
会泄漏内存,而正常情况下会通过:
test {
const length: usize = 10;
const allocator = std.testing.allocator;
var foo = try allocator.alloc(u8, length);
var bar = try allocator.alloc(u8, length);
allocator.free(foo);
allocator.free(bar);
}
可以按以下方式将测试用例转换为 本函数可调用的形式:
fn testImpl(allocator: std.mem.Allocator, length: usize) !void {
var foo = try allocator.alloc(u8, length);
var bar = try allocator.alloc(u8, length);
allocator.free(foo);
allocator.free(bar);
}
test {
const length: usize = 10;
const allocator = std.testing.allocator;
try std.testing.checkAllAllocationFailures(allocator, testImpl, .{length});
}
运行此测试将显示:foo 会在分配 bar 失败时
发生泄漏。此时最简单的修复方式是使用 defer:
fn testImpl(allocator: std.mem.Allocator, length: usize) !void {
var foo = try allocator.alloc(u8, length);
defer allocator.free(foo);
var bar = try allocator.alloc(u8, length);
defer allocator.free(bar);
}
pub fn checkAllAllocationFailures( backing_allocator: std.mem.Allocator, comptime test_fn: anytype, extra_args: CheckAllAllocationFailuresExtraArgs(@TypeOf(test_fn)), ) !void
参数
backing_allocator: std.mem.Allocator
extra_args: CheckAllAllocationFailuresExtraArgs(@TypeOf(test_fn))
std.testing.CheckAllAllocationFailuresExtraArgs
类型函数
fn CheckAllAllocationFailuresExtraArgs(comptime TestFn: type) type
参数
TestFn: type
std.testing.environ
变量
Environ
std.testing.Environ
别名
别名目标 std.process.Environ
std.testing.expect
函数
此函数仅用于测试。
ok 为 false 时,返回测试失败错误。
pub fn expect(ok: bool) !void
参数
ok: bool
std.testing.expectApproxEqAbs
函数
此函数仅用于测试。当实际值与
预期值不近似相等时,向标准错误输出诊断信息,
明确展示二者差异,然后返回测试失败错误。
容差参数的更多说明参见 math.approxEqAbs。
类型必须为浮点类型。
actual 和 expected 通过同级类型解析强制转换为公共类型。
pub inline fn expectApproxEqAbs(expected: anytype, actual: anytype, tolerance: anytype) !void
用法示例
test expectApproxEqAbs {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const pos_x: T = 12.0;
const pos_y: T = 12.06;
const neg_x: T = -12.0;
const neg_y: T = -12.06;
try expectApproxEqAbs(pos_x, pos_y, 0.1);
try expectApproxEqAbs(neg_x, neg_y, 0.1);
}
}
std.testing.expectApproxEqAbsInner
函数
fn expectApproxEqAbsInner(comptime T: type, expected: T, actual: T, tolerance: T) !void
参数
T: type
expected: T
actual: T
tolerance: T
std.testing.expectApproxEqRel
函数
此函数仅用于测试。当实际值与
预期值不近似相等时,向标准错误输出诊断信息,
明确展示二者差异,然后返回测试失败错误。
容差参数的更多说明参见 math.approxEqRel。
类型必须为浮点类型。
actual 和 expected 通过同级类型解析强制转换为公共类型。
pub inline fn expectApproxEqRel(expected: anytype, actual: anytype, tolerance: anytype) !void
用法示例
test expectApproxEqRel {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime math.floatEps(T);
const sqrt_eps_value = comptime @sqrt(eps_value);
const pos_x: T = 12.0;
const pos_y: T = pos_x + 2 * eps_value;
const neg_x: T = -12.0;
const neg_y: T = neg_x - 2 * eps_value;
try expectApproxEqRel(pos_x, pos_y, sqrt_eps_value);
try expectApproxEqRel(neg_x, neg_y, sqrt_eps_value);
}
}
std.testing.expectApproxEqRelInner
函数
fn expectApproxEqRelInner(comptime T: type, expected: T, actual: T, tolerance: T) !void
参数
T: type
expected: T
actual: T
tolerance: T
std.testing.expectEqual
函数
此函数仅用于测试。两个值不相等时,
向标准错误输出诊断信息,明确展示二者差异,
然后返回测试失败错误。
actual 和 expected 通过同级类型解析强制转换为公共类型。
pub inline fn expectEqual(expected: anytype, actual: anytype) !void
std.testing.expectEqualDeep
函数
此函数仅用于测试。若两个值不是
深度相等,则向 stderr 输出诊断,准确指出差异,
然后返回测试失败错误。
actual 和 expected 通过同级类型解析强制转换为公共类型。
深度相等定义如下:
原始类型使用 == 运算符相等时,视为深度相等。
结构体值的对应字段深度相等时,视为深度相等。
数组、切片、向量等容器类型的对应元素深度相等时,视为深度相等。
指针值所指向的值深度相等时,视为深度相等。
注意:支持 std.SinglyLinkedList 等自引用结构体, 但容器包含指向自身的指针时,可能导致无限递归或栈溢出。
pub inline fn expectEqualDeep(expected: anytype, actual: anytype) error{TestExpectedEqual}!void
错误
- TestExpectedEqual
std.testing.expectEqualDeepInner
函数
fn expectEqualDeepInner(comptime T: type, expected: T, actual: T) error{TestExpectedEqual}!void
参数
T: type
expected: T
actual: T
错误
- TestExpectedEqual
std.testing.expectEqualInner
函数
fn expectEqualInner(comptime T: type, expected: T, actual: T) !void
参数
T: type
expected: T
actual: T
std.testing.expectEqualSentinel
函数
此函数仅用于测试。两个切片或数组不相等,
或其哨兵(若存在)不相同时,会向 stderr 输出诊断,准确指出
差异,并以红色高亮,然后返回测试失败错误。
诊断输出部分依赖 expectEquaSlices。
pub fn expectEqualSentinel(comptime T: type, comptime sentinel: T, expected: [:sentinel]const T, actual: [:sentinel]const T) !void
参数
T: type
sentinel: T
expected: [:sentinel]const T
actual: [:sentinel]const T
std.testing.expectEqualSlices
函数
此函数仅供测试使用。当两个切片 不相等时,它会向标准错误输出诊断信息,精确展示差异 (以红色突出显示),随后返回测试 失败错误。
pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const T) !void
参数
T: type
expected: []const T
actual: []const T
用法示例
test expectEqualSlices {
try expectEqualSlices(u8, "foo\x00", "foo\x00");
try expectEqualSlices(u16, &[_]u16{ 100, 200, 300, 400 }, &[_]u16{ 100, 200, 300, 400 });
const E = enum { foo, bar };
const S = struct {
v: E,
};
try expectEqualSlices(
S,
&[_]S{ .{ .v = .foo }, .{ .v = .bar }, .{ .v = .foo }, .{ .v = .bar } },
&[_]S{ .{ .v = .foo }, .{ .v = .bar }, .{ .v = .foo }, .{ .v = .bar } },
);
}
std.testing.expectEqualStrings
函数
向标准错误打印诊断信息,说明它们为何不相等,然后返回错误。
pub fn expectEqualStrings(expected: []const u8, actual: []const u8) !void
参数
expected: []const u8
actual: []const u8
用法示例
test expectEqualStrings {
try expectEqualStrings("foo", "foo");
}
std.testing.expectError
函数
此函数仅供测试使用。若 actual_error_union 不是
expected_error,则向 stderr 打印诊断信息,再返回测试失败错误。
pub fn expectError(expected_error: anyerror, actual_error_union: anytype) !void
参数
expected_error: anyerror
用法示例
test expectError {
const actualErrorUnion = returnErrorUnion();
try expectError(error.Expected, actualErrorUnion);
}
std.testing.expectFmt
函数
此函数仅供测试使用。当模板及其参数的格式化结果
不等于预期文本时,它向标准错误输出诊断信息,展示
差异,随后返回错误。它依赖 expectEqualStrings 打印
诊断信息。
pub fn expectFmt(expected: []const u8, comptime template: []const u8, args: anytype) !void
参数
expected: []const u8
template: []const u8
std.testing.expectStringEndsWith
函数
此函数仅供测试使用。若 actual 的结尾与 expected_ends_with
不相等,则向 stderr 打印诊断信息,展示差异,随后返回错误。
pub fn expectStringEndsWith(actual: []const u8, expected_ends_with: []const u8) !void
参数
actual: []const u8
expected_ends_with: []const u8
用法示例
test expectStringEndsWith {
try expectStringEndsWith("foobar", "bar");
}
std.testing.expectStringStartsWith
函数
此函数仅供测试使用。若 actual 的开头与 expected_starts_with
不相等,则向 stderr 打印诊断信息,展示差异,随后返回错误。
pub fn expectStringStartsWith(actual: []const u8, expected_starts_with: []const u8) !void
参数
actual: []const u8
expected_starts_with: []const u8
用法示例
test expectStringStartsWith {
try expectStringStartsWith("foobar", "foo");
}
std.testing.f
函数
fn f(ally: std.mem.Allocator, params: struct { foo_len: u32, bar_len: u32, }) !void
参数
std.testing.f
函数
fn f(gpa: std.mem.Allocator) !void
参数
std.testing.failEqualSlices
函数
fn failEqualSlices( comptime T: type, expected: []const T, actual: []const T, diff_index: usize, w: *Io.Writer, terminal_mode: Io.Terminal.Mode, ) !void
参数
std.testing.failing_allocator
常量
std.testing.failing_allocator_instance
变量
std.testing.FailingAllocator
别名
std.testing.failPrint
函数
打印测试失败信息的辅助函数。
pub fn failPrint(comptime fmt: []const u8, args: anytype) void
参数
fmt: []const u8
std.testing.failPrintIndicatorLine
函数
打印测试失败信息的辅助函数。
pub fn failPrintIndicatorLine(source: []const u8, indicator_index: usize) void
参数
source: []const u8
indicator_index: usize
std.testing.failPrintLine
函数
打印测试失败信息的辅助函数。
pub fn failPrintLine(line: []const u8) void
参数
line: []const u8
std.testing.failPrintWithVisibleNewlines
函数
打印测试失败信息的辅助函数。
pub fn failPrintWithVisibleNewlines(source: []const u8) void
参数
source: []const u8
std.testing.foo
函数
fn foo() void
std.testing.format
函数
pub fn format(self: @This(), writer: *Io.Writer) !void
参数
std.testing.fuzz
函数
内联以避免覆盖率插桩。
pub inline fn fuzz( context: anytype, comptime testOne: fn (context: @TypeOf(context), smith: *Smith) anyerror!void, options: FuzzInputOptions, ) anyerror!void
参数
testOne: fn (context: @TypeOf(context), smith: *Smith) anyerror!void
options: FuzzInputOptions
std.testing.FuzzInputOptions
容器
字段
corpus: []const []const u8 = &.{}
std.testing.io
常量
std.testing.Io
别名
别名目标 std.Io
std.testing.io_instance
变量
Io.Threaded
std.testing.log_level
变量
std.testing.math
别名
别名目标 std.math
std.testing.random_seed
变量
为单元测试提供确定性随机数据。 启动时初始化,此后只读。
u32
std.testing.Reader
容器
字段
std.testing.Reader.Call
容器
字段
buffer: []const u8
std.testing.Reader.init
函数
pub fn init(buffer: []u8, calls: []const Call) Reader
参数
buffer: []u8
calls: []const Call
std.testing.Reader.stream
函数
fn stream(io_r: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize
参数
错误
std.testing.ReaderIndirect
容器
字段
std.testing.ReaderIndirect.init
函数
pub fn init(in: *Io.Reader, buffer: []u8) ReaderIndirect
参数
std.testing.ReaderIndirect.readVec
函数
fn readVec(r: *Io.Reader, _: [][]u8) Io.Reader.Error!usize
参数
错误
- EndOfStream
- ReadFailed
详细诊断参见
Reader的实现。
std.testing.ReaderIndirect.stream
函数
fn stream(r: *Io.Reader, _: *Io.Writer, _: Io.Limit) Io.Reader.StreamError!usize
参数
错误
std.testing.ReaderIndirect.streamInner
函数
fn streamInner(r: *Io.Reader) Io.Reader.Error!void
参数
错误
- EndOfStream
- ReadFailed
详细诊断参见
Reader的实现。
std.testing.refAllDecls
函数
给定类型,引用其内部所有声明,使语义分析器能够分析它们。
pub fn refAllDecls(comptime T: type) void
参数
T: type
std.testing.returnErrorUnion
函数
fn returnErrorUnion() !u8
std.testing.SliceDiffer
类型函数
fn SliceDiffer(comptime T: type) type
参数
T: type
字段
std.testing.SliceDiffer.Self
别名
std.testing.SliceDiffer.write
函数
pub fn write(self: Self, writer: *Io.Writer) !void
参数
std.testing.Smith
别名
别名目标 std.testing.Smith
std.testing.std
别名
别名目标 std
std.testing.tmpDir
函数
pub fn tmpDir(opts: Io.Dir.OpenOptions) TmpDir
参数
opts: Io.Dir.OpenOptions
std.testing.TmpDir
容器
字段
std.testing.TmpDir.cleanup
函数
pub fn cleanup(self: *TmpDir) void
参数
self: *TmpDir
std.testing.TmpDir.parent_dir_path
常量
已弃用。
[]const u8
std.testing.TmpDir.random_bytes_count
常量
std.testing.TmpDir.sub_path_len
常量
std.testing.WriterIndirect
容器
字段
std.testing.WriterIndirect.drain
函数
fn drain(w: *Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.testing.WriterIndirect.init
函数
pub fn init(out: *Io.Writer, buffer: []u8) WriterIndirect
参数
源码
std/testing.zig
const builtin = @import("builtin");
const std = @import("std.zig");
const Io = std.Io;
const Environ = std.process.Environ;
const assert = std.debug.assert;
const math = std.math;
/// 为单元测试提供确定性随机数据。
/// 启动时初始化,此后只读。
pub var random_seed: u32 = 0;
pub const FailingAllocator = @import("testing/FailingAllocator.zig");
pub const failing_allocator = failing_allocator_instance.allocator();
var failing_allocator_instance = FailingAllocator.init(base_allocator_instance.allocator(), .{
.fail_index = 0,
});
var base_allocator_instance = std.heap.FixedBufferAllocator.init("");
pub var allocator_instance: std.heap.SafeAllocator = undefined;
pub const allocator = if (builtin.is_test) allocator_instance.allocator() else @compileError("not testing");
pub var io_instance: Io.Threaded = undefined;
pub const io = if (builtin.is_test) io_instance.io() else @compileError("not testing");
pub var environ: Environ = if (builtin.is_test) undefined else @compileError("not testing");
/// TODO https://github.com/ziglang/zig/issues/5738
pub var log_level = std.log.Level.warn;
// 对简单后端,禁用测试中的打印。
pub const backend_can_print = switch (builtin.zig_backend) {
.stage2_aarch64,
.stage2_loongarch,
.stage2_powerpc,
.stage2_riscv64,
.stage2_spirv,
=> false,
else => true,
};
/// 打印测试失败信息的辅助函数。
pub fn failPrint(comptime fmt: []const u8, args: anytype) void {
if (@inComptime()) {
@compileError(std.fmt.comptimePrint(fmt, args));
} else if (backend_can_print) {
std.debug.print(fmt, args);
}
}
/// 此函数仅用于测试。两个值不相等时,
/// 向标准错误输出诊断信息,明确展示二者差异,
/// 然后返回测试失败错误。
/// `actual` 和 `expected` 通过同级类型解析强制转换为公共类型。
pub inline fn expectEqual(expected: anytype, actual: anytype) !void {
const T = @TypeOf(expected, actual);
return expectEqualInner(T, expected, actual);
}
fn expectEqualInner(comptime T: type, expected: T, actual: T) !void {
switch (@typeInfo(@TypeOf(actual))) {
.noreturn,
.@"opaque",
.spirv,
.frame,
.@"anyframe",
=> @compileError("value of type " ++ @typeName(@TypeOf(actual)) ++ " encountered"),
.undefined,
.null,
.void,
=> return,
.type => {
if (actual != expected) {
failPrint("expected type {s}, found type {s}\n", .{ @typeName(expected), @typeName(actual) });
return error.TestExpectedEqual;
}
},
.bool,
.int,
.float,
.comptime_float,
.comptime_int,
.enum_literal,
.@"enum",
.@"fn",
.error_set,
=> {
if (actual != expected) {
failPrint("expected {any}, found {any}\n", .{ expected, actual });
return error.TestExpectedEqual;
}
},
.pointer => |pointer| {
switch (pointer.size) {
.one, .many, .c => {
if (actual != expected) {
failPrint("expected {*}, found {*}\n", .{ expected, actual });
return error.TestExpectedEqual;
}
},
.slice => {
if (actual.ptr != expected.ptr) {
failPrint("expected slice ptr {*}, found {*}\n", .{ expected.ptr, actual.ptr });
return error.TestExpectedEqual;
}
if (actual.len != expected.len) {
failPrint("expected slice len {}, found {}\n", .{ expected.len, actual.len });
return error.TestExpectedEqual;
}
},
}
},
.array => |array| try expectEqualSlices(array.child, &expected, &actual),
.vector => |info| {
const expect_array: [info.len]info.child = expected;
const actual_array: [info.len]info.child = actual;
try expectEqualSlices(info.child, &expect_array, &actual_array);
},
.@"struct" => |@"struct"| {
inline for (@"struct".field_names) |field_name| {
try expectEqual(@field(expected, field_name), @field(actual, field_name));
}
},
.@"union" => |@"union"| if (@"union".backing_integer) |Int| {
try expectEqual(@as(Int, @bitCast(expected)), @as(Int, @bitCast(actual)));
} else switch (@"union".layout) {
.@"packed" => {
const Int = @Int(.unsigned, @bitSizeOf(T));
try expectEqual(@as(Int, @bitCast(expected)), @as(Int, @bitCast(actual)));
},
.@"extern" => {
const first_size = @bitSizeOf(@"union".field_types[0]);
inline for (@"union".field_types) |field_type| {
if (@bitSizeOf(field_type) != first_size) {
@compileError("Unable to compare extern unions with varying field sizes for type " ++ @typeName(T));
}
}
const FieldInt = @Int(.unsigned, first_size);
const expected_field = @field(expected, @"union".field_names[0]);
const actual_field = @field(actual, @"union".field_names[0]);
return expectEqual(
@as(FieldInt, @bitCast(expected_field)),
@as(FieldInt, @bitCast(actual_field)),
);
},
.auto => {
const Tag = @"union".tag_type orelse @compileError("byteSwapAllFields expects packed, extern, or tagged union");
try expectEqual(@as(Tag, expected), @as(Tag, actual));
switch (expected) {
inline else => |expected_payload, tag| {
const actual_payload = @field(actual, @tagName(tag));
try expectEqual(expected_payload, actual_payload);
},
}
},
},
.optional => {
if (expected) |expected_payload| {
if (actual) |actual_payload| {
try expectEqual(expected_payload, actual_payload);
} else {
failPrint("expected {any}, found null\n", .{expected_payload});
return error.TestExpectedEqual;
}
} else {
if (actual) |actual_payload| {
failPrint("expected null, found {any}\n", .{actual_payload});
return error.TestExpectedEqual;
}
}
},
.error_union => {
if (expected) |expected_payload| {
if (actual) |actual_payload| {
try expectEqual(expected_payload, actual_payload);
} else |actual_err| {
failPrint("expected {any}, found {}\n", .{ expected_payload, actual_err });
return error.TestExpectedEqual;
}
} else |expected_err| {
if (actual) |actual_payload| {
failPrint("expected {}, found {any}\n", .{ expected_err, actual_payload });
return error.TestExpectedEqual;
} else |actual_err| {
try expectEqual(expected_err, actual_err);
}
}
},
}
}
test "expectEqual union(enum)" {
const T = union(enum) {
a: i32,
b: f32,
};
const a10 = T{ .a = 10 };
try expectEqual(a10, a10);
}
test "expectEqual union with comptime-only field" {
const U = union(enum) {
a: void,
b: void,
c: comptime_int,
};
try expectEqual(U{ .a = {} }, .a);
}
test "expectEqual nested array" {
const a = [2][2]f32{
[_]f32{ 1.0, 0.0 },
[_]f32{ 0.0, 1.0 },
};
const b = [2][2]f32{
[_]f32{ 1.0, 0.0 },
[_]f32{ 0.0, 1.0 },
};
try expectEqual(a, b);
}
test "expectEqual vector" {
const a: @Vector(4, u32) = @splat(4);
const b: @Vector(4, u32) = @splat(4);
try expectEqual(a, b);
}
test "expectEqual null" {
const a = .{null};
const b = @Vector(1, ?*u8){null};
try expectEqual(a, b);
}
/// 此函数仅用于测试。当实际值与
/// 预期值不近似相等时,向标准错误输出诊断信息,
/// 明确展示二者差异,然后返回测试失败错误。
/// 容差参数的更多说明参见 `math.approxEqAbs`。
/// 类型必须为浮点类型。
/// `actual` 和 `expected` 通过同级类型解析强制转换为公共类型。
pub inline fn expectApproxEqAbs(expected: anytype, actual: anytype, tolerance: anytype) !void {
const T = @TypeOf(expected, actual, tolerance);
return expectApproxEqAbsInner(T, expected, actual, tolerance);
}
fn expectApproxEqAbsInner(comptime T: type, expected: T, actual: T, tolerance: T) !void {
switch (@typeInfo(T)) {
.float => if (!math.approxEqAbs(T, expected, actual, tolerance)) {
failPrint("actual {}, not within absolute tolerance {} of expected {}\n", .{ actual, tolerance, expected });
return error.TestExpectedApproxEqAbs;
},
.comptime_float => @compileError("Cannot approximately compare two comptime_float values"),
else => @compileError("Unable to compare non floating point values"),
}
}
test expectApproxEqAbs {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const pos_x: T = 12.0;
const pos_y: T = 12.06;
const neg_x: T = -12.0;
const neg_y: T = -12.06;
try expectApproxEqAbs(pos_x, pos_y, 0.1);
try expectApproxEqAbs(neg_x, neg_y, 0.1);
}
}
/// 此函数仅用于测试。当实际值与
/// 预期值不近似相等时,向标准错误输出诊断信息,
/// 明确展示二者差异,然后返回测试失败错误。
/// 容差参数的更多说明参见 `math.approxEqRel`。
/// 类型必须为浮点类型。
/// `actual` 和 `expected` 通过同级类型解析强制转换为公共类型。
pub inline fn expectApproxEqRel(expected: anytype, actual: anytype, tolerance: anytype) !void {
const T = @TypeOf(expected, actual, tolerance);
return expectApproxEqRelInner(T, expected, actual, tolerance);
}
fn expectApproxEqRelInner(comptime T: type, expected: T, actual: T, tolerance: T) !void {
switch (@typeInfo(T)) {
.float => if (!math.approxEqRel(T, expected, actual, tolerance)) {
failPrint("actual {}, not within relative tolerance {} of expected {}\n", .{ actual, tolerance, expected });
return error.TestExpectedApproxEqRel;
},
.comptime_float => @compileError("Cannot approximately compare two comptime_float values"),
else => @compileError("Unable to compare non floating point values"),
}
}
test expectApproxEqRel {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime math.floatEps(T);
const sqrt_eps_value = comptime @sqrt(eps_value);
const pos_x: T = 12.0;
const pos_y: T = pos_x + 2 * eps_value;
const neg_x: T = -12.0;
const neg_y: T = neg_x - 2 * eps_value;
try expectApproxEqRel(pos_x, pos_y, sqrt_eps_value);
try expectApproxEqRel(neg_x, neg_y, sqrt_eps_value);
}
}
/// 此函数仅供测试使用。当两个切片
/// 不相等时,它会向标准错误输出诊断信息,精确展示差异
/// (以红色突出显示),随后返回测试
/// 失败错误。
pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const T) !void {
const diff_index: usize = diff_index: {
const shortest = @min(expected.len, actual.len);
var index: usize = 0;
while (index < shortest) : (index += 1) {
if (!std.meta.eql(actual[index], expected[index])) break :diff_index index;
}
break :diff_index if (expected.len == actual.len) return else shortest;
};
if (!backend_can_print) return error.TestExpectedEqual;
// 这里有意使用调试 Io 实例,而不使用测试 Io 实例。
const stderr = std.debug.lockStderr(&.{});
defer std.debug.unlockStderr();
const w = &stderr.file_writer.interface;
failEqualSlices(T, expected, actual, diff_index, w, stderr.terminal_mode) catch {};
return error.TestExpectedEqual;
}
fn failEqualSlices(
comptime T: type,
expected: []const T,
actual: []const T,
diff_index: usize,
w: *Io.Writer,
terminal_mode: Io.Terminal.Mode,
) !void {
try w.print("slices differ. first difference occurs at index {d} (0x{X})\n", .{ diff_index, diff_index });
// TODO: 是否应允许调用方配置此项?
const max_lines: usize = 16;
const max_window_size: usize = if (T == u8) max_lines * 16 else max_lines;
// 从首个差异稍前的位置开始,对每个输入最多打印 max_window_size 项,
// 以提供少量上下文。
var window_start: usize = 0;
if (@max(actual.len, expected.len) > max_window_size) {
const alignment = if (T == u8) 16 else 2;
window_start = std.mem.alignBackward(usize, diff_index - @min(diff_index, alignment), alignment);
}
const expected_window = expected[window_start..@min(expected.len, window_start + max_window_size)];
const expected_truncated = window_start + expected_window.len < expected.len;
const actual_window = actual[window_start..@min(actual.len, window_start + max_window_size)];
const actual_truncated = window_start + actual_window.len < actual.len;
var differ = if (T == u8) BytesDiffer{
.expected = expected_window,
.actual = actual_window,
.terminal_mode = terminal_mode,
} else SliceDiffer(T){
.start_index = window_start,
.expected = expected_window,
.actual = actual_window,
.terminal_mode = terminal_mode,
};
// 对于 u8 切片,以十六进制输出索引,因为它更可能是二进制数据,
// 此时这种表示通常更有用。
const index_fmt = if (T == u8) "0x{X}" else "{}";
try w.print("\n============ expected this output: ============= len: {} (0x{X})\n\n", .{ expected.len, expected.len });
if (window_start > 0) {
if (T == u8) {
try w.print("... truncated, start index: " ++ index_fmt ++ " ...\n", .{window_start});
} else {
try w.print("... truncated ...\n", .{});
}
}
differ.write(w) catch {};
if (expected_truncated) {
const end_offset = window_start + expected_window.len;
const num_missing_items = expected.len - (window_start + expected_window.len);
if (T == u8) {
try w.print("... truncated, indexes [" ++ index_fmt ++ "..] not shown, remaining bytes: " ++ index_fmt ++ " ...\n", .{ end_offset, num_missing_items });
} else {
try w.print("... truncated, remaining items: " ++ index_fmt ++ " ...\n", .{num_missing_items});
}
}
// 现在交换预期值与实际值,再次打印
differ.expected = actual_window;
differ.actual = expected_window;
try w.print("\n============= instead found this: ============== len: {} (0x{X})\n\n", .{ actual.len, actual.len });
if (window_start > 0) {
if (T == u8) {
try w.print("... truncated, start index: " ++ index_fmt ++ " ...\n", .{window_start});
} else {
try w.print("... truncated ...\n", .{});
}
}
differ.write(w) catch {};
if (actual_truncated) {
const end_offset = window_start + actual_window.len;
const num_missing_items = actual.len - (window_start + actual_window.len);
if (T == u8) {
try w.print("... truncated, indexes [" ++ index_fmt ++ "..] not shown, remaining bytes: " ++ index_fmt ++ " ...\n", .{ end_offset, num_missing_items });
} else {
try w.print("... truncated, remaining items: " ++ index_fmt ++ " ...\n", .{num_missing_items});
}
}
try w.print("\n================================================\n\n", .{});
return error.TestExpectedEqual;
}
fn SliceDiffer(comptime T: type) type {
return struct {
start_index: usize,
expected: []const T,
actual: []const T,
terminal_mode: Io.Terminal.Mode,
const Self = @This();
pub fn write(self: Self, writer: *Io.Writer) !void {
const t: Io.Terminal = .{ .writer = writer, .mode = self.terminal_mode };
for (self.expected, 0..) |value, i| {
const full_index = self.start_index + i;
const diff = if (i < self.actual.len) !std.meta.eql(self.actual[i], value) else true;
if (diff) try t.setColor(.red);
if (@typeInfo(T) == .pointer) {
try writer.print("[{}]{*}: {any}\n", .{ full_index, value, value });
} else {
try writer.print("[{}]: {any}\n", .{ full_index, value });
}
if (diff) try t.setColor(.reset);
}
}
};
}
const BytesDiffer = struct {
expected: []const u8,
actual: []const u8,
terminal_mode: Io.Terminal.Mode,
pub fn write(self: BytesDiffer, writer: *Io.Writer) !void {
var expected_iterator = std.mem.window(u8, self.expected, 16, 16);
var row: usize = 0;
while (expected_iterator.next()) |chunk| {
// 避免对每块计算两次差值
var diffs: std.bit_set.Integer(16) = .{ .mask = 0 };
for (chunk, 0..) |byte, col| {
const absolute_byte_index = col + row * 16;
const diff = if (absolute_byte_index < self.actual.len) self.actual[absolute_byte_index] != byte else true;
if (diff) diffs.set(col);
try self.writeDiff(writer, "{X:0>2} ", .{byte}, diff);
if (col == 7) try writer.writeByte(' ');
}
try writer.writeByte(' ');
if (chunk.len < 16) {
var missing_columns = (16 - chunk.len) * 3;
if (chunk.len < 8) missing_columns += 1;
try writer.splatByteAll(' ', missing_columns);
}
for (chunk, 0..) |byte, col| {
const diff = diffs.isSet(col);
if (std.ascii.isPrint(byte)) {
try self.writeDiff(writer, "{c}", .{byte}, diff);
} else {
// TODO: 修复 https://github.com/ziglang/zig/issues/7600 后移除此 `if`
if (self.terminal_mode == .windows_api) {
try self.writeDiff(writer, ".", .{}, diff);
continue;
}
// 将一些常见控制码打印为可见的 Unicode 符号。
// 不对所有控制码都这样处理,因为除 Zig 提供转义序列的控制码之外,
// 大多数控制码打印为符号的用处可能不大。
switch (byte) {
'\n' => try self.writeDiff(writer, "␊", .{}, diff),
'\r' => try self.writeDiff(writer, "␍", .{}, diff),
'\t' => try self.writeDiff(writer, "␉", .{}, diff),
else => try self.writeDiff(writer, ".", .{}, diff),
}
}
}
try writer.writeByte('\n');
row += 1;
}
}
fn terminal(self: *const BytesDiffer, writer: *Io.Writer) Io.Terminal {
return .{ .writer = writer, .mode = self.terminal_mode };
}
fn writeDiff(self: BytesDiffer, writer: *Io.Writer, comptime fmt: []const u8, args: anytype, diff: bool) !void {
if (diff) try self.terminal(writer).setColor(.red);
try writer.print(fmt, args);
if (diff) try self.terminal(writer).setColor(.reset);
}
};
test expectEqualSlices {
try expectEqualSlices(u8, "foo\x00", "foo\x00");
try expectEqualSlices(u16, &[_]u16{ 100, 200, 300, 400 }, &[_]u16{ 100, 200, 300, 400 });
const E = enum { foo, bar };
const S = struct {
v: E,
};
try expectEqualSlices(
S,
&[_]S{ .{ .v = .foo }, .{ .v = .bar }, .{ .v = .foo }, .{ .v = .bar } },
&[_]S{ .{ .v = .foo }, .{ .v = .bar }, .{ .v = .foo }, .{ .v = .bar } },
);
}
/// 此函数仅用于测试。两个切片或数组不相等,
/// 或其哨兵(若存在)不相同时,会向 stderr 输出诊断,准确指出
/// 差异,并以红色高亮,然后返回测试失败错误。
/// 诊断输出部分依赖 `expectEquaSlices`。
pub fn expectEqualSentinel(comptime T: type, comptime sentinel: T, expected: [:sentinel]const T, actual: [:sentinel]const T) !void {
try expectEqualSlices(T, expected, actual);
const expected_value_sentinel = blk: {
switch (@typeInfo(@TypeOf(expected))) {
.pointer => {
break :blk expected[expected.len];
},
.array => |array_info| {
const indexable_outside_of_bounds = @as([]const array_info.child, &expected);
break :blk indexable_outside_of_bounds[indexable_outside_of_bounds.len];
},
else => {},
}
};
const actual_value_sentinel = blk: {
switch (@typeInfo(@TypeOf(actual))) {
.pointer => {
break :blk actual[actual.len];
},
.array => |array_info| {
const indexable_outside_of_bounds = @as([]const array_info.child, &actual);
break :blk indexable_outside_of_bounds[indexable_outside_of_bounds.len];
},
else => {},
}
};
if (!std.meta.eql(sentinel, expected_value_sentinel)) {
failPrint("expectEqualSentinel: 'expected' sentinel in memory is different from its type sentinel. type sentinel {}, in memory sentinel {}\n", .{ sentinel, expected_value_sentinel });
return error.TestExpectedEqual;
}
if (!std.meta.eql(sentinel, actual_value_sentinel)) {
failPrint("expectEqualSentinel: 'actual' sentinel in memory is different from its type sentinel. type sentinel {}, in memory sentinel {}\n", .{ sentinel, actual_value_sentinel });
return error.TestExpectedEqual;
}
}
/// 此函数仅用于测试。
/// `ok` 为 false 时,返回测试失败错误。
pub fn expect(ok: bool) !void {
if (!ok) return error.TestUnexpectedResult;
}
pub const TmpDir = struct {
dir: Io.Dir,
parent_dir: Io.Dir,
sub_path: [sub_path_len]u8,
const random_bytes_count = 12;
const sub_path_len = std.base64.url_safe.Encoder.calcSize(random_bytes_count);
/// 已弃用。
pub const parent_dir_path: []const u8 = ".zig-cache" ++ std.fs.path.sep_str ++ "tmp";
pub fn cleanup(self: *TmpDir) void {
self.dir.close(io);
self.parent_dir.deleteTree(io, &self.sub_path) catch {};
self.parent_dir.close(io);
self.* = undefined;
}
};
pub fn tmpDir(opts: Io.Dir.OpenOptions) TmpDir {
comptime assert(builtin.is_test);
var random_bytes: [TmpDir.random_bytes_count]u8 = undefined;
io.random(&random_bytes);
var sub_path: [TmpDir.sub_path_len]u8 = undefined;
_ = std.base64.url_safe.Encoder.encode(&sub_path, &random_bytes);
const cwd = Io.Dir.cwd();
var cache_dir = cwd.createDirPathOpen(io, ".zig-cache", .{}) catch
@panic("unable to make tmp dir for testing: unable to make and open .zig-cache dir");
defer cache_dir.close(io);
const parent_dir = cache_dir.createDirPathOpen(io, "tmp", .{}) catch
@panic("unable to make tmp dir for testing: unable to make and open .zig-cache/tmp dir");
const dir = parent_dir.createDirPathOpen(io, &sub_path, .{ .open_options = opts }) catch
@panic("unable to make tmp dir for testing: unable to make and open the tmp dir");
return .{
.dir = dir,
.parent_dir = parent_dir,
.sub_path = sub_path,
};
}
/// 此函数仅供测试使用。若 `actual_error_union` 不是
/// `expected_error`,则向 stderr 打印诊断信息,再返回测试失败错误。
pub fn expectError(expected_error: anyerror, actual_error_union: anytype) !void {
if (actual_error_union) |actual_payload| {
failPrint("expected error.{s}, found {any}\n", .{ @errorName(expected_error), actual_payload });
return error.TestExpectedError;
} else |actual_error| {
if (expected_error != actual_error) {
failPrint("expected error.{s}, found error.{s}\n", .{
@errorName(expected_error),
@errorName(actual_error),
});
return error.TestUnexpectedError;
}
}
}
fn returnErrorUnion() !u8 {
return error.Expected;
}
test expectError {
const actualErrorUnion = returnErrorUnion();
try expectError(error.Expected, actualErrorUnion);
}
/// 此函数仅供测试使用。当模板及其参数的格式化结果
/// 不等于预期文本时,它向标准错误输出诊断信息,展示
/// 差异,随后返回错误。它依赖 `expectEqualStrings` 打印
/// 诊断信息。
pub fn expectFmt(expected: []const u8, comptime template: []const u8, args: anytype) !void {
if (@inComptime()) {
var buffer: [std.fmt.count(template, args)]u8 = undefined;
return expectEqualStrings(expected, try std.mem.print(&buffer, template, args));
}
const actual = try std.fmt.allocPrint(allocator, template, args);
defer allocator.free(actual);
return expectEqualStrings(expected, actual);
}
// 此函数仅用于测试。当两个字符串不相等时,
/// 向标准错误打印诊断信息,说明它们为何不相等,然后返回错误。
pub fn expectEqualStrings(expected: []const u8, actual: []const u8) !void {
if (std.mem.findDiff(u8, actual, expected)) |diff_index| {
if (@inComptime()) {
@compileError(std.fmt.comptimePrint("\nexpected:\n{s}\nfound:\n{s}\ndifference starts at index {d}", .{
expected, actual, diff_index,
}));
}
failPrint("\n====== expected this output: =========\n", .{});
failPrintWithVisibleNewlines(expected);
failPrint("\n======== instead found this: =========\n", .{});
failPrintWithVisibleNewlines(actual);
failPrint("\n======================================\n", .{});
var diff_line_number: usize = 1;
for (expected[0..diff_index]) |value| {
if (value == '\n') diff_line_number += 1;
}
failPrint("First difference occurs on line {d}:\n", .{diff_line_number});
failPrint("expected:\n", .{});
failPrintIndicatorLine(expected, diff_index);
failPrint("found:\n", .{});
failPrintIndicatorLine(actual, diff_index);
return error.TestExpectedEqual;
}
}
test expectEqualStrings {
try expectEqualStrings("foo", "foo");
}
/// 此函数仅供测试使用。若 `actual` 的开头与 `expected_starts_with`
/// 不相等,则向 stderr 打印诊断信息,展示差异,随后返回错误。
pub fn expectStringStartsWith(actual: []const u8, expected_starts_with: []const u8) !void {
if (std.mem.startsWith(u8, actual, expected_starts_with))
return;
const shortened_actual = if (actual.len >= expected_starts_with.len)
actual[0..expected_starts_with.len]
else
actual;
failPrint("\n====== expected to start with: =========\n", .{});
failPrintWithVisibleNewlines(expected_starts_with);
failPrint("\n====== instead started with: ===========\n", .{});
failPrintWithVisibleNewlines(shortened_actual);
failPrint("\n========= full output: ==============\n", .{});
failPrintWithVisibleNewlines(actual);
failPrint("\n======================================\n", .{});
return error.TestExpectedStartsWith;
}
test expectStringStartsWith {
try expectStringStartsWith("foobar", "foo");
}
/// 此函数仅供测试使用。若 `actual` 的结尾与 `expected_ends_with`
/// 不相等,则向 stderr 打印诊断信息,展示差异,随后返回错误。
pub fn expectStringEndsWith(actual: []const u8, expected_ends_with: []const u8) !void {
if (std.mem.endsWith(u8, actual, expected_ends_with))
return;
const shortened_actual = if (actual.len >= expected_ends_with.len)
actual[(actual.len - expected_ends_with.len)..]
else
actual;
failPrint("\n====== expected to end with: =========\n", .{});
failPrintWithVisibleNewlines(expected_ends_with);
failPrint("\n====== instead ended with: ===========\n", .{});
failPrintWithVisibleNewlines(shortened_actual);
failPrint("\n========= full output: ==============\n", .{});
failPrintWithVisibleNewlines(actual);
failPrint("\n======================================\n", .{});
return error.TestExpectedEndsWith;
}
test expectStringEndsWith {
try expectStringEndsWith("foobar", "bar");
}
/// 此函数仅用于测试。若两个值不是
/// 深度相等,则向 stderr 输出诊断,准确指出差异,
/// 然后返回测试失败错误。
/// `actual` 和 `expected` 通过同级类型解析强制转换为公共类型。
///
/// 深度相等定义如下:
/// 原始类型使用 `==` 运算符相等时,视为深度相等。
/// 结构体值的对应字段深度相等时,视为深度相等。
/// 数组、切片、向量等容器类型的对应元素深度相等时,视为深度相等。
/// 指针值所指向的值深度相等时,视为深度相等。
///
/// 注意:支持 std.SinglyLinkedList 等自引用结构体,
/// 但容器包含指向自身的指针时,可能导致无限递归或栈溢出。
pub inline fn expectEqualDeep(expected: anytype, actual: anytype) error{TestExpectedEqual}!void {
const T = @TypeOf(expected, actual);
return expectEqualDeepInner(T, expected, actual);
}
fn expectEqualDeepInner(comptime T: type, expected: T, actual: T) error{TestExpectedEqual}!void {
switch (@typeInfo(@TypeOf(actual))) {
.noreturn,
.@"opaque",
.spirv,
.frame,
.@"anyframe",
=> @compileError("value of type " ++ @typeName(@TypeOf(actual)) ++ " encountered"),
.undefined,
.null,
.void,
=> return,
.type => {
if (actual != expected) {
failPrint("expected type {s}, found type {s}\n", .{ @typeName(expected), @typeName(actual) });
return error.TestExpectedEqual;
}
},
.bool,
.int,
.float,
.comptime_float,
.comptime_int,
.enum_literal,
.@"enum",
.@"fn",
.error_set,
=> {
if (actual != expected) {
failPrint("expected {any}, found {any}\n", .{ expected, actual });
return error.TestExpectedEqual;
}
},
.pointer => |pointer| {
switch (pointer.size) {
// 无法确定这些指针指向什么,因此只能进行 `==` 检查。
.c, .many => {
if (actual != expected) {
failPrint("expected {*}, found {*}\n", .{ expected, actual });
return error.TestExpectedEqual;
}
},
.one => {
// 这些指针的长度是运行期值,因此最多只能执行 `==` 检查。
switch (@typeInfo(pointer.child)) {
.@"fn", .@"opaque" => {
if (actual != expected) {
failPrint("expected {*}, found {*}\n", .{ expected, actual });
return error.TestExpectedEqual;
}
},
else => try expectEqualDeep(expected.*, actual.*),
}
},
.slice => {
if (expected.len != actual.len) {
failPrint("Slice len not the same, expected {d}, found {d}\n", .{ expected.len, actual.len });
return error.TestExpectedEqual;
}
var i: usize = 0;
while (i < expected.len) : (i += 1) {
expectEqualDeep(expected[i], actual[i]) catch |e| {
failPrint("index {d} incorrect. expected {any}, found {any}\n", .{
i, expected[i], actual[i],
});
return e;
};
}
},
}
},
.array => {
if (expected.len != actual.len) {
failPrint("Array len not the same, expected {d}, found {d}\n", .{ expected.len, actual.len });
return error.TestExpectedEqual;
}
var i: usize = 0;
while (i < expected.len) : (i += 1) {
expectEqualDeep(expected[i], actual[i]) catch |e| {
failPrint("index {d} incorrect. expected {any}, found {any}\n", .{
i, expected[i], actual[i],
});
return e;
};
}
},
.vector => |info| {
if (info.len != @typeInfo(@TypeOf(actual)).vector.len) {
failPrint("Vector len not the same, expected {d}, found {d}\n", .{ info.len, @typeInfo(@TypeOf(actual)).vector.len });
return error.TestExpectedEqual;
}
inline for (0..info.len) |i| {
expectEqualDeep(expected[i], actual[i]) catch |e| {
failPrint("index {d} incorrect. expected {any}, found {any}\n", .{
i, expected[i], actual[i],
});
return e;
};
}
},
.@"struct" => |structType| {
inline for (structType.field_names) |field_name| {
expectEqualDeep(@field(expected, field_name), @field(actual, field_name)) catch |e| {
failPrint("Field {s} incorrect. expected {any}, found {any}\n", .{ field_name, @field(expected, field_name), @field(actual, field_name) });
return e;
};
}
},
.@"union" => |union_info| {
if (union_info.tag_type == null) {
@compileError("Unable to compare untagged union values for type " ++ @typeName(@TypeOf(actual)));
}
const Tag = std.meta.Tag(@TypeOf(expected));
const expectedTag = @as(Tag, expected);
const actualTag = @as(Tag, actual);
try expectEqual(expectedTag, actualTag);
// 仅当标签相等时才会到达此 switch
switch (expected) {
inline else => |val, tag| {
try expectEqualDeep(val, @field(actual, @tagName(tag)));
},
}
},
.optional => {
if (expected) |expected_payload| {
if (actual) |actual_payload| {
try expectEqualDeep(expected_payload, actual_payload);
} else {
failPrint("expected {any}, found null\n", .{expected_payload});
return error.TestExpectedEqual;
}
} else {
if (actual) |actual_payload| {
failPrint("expected null, found {any}\n", .{actual_payload});
return error.TestExpectedEqual;
}
}
},
.error_union => {
if (expected) |expected_payload| {
if (actual) |actual_payload| {
try expectEqualDeep(expected_payload, actual_payload);
} else |actual_err| {
failPrint("expected {any}, found {any}\n", .{ expected_payload, actual_err });
return error.TestExpectedEqual;
}
} else |expected_err| {
if (actual) |actual_payload| {
failPrint("expected {any}, found {any}\n", .{ expected_err, actual_payload });
return error.TestExpectedEqual;
} else |actual_err| {
try expectEqualDeep(expected_err, actual_err);
}
}
},
}
}
test "expectEqualDeep primitive type" {
try expectEqualDeep(1, 1);
try expectEqualDeep(true, true);
try expectEqualDeep(1.5, 1.5);
try expectEqualDeep(u8, u8);
try expectEqualDeep(error.Bad, error.Bad);
// 可选
{
const foo: ?u32 = 1;
const bar: ?u32 = 1;
try expectEqualDeep(foo, bar);
try expectEqualDeep(?u32, ?u32);
}
// 函数类型
{
const fnType = struct {
fn foo() void {
unreachable;
}
}.foo;
try expectEqualDeep(fnType, fnType);
}
// 带格式化器的枚举
{
const TestEnum = enum {
a,
b,
pub fn format(self: @This(), writer: *Io.Writer) !void {
try writer.writeAll(@tagName(self));
}
};
try expectEqualDeep(TestEnum.b, TestEnum.b);
}
}
test "expectEqualDeep pointer" {
try comptime expectEqualDeep(&1, &1);
try expectEqualDeep(&@as(u32, 1), &@as(u32, 1));
}
test "expectEqualDeep composite type" {
try expectEqualDeep("abc", "abc");
const s1: []const u8 = "abc";
const s2 = "abcd";
const s3: []const u8 = s2[0..3];
try expectEqualDeep(s1, s3);
const TestStruct = struct { s: []const u8 };
try expectEqualDeep(TestStruct{ .s = "abc" }, TestStruct{ .s = "abc" });
try expectEqualDeep([_][]const u8{ "a", "b", "c" }, [_][]const u8{ "a", "b", "c" });
// 向量
try expectEqualDeep(@as(@Vector(4, u32), @splat(4)), @as(@Vector(4, u32), @splat(4)));
// 嵌套数组
{
const a = [2][2]f32{
[_]f32{ 1.0, 0.0 },
[_]f32{ 0.0, 1.0 },
};
const b = [2][2]f32{
[_]f32{ 1.0, 0.0 },
[_]f32{ 0.0, 1.0 },
};
try expectEqualDeep(a, b);
try expectEqualDeep(&a, &b);
}
// 推导的联合体
const TestStruct2 = struct {
const A = union(enum) { b: B, c: C };
const B = struct {};
const C = struct { a: *const A };
};
const union1 = TestStruct2.A{ .b = .{} };
try expectEqualDeep(
TestStruct2.A{ .c = .{ .a = &union1 } },
TestStruct2.A{ .c = .{ .a = &union1 } },
);
}
/// 打印测试失败信息的辅助函数。
pub fn failPrintIndicatorLine(source: []const u8, indicator_index: usize) void {
const line_begin_index = if (std.mem.findScalarLast(u8, source[0..indicator_index], '\n')) |line_begin|
line_begin + 1
else
0;
const line_end_index = if (std.mem.findScalar(u8, source[indicator_index..], '\n')) |line_end|
(indicator_index + line_end)
else
source.len;
failPrintLine(source[line_begin_index..line_end_index]);
for (line_begin_index..indicator_index) |_|
failPrint(" ", .{});
if (indicator_index >= source.len)
failPrint("^ (end of string)\n", .{})
else
failPrint("^ ('\\x{x:0>2}')\n", .{source[indicator_index]});
}
/// 打印测试失败信息的辅助函数。
pub fn failPrintWithVisibleNewlines(source: []const u8) void {
var i: usize = 0;
while (std.mem.findScalar(u8, source[i..], '\n')) |nl| : (i += nl + 1) {
failPrintLine(source[i..][0..nl]);
}
failPrint("{s}␃\n", .{source[i..]}); // 文本结束符号(ETX)
}
/// 打印测试失败信息的辅助函数。
pub fn failPrintLine(line: []const u8) void {
if (line.len != 0) switch (line[line.len - 1]) {
' ', '\t' => return failPrint("{s}⏎\n", .{line}), // 返回符号
else => {},
};
failPrint("{s}\n", .{line});
}
/// 穷举检查 `test_fn` 内的分配失败是否均得到处理,且不会
/// 引入内存泄漏。若将 `testing.allocator` 用作 `backing_allocator`,
/// 还可在启用运行时安全检查时检测重复释放等问题。
///
/// 提供的 `test_fn` 必须以 `std.mem.Allocator` 作为第一个参数,
/// 返回类型必须为 `!void`。`test_fn` 的其他参数
/// 可通过 `extra_args` 元组提供。
///
/// `test_fn` 多次运行之间共享的所有相关状态,*必须*在 `test_fn` 内重置。
///
/// 采用的策略如下:
/// - 首先运行测试函数一次,获取分配总次数。
/// - 然后迭代并额外运行函数 X 次,每次迭代
/// 递增发生失败的分配索引;X 为此前
/// 确定的分配总次数。
///
/// 要求 `test_fn` 的内存分配次数具有确定性:
/// - 若某次 `test_fn` 运行中人为使一次分配失败,但 `test_fn`
/// 没有返回 `error.OutOfMemory`,则返回 `error.SwallowedOutOfMemoryError`,
/// 此错误由 `checkAllAllocationFailures` 返回。是否忽略此错误,
/// 取决于被测代码是否包含从
/// `error.OutOfMemory` 恢复的策略。
/// - 若预期发生分配失败的一次 `test_fn` 运行实际结束时
/// 未触发分配失败,则返回 `error.NondeterministicMemoryUsage`。
/// 此错误表示本函数使用的策略无法测试
/// 某些分配点,即某些运行中的分配点
/// 多于首次运行 `test_fn` 时检测到的分配点。
///
/// ---
///
/// 以下简单测试在分配 `bar` 失败时
/// 会泄漏内存,而正常情况下会通过:
///
/// ```zig
/// test {
/// const length: usize = 10;
/// const allocator = std.testing.allocator;
/// var foo = try allocator.alloc(u8, length);
/// var bar = try allocator.alloc(u8, length);
///
/// allocator.free(foo);
/// allocator.free(bar);
/// }
/// ```
///
/// 可以按以下方式将测试用例转换为
/// 本函数可调用的形式:
///
/// ```zig
/// fn testImpl(allocator: std.mem.Allocator, length: usize) !void {
/// var foo = try allocator.alloc(u8, length);
/// var bar = try allocator.alloc(u8, length);
///
/// allocator.free(foo);
/// allocator.free(bar);
/// }
///
/// test {
/// const length: usize = 10;
/// const allocator = std.testing.allocator;
/// try std.testing.checkAllAllocationFailures(allocator, testImpl, .{length});
/// }
/// ```
///
/// 运行此测试将显示:`foo` 会在分配 `bar` 失败时
/// 发生泄漏。此时最简单的修复方式是使用 defer:
///
/// ```zig
/// fn testImpl(allocator: std.mem.Allocator, length: usize) !void {
/// var foo = try allocator.alloc(u8, length);
/// defer allocator.free(foo);
/// var bar = try allocator.alloc(u8, length);
/// defer allocator.free(bar);
/// }
/// ```
pub fn checkAllAllocationFailures(
backing_allocator: std.mem.Allocator,
comptime test_fn: anytype,
extra_args: CheckAllAllocationFailuresExtraArgs(@TypeOf(test_fn)),
) !void {
// 先使用无限内存尝试一次,确保可用
const needed_alloc_count = x: {
var failing_allocator_inst = std.testing.FailingAllocator.init(backing_allocator, .{
.resize_fail_index = 0,
});
try @call(.auto, test_fn, .{failing_allocator_inst.allocator()} ++ extra_args);
break :x failing_allocator_inst.alloc_index;
};
for (0..needed_alloc_count) |fail_index| {
var failing_allocator_inst = std.testing.FailingAllocator.init(backing_allocator, .{
.fail_index = fail_index,
.resize_fail_index = 0,
});
if (@call(.auto, test_fn, .{failing_allocator_inst.allocator()} ++ extra_args)) |_| {
if (failing_allocator_inst.has_induced_failure) {
return error.SwallowedOutOfMemoryError;
} else {
return error.NondeterministicMemoryUsage;
}
} else |err| switch (err) {
error.OutOfMemory => {
if (failing_allocator_inst.allocated_bytes != failing_allocator_inst.freed_bytes) {
failPrint(
"\nfail_index: {d}/{d}\nallocated bytes: {d}\nfreed bytes: {d}\nallocations: {d}\ndeallocations: {d}\nallocation that was made to fail: {f}",
.{
fail_index,
needed_alloc_count,
failing_allocator_inst.allocated_bytes,
failing_allocator_inst.freed_bytes,
failing_allocator_inst.allocations,
failing_allocator_inst.deallocations,
std.debug.FormatStackTrace{
.stack_trace = failing_allocator_inst.getStackTrace(),
},
},
);
return error.MemoryLeakDetected;
}
},
else => |e| return e,
}
}
}
fn CheckAllAllocationFailuresExtraArgs(comptime TestFn: type) type {
switch (@typeInfo(@typeInfo(TestFn).@"fn".return_type.?)) {
.error_union => |info| {
if (info.payload != void) {
@compileError("Return type must be !void");
}
},
else => @compileError("Return type must be !void"),
}
const ArgsTuple = std.meta.ArgsTuple(TestFn);
const field_types = @typeInfo(ArgsTuple).@"struct".field_types;
if (field_types.len == 0 or field_types[0] != std.mem.Allocator) {
@compileError("The provided function must have an " ++ @typeName(std.mem.Allocator) ++ " as its first argument");
}
var extra_args: [field_types.len - 1]type = undefined;
for (&extra_args, field_types[1..]) |*arg, field_type| {
arg.* = field_type;
}
return @Tuple(&extra_args);
}
test "checkAllAllocationFailures provide result type to 'extra_args' argument" {
try checkAllAllocationFailures(
std.testing.allocator,
struct {
fn f(ally: std.mem.Allocator, params: struct {
foo_len: u32,
bar_len: u32,
}) !void {
const foo = try ally.alloc(u8, params.foo_len);
defer ally.free(foo);
const bar = try ally.alloc(u8, params.bar_len);
defer ally.free(bar);
}
}.f,
.{
.{
.foo_len = 3,
.bar_len = 5,
},
},
);
}
test "checkAllAllocationFailures does not depend on in-place resizes" {
// `std.testing.allocator` 从不复用内存,因此列表能否原地扩容取决于它落在存储桶的哪个位置,而该位置每次运行都不同。
//
const S = struct {
fn f(gpa: std.mem.Allocator) !void {
var a: std.ArrayList(u8) = .empty;
defer a.deinit(gpa);
var b: std.ArrayList(u8) = .empty;
defer b.deinit(gpa);
for (0..2000) |i| {
try a.append(gpa, @truncate(i));
try b.append(gpa, @truncate(i));
}
}
};
try checkAllAllocationFailures(std.testing.allocator, S.f, .{});
}
/// 给定类型,引用其内部所有声明,使语义分析器能够分析它们。
pub fn refAllDecls(comptime T: type) void {
if (!builtin.is_test) return;
inline for (comptime std.meta.declarations(T)) |decl_name| {
_ = &@field(T, decl_name);
}
}
pub const Smith = @import("testing/Smith.zig");
pub const FuzzInputOptions = struct {
corpus: []const []const u8 = &.{},
};
/// 内联以避免覆盖率插桩。
pub inline fn fuzz(
context: anytype,
comptime testOne: fn (context: @TypeOf(context), smith: *Smith) anyerror!void,
options: FuzzInputOptions,
) anyerror!void {
return @import("root").fuzz(context, testOne, options);
}
/// 在 `stream` 期间写出预定缓冲区列表的 `Io.Reader`。
pub const Reader = struct {
calls: []const Call,
interface: Io.Reader,
next_call_index: usize,
next_offset: usize,
/// 进一步减少每次 `stream` 调用写入的字节数。
artificial_limit: Io.Limit = .unlimited,
pub const Call = struct {
buffer: []const u8,
};
pub fn init(buffer: []u8, calls: []const Call) Reader {
return .{
.next_call_index = 0,
.next_offset = 0,
.interface = .{
.vtable = &.{ .stream = stream },
.buffer = buffer,
.seek = 0,
.end = 0,
},
.calls = calls,
};
}
fn stream(io_r: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize {
const r: *Reader = @alignCast(@fieldParentPtr("interface", io_r));
if (r.calls.len - r.next_call_index == 0) return error.EndOfStream;
const call = r.calls[r.next_call_index];
const buffer = r.artificial_limit.sliceConst(limit.sliceConst(call.buffer[r.next_offset..]));
const n = try w.write(buffer);
r.next_offset += n;
if (call.buffer.len - r.next_offset == 0) {
r.next_call_index += 1;
r.next_offset = 0;
}
return n;
}
};
/// 从另一个 `Io.Reader` 获取数据的 `Io.Reader`;在 `stream` 和 `readVec` 中,
/// 始终写入自身缓冲区,并返回 0。
/// 注意:不支持零长度缓冲区。
pub const ReaderIndirect = struct {
in: *Io.Reader,
interface: Io.Reader,
pub fn init(in: *Io.Reader, buffer: []u8) ReaderIndirect {
assert(buffer.len > 0);
return .{
.in = in,
.interface = .{
.vtable = &.{
.stream = stream,
.readVec = readVec,
},
.buffer = buffer,
.seek = 0,
.end = 0,
},
};
}
fn readVec(r: *Io.Reader, _: [][]u8) Io.Reader.Error!usize {
try streamInner(r);
return 0;
}
fn stream(r: *Io.Reader, _: *Io.Writer, _: Io.Limit) Io.Reader.StreamError!usize {
try streamInner(r);
return 0;
}
fn streamInner(r: *Io.Reader) Io.Reader.Error!void {
const r_indirect: *ReaderIndirect = @alignCast(@fieldParentPtr("interface", r));
// 如果缓冲区完全没有剩余空间,则腾出空间。
if (r.buffer.len == r.end) {
try r.rebase(r.buffer.len);
}
var writer: Io.Writer = .{
.buffer = r.buffer,
.end = r.end,
.vtable = &.{
.drain = Io.Writer.unreachableDrain,
.rebase = Io.Writer.unreachableRebase,
},
};
defer r.end = writer.end;
r_indirect.in.streamExact(&writer, r.buffer.len - r.end) catch |err| switch (err) {
// 仅在没有向缓冲区写入新字节时传播 EndOfStream
error.EndOfStream => |e| if (r.end == writer.end) {
return e;
},
error.WriteFailed => unreachable,
else => |e| return e,
};
}
};
/// 一种 `Io.Writer`,将数据写入另一个 `Io.Writer`,且仅在
/// `drain` 期间向自身缓冲区写入新数据。
/// 注意:不支持长度为零的缓冲区。
pub const WriterIndirect = struct {
out: *Io.Writer,
interface: Io.Writer,
pub fn init(out: *Io.Writer, buffer: []u8) WriterIndirect {
assert(buffer.len > 0);
return .{
.out = out,
.interface = .{
.vtable = &.{
.drain = drain,
},
.buffer = buffer,
.end = 0,
},
};
}
fn drain(w: *Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize {
const w_indirect: *WriterIndirect = @alignCast(@fieldParentPtr("interface", w));
// 将缓冲区中的全部数据写入 `out`
try w_indirect.out.writeAll(w.buffer[0..w.end]);
w.end = 0;
// 使用数据重新填充缓冲区
{
const end_before_fill = w.end;
for (data[0 .. data.len - 1]) |bytes| {
const dest = w.buffer[w.end..];
const len = @min(bytes.len, dest.len);
@memcpy(dest[0..len], bytes[0..len]);
w.end += len;
}
const pattern = data[data.len - 1];
switch (pattern.len) {
0 => {},
1 => {
const len = @min(w.buffer[w.end..].len, splat);
@memset(w.buffer[w.end..][0..len], pattern[0]);
w.end += len;
},
else => {
const dest = w.buffer[w.end..];
for (0..splat) |i| {
const start_i = i * pattern.len;
if (start_i >= dest.len) break;
const remaining = dest[start_i..];
const len = @min(pattern.len, remaining.len);
@memcpy(remaining[0..len], pattern[0..len]);
w.end += len;
}
},
}
return w.end - end_before_fill;
}
}
};
test {
_ = &Smith;
}