tests.zig 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 test` 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. if (ex.skip) continue;
  27. const cmd = b.addSystemCommand(&.{
  28. b.zig_exe,
  29. "build",
  30. "-Dhealed",
  31. b.fmt("-Dhealed-path={s}", .{tmp_path}),
  32. b.fmt("-Dn={}", .{n}),
  33. "test",
  34. });
  35. cmd.setName(b.fmt("zig build -Dhealed -Dn={} test", .{n}));
  36. cmd.expectExitCode(0);
  37. cmd.step.dependOn(&heal_step.step);
  38. const output = if (ex.check_stdout)
  39. cmd.captureStdOut()
  40. else
  41. cmd.captureStdErr();
  42. const verify = CheckNamedStep.create(b, ex, output);
  43. verify.step.dependOn(&cmd.step);
  44. case_step.dependOn(&verify.step);
  45. }
  46. const cleanup = b.addRemoveDirTree(tmp_path);
  47. cleanup.step.dependOn(case_step);
  48. step.dependOn(&cleanup.step);
  49. }
  50. {
  51. // Test that `zig build -Dhealed -Dn=n test` skips disabled esercises.
  52. const case_step = createCase(b, "case-2");
  53. const tmp_path = makeTempPath(b) catch |err| {
  54. return fail(step, "unable to make tmp path: {s}\n", .{@errorName(err)});
  55. };
  56. const heal_step = HealStep.create(b, exercises, tmp_path);
  57. for (exercises[0 .. exercises.len - 1]) |ex| {
  58. const n = ex.number();
  59. if (!ex.skip) continue;
  60. const cmd = b.addSystemCommand(&.{
  61. b.zig_exe,
  62. "build",
  63. "-Dhealed",
  64. b.fmt("-Dhealed-path={s}", .{tmp_path}),
  65. b.fmt("-Dn={}", .{n}),
  66. "test",
  67. });
  68. cmd.setName(b.fmt("zig build -Dhealed -Dn={} test", .{n}));
  69. cmd.expectExitCode(0);
  70. cmd.expectStdOutEqual("");
  71. expectStdErrMatch(cmd, b.fmt("{s} skipped", .{ex.main_file}));
  72. cmd.step.dependOn(&heal_step.step);
  73. case_step.dependOn(&cmd.step);
  74. }
  75. const cleanup = b.addRemoveDirTree(tmp_path);
  76. cleanup.step.dependOn(case_step);
  77. step.dependOn(&cleanup.step);
  78. }
  79. {
  80. // Test that `zig build -Dhealed` process all the exercises in order.
  81. const case_step = createCase(b, "case-3");
  82. const tmp_path = makeTempPath(b) catch |err| {
  83. return fail(step, "unable to make tmp path: {s}\n", .{@errorName(err)});
  84. };
  85. const heal_step = HealStep.create(b, exercises, tmp_path);
  86. heal_step.step.dependOn(case_step);
  87. // TODO: when an exercise is modified, the cache is not invalidated.
  88. const cmd = b.addSystemCommand(&.{
  89. b.zig_exe,
  90. "build",
  91. "-Dhealed",
  92. b.fmt("-Dhealed-path={s}", .{tmp_path}),
  93. });
  94. cmd.setName("zig build -Dhealed");
  95. cmd.expectExitCode(0);
  96. cmd.step.dependOn(&heal_step.step);
  97. const stderr = cmd.captureStdErr();
  98. const verify = CheckStep.create(b, exercises, stderr, true);
  99. verify.step.dependOn(&cmd.step);
  100. const cleanup = b.addRemoveDirTree(tmp_path);
  101. cleanup.step.dependOn(&verify.step);
  102. step.dependOn(&cleanup.step);
  103. }
  104. {
  105. // Test that `zig build -Dhealed -Dn=1 start` process all the exercises
  106. // in order.
  107. const case_step = createCase(b, "case-4");
  108. const tmp_path = makeTempPath(b) catch |err| {
  109. return fail(step, "unable to make tmp path: {s}\n", .{@errorName(err)});
  110. };
  111. const heal_step = HealStep.create(b, exercises, tmp_path);
  112. heal_step.step.dependOn(case_step);
  113. // TODO: when an exercise is modified, the cache is not invalidated.
  114. const cmd = b.addSystemCommand(&.{
  115. b.zig_exe,
  116. "build",
  117. "-Dhealed",
  118. b.fmt("-Dhealed-path={s}", .{tmp_path}),
  119. "-Dn=1",
  120. "start",
  121. });
  122. cmd.setName("zig build -Dhealed -Dn=1 start");
  123. cmd.expectExitCode(0);
  124. cmd.step.dependOn(&heal_step.step);
  125. const stderr = cmd.captureStdErr();
  126. const verify = CheckStep.create(b, exercises, stderr, false);
  127. verify.step.dependOn(&cmd.step);
  128. const cleanup = b.addRemoveDirTree(tmp_path);
  129. cleanup.step.dependOn(&verify.step);
  130. step.dependOn(&cleanup.step);
  131. }
  132. {
  133. // Test that `zig build -Dn=1` prints the hint.
  134. const case_step = createCase(b, "case-5");
  135. const cmd = b.addSystemCommand(&.{ b.zig_exe, "build", "-Dn=1" });
  136. cmd.setName("zig build -Dn=1");
  137. cmd.expectExitCode(1);
  138. expectStdErrMatch(cmd, exercises[0].hint orelse "");
  139. cmd.step.dependOn(case_step);
  140. step.dependOn(&cmd.step);
  141. }
  142. return step;
  143. }
  144. fn createCase(b: *Build, name: []const u8) *Step {
  145. const case_step = b.allocator.create(Step) catch @panic("OOM");
  146. case_step.* = Step.init(.{
  147. .id = .custom,
  148. .name = name,
  149. .owner = b,
  150. });
  151. return case_step;
  152. }
  153. /// Checks the output of `zig build -Dn=n test`.
  154. const CheckNamedStep = struct {
  155. step: Step,
  156. exercise: Exercise,
  157. output: FileSource,
  158. pub fn create(owner: *Build, exercise: Exercise, output: FileSource) *CheckNamedStep {
  159. const self = owner.allocator.create(CheckNamedStep) catch @panic("OOM");
  160. self.* = .{
  161. .step = Step.init(.{
  162. .id = .custom,
  163. .name = "check-named",
  164. .owner = owner,
  165. .makeFn = make,
  166. }),
  167. .exercise = exercise,
  168. .output = output,
  169. };
  170. return self;
  171. }
  172. fn make(step: *Step, _: *std.Progress.Node) !void {
  173. const b = step.owner;
  174. const self = @fieldParentPtr(CheckNamedStep, "step", step);
  175. // Allow up to 1 MB of output capture.
  176. const max_bytes = 1 * 1024 * 1024;
  177. const path = self.output.getPath(b);
  178. const raw_output = try fs.cwd().readFileAlloc(b.allocator, path, max_bytes);
  179. const actual = try root.trimLines(b.allocator, raw_output);
  180. const expect = self.exercise.output;
  181. if (!mem.eql(u8, expect, actual)) {
  182. return step.fail("{s}: expected to see \"{s}\", found \"{s}\"", .{
  183. self.exercise.main_file, expect, actual,
  184. });
  185. }
  186. }
  187. };
  188. /// Checks the output of `zig build` or `zig build -Dn=1 start`.
  189. const CheckStep = struct {
  190. step: Step,
  191. exercises: []const Exercise,
  192. stderr: FileSource,
  193. has_logo: bool,
  194. pub fn create(
  195. owner: *Build,
  196. exercises: []const Exercise,
  197. stderr: FileSource,
  198. has_logo: bool,
  199. ) *CheckStep {
  200. const self = owner.allocator.create(CheckStep) catch @panic("OOM");
  201. self.* = .{
  202. .step = Step.init(.{
  203. .id = .custom,
  204. .name = "check",
  205. .owner = owner,
  206. .makeFn = make,
  207. }),
  208. .exercises = exercises,
  209. .stderr = stderr,
  210. .has_logo = has_logo,
  211. };
  212. return self;
  213. }
  214. fn make(step: *Step, _: *std.Progress.Node) !void {
  215. const b = step.owner;
  216. const self = @fieldParentPtr(CheckStep, "step", step);
  217. const exercises = self.exercises;
  218. const stderr_file = try fs.cwd().openFile(
  219. self.stderr.getPath(b),
  220. .{ .mode = .read_only },
  221. );
  222. defer stderr_file.close();
  223. const stderr = stderr_file.reader();
  224. for (exercises) |ex| {
  225. if (ex.number() == 1 and self.has_logo) {
  226. // Skip the logo.
  227. var buf: [80]u8 = undefined;
  228. var lineno: usize = 0;
  229. while (lineno < 8) : (lineno += 1) {
  230. _ = try readLine(stderr, &buf);
  231. }
  232. }
  233. try check_output(step, ex, stderr);
  234. }
  235. }
  236. fn check_output(step: *Step, exercise: Exercise, reader: Reader) !void {
  237. const b = step.owner;
  238. var buf: [1024]u8 = undefined;
  239. if (exercise.skip) {
  240. {
  241. const actual = try readLine(reader, &buf) orelse "EOF";
  242. const expect = b.fmt("Skipping {s}", .{exercise.main_file});
  243. try check(step, exercise, expect, actual);
  244. }
  245. {
  246. const actual = try readLine(reader, &buf) orelse "EOF";
  247. try check(step, exercise, "", actual);
  248. }
  249. return;
  250. }
  251. {
  252. const actual = try readLine(reader, &buf) orelse "EOF";
  253. const expect = b.fmt("Compiling {s}...", .{exercise.main_file});
  254. try check(step, exercise, expect, actual);
  255. }
  256. {
  257. const actual = try readLine(reader, &buf) orelse "EOF";
  258. const expect = b.fmt("Checking {s}...", .{exercise.main_file});
  259. try check(step, exercise, expect, actual);
  260. }
  261. {
  262. const actual = try readLine(reader, &buf) orelse "EOF";
  263. const expect = "PASSED:";
  264. try check(step, exercise, expect, actual);
  265. }
  266. // Skip the exercise output.
  267. const nlines = 1 + mem.count(u8, exercise.output, "\n") + 1;
  268. var lineno: usize = 0;
  269. while (lineno < nlines) : (lineno += 1) {
  270. _ = try readLine(reader, &buf) orelse @panic("EOF");
  271. }
  272. }
  273. fn check(
  274. step: *Step,
  275. exercise: Exercise,
  276. expect: []const u8,
  277. actual: []const u8,
  278. ) !void {
  279. if (!mem.eql(u8, expect, actual)) {
  280. return step.fail("{s}: expected to see \"{s}\", found \"{s}\"", .{
  281. exercise.main_file,
  282. expect,
  283. actual,
  284. });
  285. }
  286. }
  287. fn readLine(reader: fs.File.Reader, buf: []u8) !?[]const u8 {
  288. if (try reader.readUntilDelimiterOrEof(buf, '\n')) |line| {
  289. return mem.trimRight(u8, line, " \r\n");
  290. }
  291. return null;
  292. }
  293. };
  294. /// Fails with a custom error message.
  295. const FailStep = struct {
  296. step: Step,
  297. error_msg: []const u8,
  298. pub fn create(owner: *Build, error_msg: []const u8) *FailStep {
  299. const self = owner.allocator.create(FailStep) catch @panic("OOM");
  300. self.* = .{
  301. .step = Step.init(.{
  302. .id = .custom,
  303. .name = "fail",
  304. .owner = owner,
  305. .makeFn = make,
  306. }),
  307. .error_msg = error_msg,
  308. };
  309. return self;
  310. }
  311. fn make(step: *Step, _: *std.Progress.Node) !void {
  312. const b = step.owner;
  313. const self = @fieldParentPtr(FailStep, "step", step);
  314. try step.result_error_msgs.append(b.allocator, self.error_msg);
  315. return error.MakeFailed;
  316. }
  317. };
  318. /// A variant of `std.Build.Step.fail` that does not return an error so that it
  319. /// can be used in the configuration phase. It returns a FailStep, so that the
  320. /// error will be cleanly handled by the build runner.
  321. fn fail(step: *Step, comptime format: []const u8, args: anytype) *Step {
  322. const b = step.owner;
  323. const fail_step = FailStep.create(b, b.fmt(format, args));
  324. step.dependOn(&fail_step.step);
  325. return step;
  326. }
  327. /// Heals the exercises.
  328. const HealStep = struct {
  329. step: Step,
  330. exercises: []const Exercise,
  331. work_path: []const u8,
  332. pub fn create(owner: *Build, exercises: []const Exercise, work_path: []const u8) *HealStep {
  333. const self = owner.allocator.create(HealStep) catch @panic("OOM");
  334. self.* = .{
  335. .step = Step.init(.{
  336. .id = .custom,
  337. .name = "heal",
  338. .owner = owner,
  339. .makeFn = make,
  340. }),
  341. .exercises = exercises,
  342. .work_path = work_path,
  343. };
  344. return self;
  345. }
  346. fn make(step: *Step, _: *std.Progress.Node) !void {
  347. const b = step.owner;
  348. const self = @fieldParentPtr(HealStep, "step", step);
  349. return heal(b.allocator, self.exercises, self.work_path);
  350. }
  351. };
  352. /// Heals all the exercises.
  353. fn heal(allocator: Allocator, exercises: []const Exercise, work_path: []const u8) !void {
  354. const join = fs.path.join;
  355. const exercises_path = "exercises";
  356. const patches_path = "patches/patches";
  357. for (exercises) |ex| {
  358. const name = ex.name();
  359. const file = try join(allocator, &.{ exercises_path, ex.main_file });
  360. const patch = b: {
  361. const patch_name = try fmt.allocPrint(allocator, "{s}.patch", .{name});
  362. break :b try join(allocator, &.{ patches_path, patch_name });
  363. };
  364. const output = try join(allocator, &.{ work_path, ex.main_file });
  365. const argv = &.{ "patch", "-i", patch, "-o", output, "-s", file };
  366. var child = Child.init(argv, allocator);
  367. _ = try child.spawnAndWait();
  368. }
  369. }
  370. /// This function is the same as the one in std.Build.makeTempPath, with the
  371. /// difference that returns an error when the temp path cannot be created.
  372. pub fn makeTempPath(b: *Build) ![]const u8 {
  373. const rand_int = std.crypto.random.int(u64);
  374. const tmp_dir_sub_path = "tmp" ++ fs.path.sep_str ++ Build.hex64(rand_int);
  375. const path = b.cache_root.join(b.allocator, &.{tmp_dir_sub_path}) catch
  376. @panic("OOM");
  377. try b.cache_root.handle.makePath(tmp_dir_sub_path);
  378. return path;
  379. }
  380. //
  381. // Missing functions from std.Build.RunStep
  382. //
  383. /// Adds a check for stderr match. Does not add any other checks.
  384. pub fn expectStdErrMatch(self: *RunStep, bytes: []const u8) void {
  385. const new_check: RunStep.StdIo.Check = .{
  386. .expect_stderr_match = self.step.owner.dupe(bytes),
  387. };
  388. self.addCheck(new_check);
  389. }
  390. /// Adds a check for stdout match as well as a check for exit code 0, if
  391. /// there is not already an expected termination check.
  392. pub fn expectStdOutMatch(self: *RunStep, bytes: []const u8) void {
  393. const new_check: RunStep.StdIo.Check = .{
  394. .expect_stdout_match = self.step.owner.dupe(bytes),
  395. };
  396. self.addCheck(new_check);
  397. if (!self.hasTermCheck()) {
  398. self.expectExitCode(0);
  399. }
  400. }