tests.zig 12 KB

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