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