tests.zig 12 KB

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