fix error wrapping

This commit is contained in:
Motiejus Jakštys 2022-06-28 16:41:10 +03:00
parent 3872f2af40
commit 71f94d0600
2 changed files with 20 additions and 20 deletions

View File

@ -31,12 +31,18 @@ pub fn write(self: *ErrCtx, bytes: []const u8) error{}!usize {
const Writer = std.io.Writer(*ErrCtx, error{}, write);
pub fn writer(self: *ErrCtx) Writer {
fn writer(self: *ErrCtx) Writer {
return Writer{ .context = self };
}
pub fn print(self: *ErrCtx, comptime format: []const u8, args: anytype) void {
self.writer().print(format, args) catch unreachable;
var buf: [capacity]u8 = undefined;
var buf_stream = std.io.fixedBufferStream(&buf);
buf_stream.writer().print(format, args) catch |err| switch (err) {
error.NoSpaceLeft => {},
};
_ = self.write(buf[0..buf_stream.pos]) catch unreachable;
}
pub fn returnf(
@ -117,10 +123,10 @@ test "almost overflow" {
test "rev" {
var ctx = ErrCtx{};
ctx.print("yadda", .{});
ctx.print("yadda {s}", .{"xx"});
var it = ctx.rev();
try testing.expectEqualSlices(u8, "yadda", it.next().?);
try testing.expectEqualStrings("yadda xx", it.next().?);
try testing.expectEqual(it.next(), null);
}

View File

@ -151,31 +151,25 @@ test "trivial error: missing passwd file" {
const exit_code = execute(allocator, stdout.writer(), stderr.writer(), args[0..]);
try testing.expectEqual(@as(u8, 1), exit_code);
try testing.expectEqualSlices(
u8,
stderr.items,
"ERROR FileNotFound: ./passwd: open \n",
);
try testing.expectEqualStrings(stderr.items, "ERROR FileNotFound: ./passwd: open \n");
}
test "fail" {
var errc = ErrCtx{};
var stderr = ArrayList(u8).init(testing.allocator);
defer stderr.deinit();
var stderrw = stderr.writer();
const exit_code = fail(errc.wrapf("got 1", .{}), stderrw, error.NotSure);
var buf = ArrayList(u8).init(testing.allocator);
defer buf.deinit();
var wr = buf.writer();
const exit_code = fail(errc.wrapf("invalid user 'foo'", .{}), wr, error.NotSure);
try testing.expectEqual(exit_code, 1);
try testing.expectEqualSlices(
u8,
stderr.items,
"ERROR NotSure: got 1\n",
);
try testing.expectEqualStrings(buf.items, "ERROR NotSure: invalid user 'foo'\n");
}
test "smoke test" {
const allocator = testing.allocator;
var stderr = ArrayList(u8).init(allocator);
defer stderr.deinit();
var stdout = ArrayList(u8).init(allocator);
defer stdout.deinit();
var corpus = try Corpus.testCorpus(allocator);
defer corpus.deinit();
@ -225,8 +219,8 @@ test "smoke test" {
"--output", outPath,
};
const exit_code = execute(allocator, stdout.writer(), stderr.writer(), args);
if (true) return error.SkipZigTest;
const exit_code = try execute(allocator, stderr.writer(), args);
try testing.expectEqualStrings("", stderr.items);
try testing.expectEqual(@as(u8, 0), exit_code);
}