tests.zig 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. try check_output(step, ex, stderr);
  122. }
  123. };
  124. /// Checks the output of `zig build`.
  125. const CheckStep = struct {
  126. step: Step,
  127. exercises: []const Exercise,
  128. stderr: FileSource,
  129. pub fn create(
  130. owner: *Build,
  131. exercises: []const Exercise,
  132. stderr: FileSource,
  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. };
  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) {
  159. // Skip the logo.
  160. const nlines = mem.count(u8, root.logo, "\n");
  161. var buf: [80]u8 = undefined;
  162. var lineno: usize = 0;
  163. while (lineno < nlines) : (lineno += 1) {
  164. _ = try readLine(stderr, &buf);
  165. }
  166. }
  167. try check_output(step, ex, stderr);
  168. }
  169. }
  170. };
  171. fn check_output(step: *Step, exercise: Exercise, reader: Reader) !void {
  172. const b = step.owner;
  173. var buf: [1024]u8 = undefined;
  174. if (exercise.skip) {
  175. {
  176. const actual = try readLine(reader, &buf) orelse "EOF";
  177. const expect = b.fmt("Skipping {s}", .{exercise.main_file});
  178. try check(step, exercise, expect, actual);
  179. }
  180. {
  181. const actual = try readLine(reader, &buf) orelse "EOF";
  182. try check(step, exercise, "", actual);
  183. }
  184. return;
  185. }
  186. {
  187. const actual = try readLine(reader, &buf) orelse "EOF";
  188. const expect = b.fmt("Compiling {s}...", .{exercise.main_file});
  189. try check(step, exercise, expect, actual);
  190. }
  191. {
  192. const actual = try readLine(reader, &buf) orelse "EOF";
  193. const expect = b.fmt("Checking {s}...", .{exercise.main_file});
  194. try check(step, exercise, expect, actual);
  195. }
  196. {
  197. const actual = try readLine(reader, &buf) orelse "EOF";
  198. const expect = "PASSED:";
  199. try check(step, exercise, expect, actual);
  200. }
  201. // Skip the exercise output.
  202. const nlines = 1 + mem.count(u8, exercise.output, "\n") + 1;
  203. var lineno: usize = 0;
  204. while (lineno < nlines) : (lineno += 1) {
  205. _ = try readLine(reader, &buf) orelse @panic("EOF");
  206. }
  207. }
  208. fn check(
  209. step: *Step,
  210. exercise: Exercise,
  211. expect: []const u8,
  212. actual: []const u8,
  213. ) !void {
  214. if (!mem.eql(u8, expect, actual)) {
  215. return step.fail("{s}: expected to see \"{s}\", found \"{s}\"", .{
  216. exercise.main_file,
  217. expect,
  218. actual,
  219. });
  220. }
  221. }
  222. fn readLine(reader: fs.File.Reader, buf: []u8) !?[]const u8 {
  223. if (try reader.readUntilDelimiterOrEof(buf, '\n')) |line| {
  224. return mem.trimRight(u8, line, " \r\n");
  225. }
  226. return null;
  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 sep = std.fs.path.sep_str;
  289. const join = fs.path.join;
  290. const exercises_path = "exercises";
  291. const patches_path = "patches" ++ sep ++ "patches";
  292. for (exercises) |ex| {
  293. const name = ex.name();
  294. const file = try join(allocator, &.{ exercises_path, ex.main_file });
  295. const patch = b: {
  296. const patch_name = try fmt.allocPrint(allocator, "{s}.patch", .{name});
  297. break :b try join(allocator, &.{ patches_path, patch_name });
  298. };
  299. const output = try join(allocator, &.{ work_path, ex.main_file });
  300. const argv = &.{ "patch", "-i", patch, "-o", output, "-s", file };
  301. var child = Child.init(argv, allocator);
  302. _ = try child.spawnAndWait();
  303. }
  304. }
  305. /// This function is the same as the one in std.Build.makeTempPath, with the
  306. /// difference that returns an error when the temp path cannot be created.
  307. pub fn makeTempPath(b: *Build) ![]const u8 {
  308. const rand_int = std.crypto.random.int(u64);
  309. const tmp_dir_sub_path = "tmp" ++ fs.path.sep_str ++ Build.hex64(rand_int);
  310. const path = b.cache_root.join(b.allocator, &.{tmp_dir_sub_path}) catch
  311. @panic("OOM");
  312. try b.cache_root.handle.makePath(tmp_dir_sub_path);
  313. return path;
  314. }