Socialify

Folder ..

Viewing tests.zig
414 lines (338 loc) • 11.9 KB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
const std = @import("std");
const root = @import("../build.zig");

const debug = std.debug;
const fmt = std.fmt;
const fs = std.fs;
const mem = std.mem;

const Allocator = std.mem.Allocator;
const Child = std.process.Child;
const Build = std.Build;
const LazyPath = std.Build.LazyPath;
const Reader = fs.File.Reader;
const RunStep = std.Build.RunStep;
const Step = Build.Step;

const Exercise = root.Exercise;

pub fn addCliTests(b: *std.Build, exercises: []const Exercise) *Step {
    const step = b.step("test-cli", "Test the command line interface");

    {
        // Test that `zig build -Dhealed -Dn=n` selects the nth exercise.
        const case_step = createCase(b, "case-1");

        const tmp_path = makeTempPath(b) catch |err| {
            return fail(step, "unable to make tmp path: {s}\n", .{@errorName(err)});
        };

        const heal_step = HealStep.create(b, exercises, tmp_path);

        for (exercises[0 .. exercises.len - 1]) |ex| {
            const n = ex.number();

            const cmd = b.addSystemCommand(&.{
                b.graph.zig_exe,
                "build",
                "-Dhealed",
                b.fmt("-Dhealed-path={s}", .{tmp_path}),
                b.fmt("-Dn={}", .{n}),
            });
            cmd.setName(b.fmt("zig build -Dhealed -Dn={}", .{n}));
            cmd.expectExitCode(0);
            cmd.step.dependOn(&heal_step.step);

            const stderr = cmd.captureStdErr();
            const verify = CheckNamedStep.create(b, ex, stderr);
            verify.step.dependOn(&cmd.step);

            case_step.dependOn(&verify.step);
        }

        const cleanup = b.addRemoveDirTree(tmp_path);
        cleanup.step.dependOn(case_step);

        step.dependOn(&cleanup.step);
    }

    {
        // Test that `zig build -Dhealed` processes all the exercises in order.
        const case_step = createCase(b, "case-2");

        const tmp_path = makeTempPath(b) catch |err| {
            return fail(step, "unable to make tmp path: {s}\n", .{@errorName(err)});
        };

        const heal_step = HealStep.create(b, exercises, tmp_path);
        heal_step.step.dependOn(case_step);

        // TODO: when an exercise is modified, the cache is not invalidated.
        const cmd = b.addSystemCommand(&.{
            b.graph.zig_exe,
            "build",
            "-Dhealed",
            b.fmt("-Dhealed-path={s}", .{tmp_path}),
        });
        cmd.setName("zig build -Dhealed");
        cmd.expectExitCode(0);
        cmd.step.dependOn(&heal_step.step);

        const stderr = cmd.captureStdErr();
        const verify = CheckStep.create(b, exercises, stderr);
        verify.step.dependOn(&cmd.step);

        const cleanup = b.addRemoveDirTree(tmp_path);
        cleanup.step.dependOn(&verify.step);

        step.dependOn(&cleanup.step);
    }

    {
        // Test that `zig build -Dn=n` prints the hint.
        const case_step = createCase(b, "case-3");

        for (exercises[0 .. exercises.len - 1]) |ex| {
            if (ex.skip) continue;

            if (ex.hint) |hint| {
                const n = ex.number();

                const cmd = b.addSystemCommand(&.{
                    b.graph.zig_exe,
                    "build",
                    b.fmt("-Dn={}", .{n}),
                });
                cmd.setName(b.fmt("zig build -Dn={}", .{n}));
                cmd.expectExitCode(2);
                cmd.addCheck(.{ .expect_stderr_match = hint });

                case_step.dependOn(&cmd.step);
            }
        }

        step.dependOn(case_step);
    }

    return step;
}

fn createCase(b: *Build, name: []const u8) *Step {
    const case_step = b.allocator.create(Step) catch @panic("OOM");
    case_step.* = Step.init(.{
        .id = .custom,
        .name = name,
        .owner = b,
    });

    return case_step;
}

/// Checks the output of `zig build -Dn=n`.
const CheckNamedStep = struct {
    step: Step,
    exercise: Exercise,
    stderr: LazyPath,

    pub fn create(owner: *Build, exercise: Exercise, stderr: LazyPath) *CheckNamedStep {
        const self = owner.allocator.create(CheckNamedStep) catch @panic("OOM");
        self.* = .{
            .step = Step.init(.{
                .id = .custom,
                .name = "check-named",
                .owner = owner,
                .makeFn = make,
            }),
            .exercise = exercise,
            .stderr = stderr,
        };

        return self;
    }

    fn make(step: *Step, _: std.Progress.Node) !void {
        const b = step.owner;
        const self: *CheckNamedStep = @alignCast(@fieldParentPtr("step", step));
        const ex = self.exercise;

        const stderr_file = try fs.cwd().openFile(
            self.stderr.getPath(b),
            .{ .mode = .read_only },
        );
        defer stderr_file.close();

        const stderr = stderr_file.reader();
        {
            // Skip the logo.
            const nlines = mem.count(u8, root.logo, "\n");
            var buf: [80]u8 = undefined;

            var lineno: usize = 0;
            while (lineno < nlines) : (lineno += 1) {
                _ = try readLine(stderr, &buf);
            }
        }
        try check_output(step, ex, stderr);
    }
};

/// Checks the output of `zig build`.
const CheckStep = struct {
    step: Step,
    exercises: []const Exercise,
    stderr: LazyPath,

    pub fn create(
        owner: *Build,
        exercises: []const Exercise,
        stderr: LazyPath,
    ) *CheckStep {
        const self = owner.allocator.create(CheckStep) catch @panic("OOM");
        self.* = .{
            .step = Step.init(.{
                .id = .custom,
                .name = "check",
                .owner = owner,
                .makeFn = make,
            }),
            .exercises = exercises,
            .stderr = stderr,
        };

        return self;
    }

    fn make(step: *Step, _: std.Progress.Node) !void {
        const b = step.owner;
        const self: *CheckStep = @alignCast(@fieldParentPtr("step", step));
        const exercises = self.exercises;

        const stderr_file = try fs.cwd().openFile(
            self.stderr.getPath(b),
            .{ .mode = .read_only },
        );
        defer stderr_file.close();

        const stderr = stderr_file.reader();
        for (exercises) |ex| {
            if (ex.number() == 1) {
                // Skip the logo.
                const nlines = mem.count(u8, root.logo, "\n");
                var buf: [80]u8 = undefined;

                var lineno: usize = 0;
                while (lineno < nlines) : (lineno += 1) {
                    _ = try readLine(stderr, &buf);
                }
            }
            try check_output(step, ex, stderr);
        }
    }
};

fn check_output(step: *Step, exercise: Exercise, reader: Reader) !void {
    const b = step.owner;

    var buf: [1024]u8 = undefined;
    if (exercise.skip) {
        {
            const actual = try readLine(reader, &buf) orelse "EOF";
            const expect = b.fmt("Skipping {s}", .{exercise.main_file});
            try check(step, exercise, expect, actual);
        }

        {
            const actual = try readLine(reader, &buf) orelse "EOF";
            try check(step, exercise, "", actual);
        }

        return;
    }

    {
        const actual = try readLine(reader, &buf) orelse "EOF";
        const expect = b.fmt("Compiling {s}...", .{exercise.main_file});
        try check(step, exercise, expect, actual);
    }

    {
        const actual = try readLine(reader, &buf) orelse "EOF";
        const expect = b.fmt("Checking {s}...", .{exercise.main_file});
        try check(step, exercise, expect, actual);
    }

    {
        const actual = try readLine(reader, &buf) orelse "EOF";
        const expect = switch (exercise.kind) {
            .exe => "PASSED:",
            .@"test" => "PASSED",
        };
        try check(step, exercise, expect, actual);
    }

    // Skip the exercise output.
    const nlines = switch (exercise.kind) {
        .exe => 1 + mem.count(u8, exercise.output, "\n") + 1,
        .@"test" => 1,
    };

    var lineno: usize = 0;
    while (lineno < nlines) : (lineno += 1) {
        _ = try readLine(reader, &buf) orelse @panic("EOF");
    }
}

fn check(
    step: *Step,
    exercise: Exercise,
    expect: []const u8,
    actual: []const u8,
) !void {
    if (!mem.eql(u8, expect, actual)) {
        return step.fail("{s}: expected to see \"{s}\", found \"{s}\"", .{
            exercise.main_file,
            expect,
            actual,
        });
    }
}

fn readLine(reader: fs.File.Reader, buf: []u8) !?[]const u8 {
    if (try reader.readUntilDelimiterOrEof(buf, '\n')) |line| {
        return mem.trimRight(u8, line, " \r\n");
    }

    return null;
}

/// Fails with a custom error message.
const FailStep = struct {
    step: Step,
    error_msg: []const u8,

    pub fn create(owner: *Build, error_msg: []const u8) *FailStep {
        const self = owner.allocator.create(FailStep) catch @panic("OOM");
        self.* = .{
            .step = Step.init(.{
                .id = .custom,
                .name = "fail",
                .owner = owner,
                .makeFn = make,
            }),
            .error_msg = error_msg,
        };

        return self;
    }

    fn make(step: *Step, _: std.Progress.Node) !void {
        const b = step.owner;
        const self: *FailStep = @alignCast(@fieldParentPtr("step", step));

        try step.result_error_msgs.append(b.allocator, self.error_msg);
        return error.MakeFailed;
    }
};

/// A variant of `std.Build.Step.fail` that does not return an error so that it
/// can be used in the configuration phase.  It returns a FailStep, so that the
/// error will be cleanly handled by the build runner.
fn fail(step: *Step, comptime format: []const u8, args: anytype) *Step {
    const b = step.owner;

    const fail_step = FailStep.create(b, b.fmt(format, args));
    step.dependOn(&fail_step.step);

    return step;
}

/// Heals the exercises.
const HealStep = struct {
    step: Step,
    exercises: []const Exercise,
    work_path: []const u8,

    pub fn create(owner: *Build, exercises: []const Exercise, work_path: []const u8) *HealStep {
        const self = owner.allocator.create(HealStep) catch @panic("OOM");
        self.* = .{
            .step = Step.init(.{
                .id = .custom,
                .name = "heal",
                .owner = owner,
                .makeFn = make,
            }),
            .exercises = exercises,
            .work_path = work_path,
        };

        return self;
    }

    fn make(step: *Step, _: std.Progress.Node) !void {
        const b = step.owner;
        const self: *HealStep = @alignCast(@fieldParentPtr("step", step));

        return heal(b.allocator, self.exercises, self.work_path);
    }
};

/// Heals all the exercises.
fn heal(allocator: Allocator, exercises: []const Exercise, work_path: []const u8) !void {
    const sep = std.fs.path.sep_str;
    const join = fs.path.join;

    const exercises_path = "exercises";
    const patches_path = "patches" ++ sep ++ "patches";

    for (exercises) |ex| {
        const name = ex.name();

        const file = try join(allocator, &.{ exercises_path, ex.main_file });
        const patch = b: {
            const patch_name = try fmt.allocPrint(allocator, "{s}.patch", .{name});
            break :b try join(allocator, &.{ patches_path, patch_name });
        };
        const output = try join(allocator, &.{ work_path, ex.main_file });

        const argv = &.{ "patch", "-i", patch, "-o", output, "-s", file };

        var child = Child.init(argv, allocator);
        _ = try child.spawnAndWait();
    }
}

/// This function is the same as the one in std.Build.makeTempPath, with the
/// difference that returns an error when the temp path cannot be created.
pub fn makeTempPath(b: *Build) ![]const u8 {
    const rand_int = std.crypto.random.int(u64);
    const tmp_dir_sub_path = "tmp" ++ fs.path.sep_str ++ Build.hex64(rand_int);
    const path = b.cache_root.join(b.allocator, &.{tmp_dir_sub_path}) catch
        @panic("OOM");
    try b.cache_root.handle.makePath(tmp_dir_sub_path);

    return path;
}