Commit d976456ef6

Rabin Gaire <rabingaire20@gmail.com>
2022-04-20 14:52:10
add test case for child_process spawn logic
tests creating a child process with stdin/stdout behavior set to StdIo.Pipe.
1 parent 9e4cd1f
Changed files (1)
lib/std/child_process.zig
@@ -1379,3 +1379,49 @@ test "build and call child_process" {
     const ret_val = try child_proc.spawnAndWait();
     try testing.expectEqual(ret_val, .{ .Exited = 0 });
 }
+
+test "creating a child process with stdin/stdout behavior set to StdIo.Pipe" {
+    if (builtin.os.tag == .wasi) return error.SkipZigTest;
+    const testing = std.testing;
+    const allocator = testing.allocator;
+
+    var child_process = try std.ChildProcess.init(
+        &[_][]const u8{ testing.zig_exe_path, "fmt", "--stdin" },
+        allocator,
+    );
+    defer child_process.deinit();
+    child_process.stdin_behavior = .Pipe;
+    child_process.stdout_behavior = .Pipe;
+
+    try child_process.spawn();
+
+    const input_program =
+        \\ const std = @import("std");
+        \\ pub fn main() void {
+        \\ std.debug.print("Hello World", .{});
+        \\ }
+    ;
+
+    try child_process.stdin.?.writer().writeAll(input_program);
+    child_process.stdin.?.close();
+    child_process.stdin = null;
+
+    const out_bytes = try child_process.stdout.?.reader().readAllAlloc(allocator, std.math.maxInt(usize));
+    defer allocator.free(out_bytes);
+    
+    switch (try child_process.wait()) {
+        .Exited => |code| if (code == 0) {
+            const expected_program =
+                \\const std = @import("std");
+                \\pub fn main() void {
+                \\    std.debug.print("Hello World", .{});
+                \\}
+                \\
+            ;
+            try testing.expectEqualStrings(expected_program, out_bytes);
+        },
+        else => {
+            try testing.expect(false);
+        }
+    }
+}