tests.zig 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. const std = @import("std");
  2. const root = @import("../build.zig");
  3. const debug = std.debug;
  4. const fmt = std.fmt;
  5. const fs = std.fs;
  6. const mem = std.mem;
  7. const Allocator = std.mem.Allocator;
  8. const Build = std.build;
  9. const FileSource = std.Build.FileSource;
  10. const Reader = fs.File.Reader;
  11. const RunStep = std.Build.RunStep;
  12. const Step = Build.Step;
  13. const Exercise = root.Exercise;
  14. pub fn addCliTests(b: *std.Build, exercises: []const Exercise) *Step {
  15. const step = b.step("test-cli", "Test the command line interface");
  16. // We should use a temporary path, but it will make the implementation of
  17. // `build.zig` more complex.
  18. const outdir = "patches/healed";
  19. fs.cwd().makePath(outdir) catch |err| {
  20. return fail(step, "unable to make '{s}': {s}\n", .{ outdir, @errorName(err) });
  21. };
  22. heal(b.allocator, exercises, outdir) catch |err| {
  23. return fail(step, "unable to heal exercises: {s}\n", .{@errorName(err)});
  24. };
  25. {
  26. // Test that `zig build -Dhealed -Dn=n test` selects the nth exercise.
  27. const case_step = createCase(b, "case-1");
  28. var i: usize = 0;
  29. for (exercises[0 .. exercises.len - 1]) |ex| {
  30. i += 1;
  31. if (ex.skip) continue;
  32. const cmd = b.addSystemCommand(
  33. &.{ b.zig_exe, "build", "-Dhealed", b.fmt("-Dn={}", .{i}), "test" },
  34. );
  35. cmd.setName(b.fmt("zig build -Dhealed -Dn={} test", .{i}));
  36. cmd.expectExitCode(0);
  37. if (ex.check_stdout)
  38. expectStdOutMatch(cmd, ex.output)
  39. else
  40. expectStdErrMatch(cmd, ex.output);
  41. case_step.dependOn(&cmd.step);
  42. }
  43. step.dependOn(case_step);
  44. }
  45. {
  46. // Test that `zig build -Dhealed -Dn=n test` skips disabled esercises.
  47. const case_step = createCase(b, "case-2");
  48. var i: usize = 0;
  49. for (exercises[0 .. exercises.len - 1]) |ex| {
  50. i += 1;
  51. if (!ex.skip) continue;
  52. const cmd = b.addSystemCommand(
  53. &.{ b.zig_exe, "build", "-Dhealed", b.fmt("-Dn={}", .{i}), "test" },
  54. );
  55. cmd.setName(b.fmt("zig build -Dhealed -Dn={} test", .{i}));
  56. cmd.expectExitCode(0);
  57. cmd.expectStdOutEqual("");
  58. expectStdErrMatch(cmd, b.fmt("{s} skipped", .{ex.main_file}));
  59. case_step.dependOn(&cmd.step);
  60. }
  61. step.dependOn(case_step);
  62. }
  63. {
  64. // Test that `zig build -Dhealed` process all the exercises in order.
  65. const case_step = createCase(b, "case-3");
  66. // TODO: when an exercise is modified, the cache is not invalidated.
  67. const cmd = b.addSystemCommand(&.{ b.zig_exe, "build", "-Dhealed" });
  68. cmd.setName("zig build -Dhealed");
  69. cmd.expectExitCode(0);
  70. const stderr = cmd.captureStdErr();
  71. const verify = CheckStep.create(b, exercises, stderr, true);
  72. verify.step.dependOn(&cmd.step);
  73. case_step.dependOn(&verify.step);
  74. step.dependOn(case_step);
  75. }
  76. {
  77. // Test that `zig build -Dhealed -Dn=1 start` process all the exercises
  78. // in order.
  79. const case_step = createCase(b, "case-4");
  80. // TODO: when an exercise is modified, the cache is not invalidated.
  81. const cmd = b.addSystemCommand(
  82. &.{ b.zig_exe, "build", "-Dhealed", "-Dn=1", "start" },
  83. );
  84. cmd.setName("zig build -Dhealed -Dn=1 start");
  85. cmd.expectExitCode(0);
  86. const stderr = cmd.captureStdErr();
  87. const verify = CheckStep.create(b, exercises, stderr, false);
  88. verify.step.dependOn(&cmd.step);
  89. case_step.dependOn(&verify.step);
  90. step.dependOn(case_step);
  91. }
  92. {
  93. // Test that `zig build -Dn=1` prints the hint.
  94. const case_step = createCase(b, "case-5");
  95. const cmd = b.addSystemCommand(&.{ b.zig_exe, "build", "-Dn=1" });
  96. cmd.setName("zig build -Dn=1");
  97. cmd.expectExitCode(1);
  98. expectStdErrMatch(cmd, exercises[0].hint);
  99. case_step.dependOn(&cmd.step);
  100. step.dependOn(case_step);
  101. }
  102. // Don't add the cleanup step, since it may delete outdir while a test case
  103. // is running.
  104. //const cleanup = b.addRemoveDirTree(outdir);
  105. //step.dependOn(&cleanup.step);
  106. return step;
  107. }
  108. fn createCase(b: *Build, name: []const u8) *Step {
  109. const case_step = b.allocator.create(Step) catch @panic("OOM");
  110. case_step.* = Step.init(.{
  111. .id = .custom,
  112. .name = name,
  113. .owner = b,
  114. });
  115. return case_step;
  116. }
  117. // Check the output of `zig build` or `zig build -Dn=1 start`.
  118. const CheckStep = struct {
  119. step: Step,
  120. exercises: []const Exercise,
  121. stderr: FileSource,
  122. has_logo: bool,
  123. pub fn create(
  124. owner: *Build,
  125. exercises: []const Exercise,
  126. stderr: FileSource,
  127. has_logo: bool,
  128. ) *CheckStep {
  129. const self = owner.allocator.create(CheckStep) catch @panic("OOM");
  130. self.* = .{
  131. .step = Step.init(.{
  132. .id = .custom,
  133. .name = "check",
  134. .owner = owner,
  135. .makeFn = make,
  136. }),
  137. .exercises = exercises,
  138. .stderr = stderr,
  139. .has_logo = has_logo,
  140. };
  141. return self;
  142. }
  143. fn make(step: *Step, _: *std.Progress.Node) !void {
  144. const b = step.owner;
  145. const self = @fieldParentPtr(CheckStep, "step", step);
  146. const exercises = self.exercises;
  147. const stderr_file = try fs.cwd().openFile(
  148. self.stderr.getPath(b),
  149. .{ .mode = .read_only },
  150. );
  151. defer stderr_file.close();
  152. const stderr = stderr_file.reader();
  153. for (exercises) |ex| {
  154. if (ex.number() == 1 and self.has_logo) {
  155. // Skip the logo.
  156. var buf: [80]u8 = undefined;
  157. var lineno: usize = 0;
  158. while (lineno < 8) : (lineno += 1) {
  159. _ = try readLine(stderr, &buf);
  160. }
  161. }
  162. try check_output(step, ex, stderr);
  163. }
  164. }
  165. fn check_output(step: *Step, exercise: Exercise, reader: Reader) !void {
  166. const b = step.owner;
  167. var buf: [1024]u8 = undefined;
  168. if (exercise.skip) {
  169. {
  170. const actual = try readLine(reader, &buf) orelse "EOF";
  171. const expect = b.fmt("Skipping {s}", .{exercise.main_file});
  172. try check(step, exercise, expect, actual);
  173. }
  174. {
  175. const actual = try readLine(reader, &buf) orelse "EOF";
  176. try check(step, exercise, "", actual);
  177. }
  178. return;
  179. }
  180. {
  181. const actual = try readLine(reader, &buf) orelse "EOF";
  182. const expect = b.fmt("Compiling {s}...", .{exercise.main_file});
  183. try check(step, exercise, expect, actual);
  184. }
  185. {
  186. const actual = try readLine(reader, &buf) orelse "EOF";
  187. const expect = b.fmt("Checking {s}...", .{exercise.main_file});
  188. try check(step, exercise, expect, actual);
  189. }
  190. {
  191. const actual = try readLine(reader, &buf) orelse "EOF";
  192. const expect = "PASSED:";
  193. try check(step, exercise, expect, actual);
  194. }
  195. // Skip the exercise output.
  196. const nlines = 1 + mem.count(u8, exercise.output, "\n") + 1;
  197. var lineno: usize = 0;
  198. while (lineno < nlines) : (lineno += 1) {
  199. _ = try readLine(reader, &buf) orelse @panic("EOF");
  200. }
  201. }
  202. fn check(
  203. step: *Step,
  204. exercise: Exercise,
  205. expect: []const u8,
  206. actual: []const u8,
  207. ) !void {
  208. if (!mem.eql(u8, expect, actual)) {
  209. return step.fail("{s}: expected to see \"{s}\", found \"{s}\"", .{
  210. exercise.main_file,
  211. expect,
  212. actual,
  213. });
  214. }
  215. }
  216. fn readLine(reader: fs.File.Reader, buf: []u8) !?[]const u8 {
  217. if (try reader.readUntilDelimiterOrEof(buf, '\n')) |line| {
  218. return mem.trimRight(u8, line, " \r\n");
  219. }
  220. return null;
  221. }
  222. };
  223. // A step that will fail.
  224. const FailStep = struct {
  225. step: Step,
  226. error_msg: []const u8,
  227. pub fn create(owner: *Build, error_msg: []const u8) *FailStep {
  228. const self = owner.allocator.create(FailStep) catch @panic("OOM");
  229. self.* = .{
  230. .step = Step.init(.{
  231. .id = .custom,
  232. .name = "fail",
  233. .owner = owner,
  234. .makeFn = make,
  235. }),
  236. .error_msg = error_msg,
  237. };
  238. return self;
  239. }
  240. fn make(step: *Step, _: *std.Progress.Node) !void {
  241. const b = step.owner;
  242. const self = @fieldParentPtr(FailStep, "step", step);
  243. try step.result_error_msgs.append(b.allocator, self.error_msg);
  244. return error.MakeFailed;
  245. }
  246. };
  247. // A variant of `std.Build.Step.fail` that does not return an error so that it
  248. // can be used in the configuration phase. It returns a FailStep, so that the
  249. // error will be cleanly handled by the build runner.
  250. fn fail(step: *Step, comptime format: []const u8, args: anytype) *Step {
  251. const b = step.owner;
  252. const fail_step = FailStep.create(b, b.fmt(format, args));
  253. step.dependOn(&fail_step.step);
  254. return step;
  255. }
  256. // Heals all the exercises.
  257. fn heal(allocator: Allocator, exercises: []const Exercise, outdir: []const u8) !void {
  258. const join = fs.path.join;
  259. const exercises_path = "exercises";
  260. const patches_path = "patches/patches";
  261. for (exercises) |ex| {
  262. const name = ex.baseName();
  263. // Use the POSIX patch variant.
  264. const file = try join(allocator, &.{ exercises_path, ex.main_file });
  265. const patch = b: {
  266. const patch_name = try fmt.allocPrint(allocator, "{s}.patch", .{name});
  267. break :b try join(allocator, &.{ patches_path, patch_name });
  268. };
  269. const output = try join(allocator, &.{ outdir, ex.main_file });
  270. const argv = &.{ "patch", "-i", patch, "-o", output, "-s", file };
  271. var child = std.process.Child.init(argv, allocator);
  272. _ = try child.spawnAndWait();
  273. }
  274. }
  275. //
  276. // Missing functions from std.Build.RunStep
  277. //
  278. /// Adds a check for stderr match. Does not add any other checks.
  279. pub fn expectStdErrMatch(self: *RunStep, bytes: []const u8) void {
  280. const new_check: RunStep.StdIo.Check = .{
  281. .expect_stderr_match = self.step.owner.dupe(bytes),
  282. };
  283. self.addCheck(new_check);
  284. }
  285. /// Adds a check for stdout match as well as a check for exit code 0, if
  286. /// there is not already an expected termination check.
  287. pub fn expectStdOutMatch(self: *RunStep, bytes: []const u8) void {
  288. const new_check: RunStep.StdIo.Check = .{
  289. .expect_stdout_match = self.step.owner.dupe(bytes),
  290. };
  291. self.addCheck(new_check);
  292. if (!self.hasTermCheck()) {
  293. self.expectExitCode(0);
  294. }
  295. }