zig/test/behavior/try.zig

48 lines
1.1 KiB
Zig
Raw Normal View History

2022-02-22 13:15:09 +00:00
const std = @import("std");
const builtin = @import("builtin");
const expect = std.testing.expect;
2017-02-02 22:09:27 +00:00
2017-05-24 02:38:31 +01:00
test "try on error union" {
2022-02-22 13:15:09 +00:00
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest;
try tryOnErrorUnionImpl();
comptime try tryOnErrorUnionImpl();
}
fn tryOnErrorUnionImpl() !void {
const x = if (returnsTen()) |val| val + 1 else |err| switch (err) {
2018-05-29 01:23:55 +01:00
error.ItBroke, error.NoMem => 1,
2019-11-07 04:25:57 +00:00
error.CrappedOut => @as(i32, 2),
else => unreachable,
2017-02-02 22:09:27 +00:00
};
try expect(x == 11);
2017-02-02 22:09:27 +00:00
}
fn returnsTen() anyerror!i32 {
return 10;
2017-02-02 22:09:27 +00:00
}
2017-05-24 02:38:31 +01:00
test "try without vars" {
2019-11-07 04:25:57 +00:00
const result1 = if (failIfTrue(true)) 1 else |_| @as(i32, 2);
try expect(result1 == 2);
2019-11-07 04:25:57 +00:00
const result2 = if (failIfTrue(false)) 1 else |_| @as(i32, 2);
try expect(result2 == 1);
}
fn failIfTrue(ok: bool) anyerror!void {
if (ok) {
return error.ItBroke;
} else {
return;
}
}
test "try then not executed with assignment" {
if (failIfTrue(true)) {
unreachable;
} else |err| {
try expect(err == error.ItBroke);
}
}