tests.zig 12 KB

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