zig-testing
БесплатноБез исполняемых скриптовНе проверенZig testing skill for writing and running tests. Use when using zig build test, writing comptime tests, using test filters, working with test allocators to…
от mohitmishra786★ 307 звёзд на GitHubОб этом скилле
Zig Testing
Purpose
Guide agents through Zig's testing system: zig build test and zig test, comptime testing patterns, test filters, the test allocator for leak detection, and Zig's built-in fuzz testing.
Triggers
- "How do I write and run tests in Zig?"
- "How do I filter which Zig tests run?"
- "How do I detect memory leaks in Zig tests?"
- "How do I write comptime tests in Zig?"
- "How do I use Zig's built-in fuzzer?"
- "How do I test a Zig library?"
Workflow
1. Writing and running tests
// src/math.zig
const std = @import("std");
const testing = std.testing;
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn divide(a: f64, b: f64) !f64 {
if (b == 0.0) return error.DivisionByZero;
return a / b;
}
// Tests live in the same file or a dedicated test file
test "add: basic addition" {
try testing.expectEqual(@as(i32, 5), add(2, 3));
try testing.expectEqual(@as(i32, -1), add(2, -3));
}
test "add: identity" {
try testing.expectEqual(@as(i32, 42), add(42, 0));
}
test "divide: normal case" {
const result = try divide(10.0, 2.0);
try testing.expectApproxEqAbs(result, 5.0, 1e-9);
}
test "divide: by zero returns error" {
try testing.expectError(error.DivisionByZero, divide(1.0, 0.0));
}
# Run all tests in a single file
zig test src/math.zig
# Run all tests via build system
zig build test
# Verbose output
zig build test -- --verbose
# Run specific test by name (substring match)
zig build test -- --test-filter "add"
2. build.zig test configuration
// build.zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const math_mod = b.createModule(.{
.root_source_file = b.path("src/math.zig"),
.target = target,
.optimize = optimize,
});
// Unit test step
const unit_tests = b.addTest(.{ .root_module = math_mod });
const run_unit_tests = b.addRunArtifact(unit_tests);
// Integration tests (separate test binary that imports the module)
const integration_tests = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("tests/integration.zig"),
.target = target,
.optimize = optimize,
.imports = &.{.{ .name = "math", .module = math_mod }},
}),
});
const run_integration = b.addRunArtifact(integration_tests);
// `zig build test` runs both
const test_step = b.step("test", "Run all tests");
test_step.dependOn(&run_unit_tests.step);
test_step.dependOn(&run_integration.step);
// `zig build test-unit` runs only unit tests
const unit_step = b.step("test-unit", "Run unit tests");
unit_step.dependOn(&run_unit_tests.step);
}
3. Test allocator — leak detection
std.testing.allocator is a std.heap.DebugAllocator that reports leaks at the end of each test:
const std = @import("std");
const testing = std.testing;
test "ArrayList: no leaks" {
// std.ArrayList is unmanaged since 0.15: pass the allocator to each call
var list: std.ArrayList(u32) = .empty;
defer list.deinit(testing.allocator); // MUST defer to return memory
try list.append(testing.allocator, 1);
try list.append(testing.allocator, 2);
try list.append(testing.allocator, 3);
try testing.expectEqual(@as(usize, 3), list.items.len);
// If you forget defer list.deinit(), test reports a leak
}
test "custom allocation" {
// DebugAllocator replaced GeneralPurposeAllocator
var da: std.heap.DebugAllocator(.{}) = .init;
defer {
const leaked = da.deinit();
// .ok means no leaks; .leak means memory was not freed
testing.expect(leaked == .ok) catch @panic("memory leaked!");
}
const allocator = da.allocator();
const buf = try allocator.alloc(u8, 1024);
defer allocator.free(buf); // leak if forgotten
}
4. Testing assertions
const testing = std.testing;
// Equality
try testing.expectEqual(expected, actual);
try testing.expectEqualStrings("hello", result_str);
try testing.expectEqualSlices(u8, expected_slice, actual_slice);
// Approximate equality (for floats)
try testing.expectApproxEqAbs(expected, actual, tolerance);
try testing.expectApproxEqRel(expected, actual, tolerance);
// Errors
try testing.expectError(error.MyError, might_fail());
try testing.expect(condition); // basic boolean assertion
// Comparison
try testing.expect(a < b);
try testing.expectStringStartsWith(str, "prefix");
try testing.expectStringEndsWith(str, "suffix");
5. Comptime testing
Zig can run tests at comptime — useful for compile-time constants and type-level checks:
const std = @import("std");
const testing = std.testing;
// Test comptime functions
fn isPowerOfTwo(n: comptime_int) bool {
return n > 0 and (n & (n - 1)) == 0;
}
// Comptime assert (compile error if false)
compti
Установить zig-testing в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл zig-testing?
Zig testing skill for writing and running tests. Use when using zig build test, writing comptime tests, using test filters, working with test allocators to detect leaks, or using Zig's built-in fuzz testing (std.testing.fuzz). Activates on queries about Zig tests, zig test, zig build test, comptime testing, test allocators, Zig fuzz testing, or detecting memory leaks in Zig tests.
Как установить скилл zig-testing?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл zig-testing запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic