tests.zig 14 KB

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