master
 1// test getting environment variables
 2
 3const std = @import("std");
 4const builtin = @import("builtin");
 5
 6pub fn main() !void {
 7    if (builtin.target.os.tag == .windows) {
 8        return; // Windows env strings are WTF-16, so not supported by Zig's std.posix.getenv()
 9    }
10
11    if (builtin.target.os.tag == .wasi and !builtin.link_libc) {
12        return; // std.posix.getenv is not supported on WASI due to the need of allocation
13    }
14
15    // Test some unset env vars:
16
17    try std.testing.expectEqual(std.posix.getenv(""), null);
18    try std.testing.expectEqual(std.posix.getenv("BOGUSDOESNOTEXISTENVVAR"), null);
19    try std.testing.expectEqual(std.posix.getenvZ("BOGUSDOESNOTEXISTENVVAR"), null);
20
21    if (builtin.link_libc) {
22        // Test if USER matches what C library sees
23        const expected = std.mem.span(std.c.getenv("USER") orelse "");
24        const actual = std.posix.getenv("USER") orelse "";
25        try std.testing.expectEqualStrings(expected, actual);
26    }
27
28    // env vars set by our build.zig run step:
29    try std.testing.expectEqualStrings("", std.posix.getenv("ZIG_TEST_POSIX_EMPTY") orelse "invalid");
30    try std.testing.expectEqualStrings("test=variable", std.posix.getenv("ZIG_TEST_POSIX_1EQ") orelse "invalid");
31    try std.testing.expectEqualStrings("=test=variable=", std.posix.getenv("ZIG_TEST_POSIX_3EQ") orelse "invalid");
32}