Installation

Ready to test your Zig CLI? This guide shows you how to install cmdtest, hook it into your build script, and run your first command-line test.

Let’s get cmdtest working in your project. It only takes a few steps.

Step 1: Fetch the package

First, you need to add cmdtest as a dependency. Run this command in your project’s root folder.

Shell
zig fetch --save=cmdtest https://github.com/pyk/cmdtest/archive/v0.2.0.tar.gz

This downloads the code and adds it to your build.zig.zon file.

Step 2: Update your build.zig

Next, you need to tell your build script about the tests. Open your build.zig and add the cmdtest.add function.

Let’s say you have an executable named mycli and a test file at src/test.zig.

Zig
const std = @import("std");
const cmdtest = @import("cmdtest");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});

    // Your CLI executable
    const exe = b.addExecutable(.{
        .name = "mycli",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
    });
    b.installArtifact(exe);

    // Register a new test runner for your CLI
    const mycli_test = cmdtest.add(b, .{
        .name = "mycli-test",
        .test_file = b.path("src/test.zig"),
    });

    const test_step = b.step("test", "Run tests");
    test_step.dependOn(&mycli_test.step);
}

The cmdtest.add function creates a new test step. When you run zig build test, it will compile and run your src/test.zig file. It also makes sure your mycli executable is built first and is available in the PATH.

Step 3: Write a test

Now, create your test file at src/test.zig. Here’s a simple example that runs the echo command.

Zig
const std = @import("std");
const testing = std.testing;
const cmdtest = @import("cmdtest");

test "echo hello" {
    const argv = &[_][]const u8{"echo", "hello"};
    var result = try cmdtest.run(.{ .argv = argv });
    defer result.deinit();

    try testing.expectEqualStrings("hello\n", result.stdout);
    try testing.expectEqual(@as(u8, 0), result.code);
}

The important parts are cmdtest.run(), which runs the command, and result.deinit(), which frees the memory used to store the output. Don’t forget to call defer result.deinit().

Step 4: Run it

You’re all set. Run the tests from your terminal.

Shell
zig build test

It should compile everything and run your test.