tests.zig 12 KB

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