tests.zig 11 KB

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