zig/test/cases/error.zig

77 lines
1.5 KiB
Zig
Raw Normal View History

2017-01-05 16:57:48 +08:00
const assert = @import("std").debug.assert;
const mem = @import("std").mem;
2017-01-05 16:57:48 +08:00
2018-02-01 11:48:40 +08:00
pub fn foo() !i32 {
const x = try bar();
return x + 1;
}
2018-02-01 11:48:40 +08:00
pub fn bar() !i32 {
return 13;
}
2018-02-01 11:48:40 +08:00
pub fn baz() !i32 {
const y = foo() catch 1234;
return y + 1;
}
2017-05-24 09:38:31 +08:00
test "error wrapping" {
assert((baz() catch unreachable) == 15);
}
fn gimmeItBroke() []const u8 {
return @errorName(error.ItBroke);
}
2017-05-24 09:38:31 +08:00
test "@errorName" {
assert(mem.eql(u8, @errorName(error.AnError), "AnError"));
assert(mem.eql(u8, @errorName(error.ALongerErrorName), "ALongerErrorName"));
}
2017-05-24 09:38:31 +08:00
test "error values" {
2016-12-22 14:20:08 +08:00
const a = i32(error.err1);
const b = i32(error.err2);
assert(a != b);
}
2017-05-24 09:38:31 +08:00
test "redefinition of error values allowed" {
2016-12-22 14:20:08 +08:00
shouldBeNotEqual(error.AnError, error.SecondError);
}
fn shouldBeNotEqual(a: error, b: error) void {
if (a == b) unreachable;
2016-12-22 14:20:08 +08:00
}
2017-05-24 09:38:31 +08:00
test "error binary operator" {
const a = errBinaryOperatorG(true) catch 3;
const b = errBinaryOperatorG(false) catch 3;
2016-12-22 14:42:30 +08:00
assert(a == 3);
assert(b == 10);
}
2018-02-01 11:48:40 +08:00
fn errBinaryOperatorG(x: bool) !isize {
return if (x) error.ItBroke else isize(10);
2016-12-22 14:42:30 +08:00
}
2017-05-24 09:38:31 +08:00
test "unwrap simple value from error" {
const i = unwrapSimpleValueFromErrorDo() catch unreachable;
2016-12-22 14:42:30 +08:00
assert(i == 13);
}
fn unwrapSimpleValueFromErrorDo() %isize { return 13; }
2016-12-22 14:42:30 +08:00
2016-12-22 14:20:08 +08:00
2017-05-24 09:38:31 +08:00
test "error return in assignment" {
doErrReturnInAssignment() catch unreachable;
2016-12-22 21:48:08 +08:00
}
2018-02-01 11:48:40 +08:00
fn doErrReturnInAssignment() !void {
2016-12-22 21:48:08 +08:00
var x : i32 = undefined;
x = try makeANonErr();
2016-12-22 21:48:08 +08:00
}
2018-02-01 11:48:40 +08:00
fn makeANonErr() !i32 {
2016-12-22 21:48:08 +08:00
return 1;
}