Commit 4592fd26b9

Andrew Kelley <andrew@ziglang.org>
2020-12-09 05:54:46
add std.testing.expectStringEndsWith
1 parent 72f6c6e
Changed files (2)
lib
test
lib/std/testing.zig
@@ -247,6 +247,7 @@ test "expectWithinEpsilon" {
 /// This function is intended to be used only in tests. When the two slices are not
 /// equal, prints diagnostics to stderr to show exactly how they are not equal,
 /// then aborts.
+/// If your inputs are UTF-8 encoded strings, consider calling `expectEqualStrings` instead.
 pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const T) void {
     // TODO better printing of the difference
     // If the arrays are small enough we could print the whole thing
@@ -368,6 +369,26 @@ pub fn expectEqualStrings(expected: []const u8, actual: []const u8) void {
     }
 }
 
+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[0..expected_ends_with.len]
+    else
+        actual;
+
+    print("\n====== expected to end with: =========\n", .{});
+    printWithVisibleNewlines(expected_ends_with);
+    print("\n====== instead ended with: ===========\n", .{});
+    printWithVisibleNewlines(shortened_actual);
+    print("\n========= full output: ==============\n", .{});
+    printWithVisibleNewlines(actual);
+    print("\n======================================\n", .{});
+
+    @panic("test failure");
+}
+
 fn printIndicatorLine(source: []const u8, indicator_index: usize) void {
     const line_begin_index = if (std.mem.lastIndexOfScalar(u8, source[0..indicator_index], '\n')) |line_begin|
         line_begin + 1
test/cli.zig
@@ -92,13 +92,13 @@ fn exec(cwd: []const u8, expect_0: bool, argv: []const []const u8) !ChildProcess
 fn testZigInitLib(zig_exe: []const u8, dir_path: []const u8) !void {
     _ = try exec(dir_path, true, &[_][]const u8{ zig_exe, "init-lib" });
     const test_result = try exec(dir_path, true, &[_][]const u8{ zig_exe, "build", "test" });
-    testing.expect(std.mem.endsWith(u8, test_result.stderr, "All 1 tests passed.\n"));
+    testing.expectStringEndsWith(test_result.stderr, "All 1 tests passed.\n");
 }
 
 fn testZigInitExe(zig_exe: []const u8, dir_path: []const u8) !void {
     _ = try exec(dir_path, true, &[_][]const u8{ zig_exe, "init-exe" });
     const run_result = try exec(dir_path, true, &[_][]const u8{ zig_exe, "build", "run" });
-    testing.expect(std.mem.eql(u8, run_result.stderr, "info: All your codebase are belong to us.\n"));
+    testing.expectEqualStrings("info: All your codebase are belong to us.\n", run_result.stderr);
 }
 
 fn testGodboltApi(zig_exe: []const u8, dir_path: []const u8) anyerror!void {