tests.zig 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. if (ex.check_stdout) {
  38. expectStdOutMatch(cmd, ex.output);
  39. cmd.expectStdErrEqual("");
  40. } else {
  41. expectStdErrMatch(cmd, ex.output);
  42. cmd.expectStdOutEqual("");
  43. }
  44. cmd.step.dependOn(&heal_step.step);
  45. case_step.dependOn(&cmd.step);
  46. }
  47. const cleanup = b.addRemoveDirTree(tmp_path);
  48. cleanup.step.dependOn(case_step);
  49. step.dependOn(&cleanup.step);
  50. }
  51. {
  52. // Test that `zig build -Dhealed -Dn=n test` skips disabled esercises.
  53. const case_step = createCase(b, "case-2");
  54. const tmp_path = makeTempPath(b) catch |err| {
  55. return fail(step, "unable to make tmp path: {s}\n", .{@errorName(err)});
  56. };
  57. const heal_step = HealStep.create(b, exercises, tmp_path);
  58. for (exercises[0 .. exercises.len - 1]) |ex| {
  59. const n = ex.number();
  60. if (!ex.skip) continue;
  61. const cmd = b.addSystemCommand(&.{
  62. b.zig_exe,
  63. "build",
  64. "-Dhealed",
  65. b.fmt("-Dhealed-path={s}", .{tmp_path}),
  66. b.fmt("-Dn={}", .{n}),
  67. "test",
  68. });
  69. cmd.setName(b.fmt("zig build -Dhealed -Dn={} test", .{n}));
  70. cmd.expectExitCode(0);
  71. cmd.expectStdOutEqual("");
  72. expectStdErrMatch(cmd, b.fmt("{s} skipped", .{ex.main_file}));
  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. cmd.setName("zig build -Dn=1");
  138. cmd.expectExitCode(1);
  139. expectStdErrMatch(cmd, exercises[0].hint orelse "");
  140. cmd.step.dependOn(case_step);
  141. step.dependOn(&cmd.step);
  142. }
  143. return step;
  144. }
  145. fn createCase(b: *Build, name: []const u8) *Step {
  146. const case_step = b.allocator.create(Step) catch @panic("OOM");
  147. case_step.* = Step.init(.{
  148. .id = .custom,
  149. .name = name,
  150. .owner = b,
  151. });
  152. return case_step;
  153. }
  154. /// Checks the output of `zig build` or `zig build -Dn=1 start`.
  155. const CheckStep = struct {
  156. step: Step,
  157. exercises: []const Exercise,
  158. stderr: FileSource,
  159. has_logo: bool,
  160. pub fn create(
  161. owner: *Build,
  162. exercises: []const Exercise,
  163. stderr: FileSource,
  164. has_logo: bool,
  165. ) *CheckStep {
  166. const self = owner.allocator.create(CheckStep) catch @panic("OOM");
  167. self.* = .{
  168. .step = Step.init(.{
  169. .id = .custom,
  170. .name = "check",
  171. .owner = owner,
  172. .makeFn = make,
  173. }),
  174. .exercises = exercises,
  175. .stderr = stderr,
  176. .has_logo = has_logo,
  177. };
  178. return self;
  179. }
  180. fn make(step: *Step, _: *std.Progress.Node) !void {
  181. const b = step.owner;
  182. const self = @fieldParentPtr(CheckStep, "step", step);
  183. const exercises = self.exercises;
  184. const stderr_file = try fs.cwd().openFile(
  185. self.stderr.getPath(b),
  186. .{ .mode = .read_only },
  187. );
  188. defer stderr_file.close();
  189. const stderr = stderr_file.reader();
  190. for (exercises) |ex| {
  191. if (ex.number() == 1 and self.has_logo) {
  192. // Skip the logo.
  193. var buf: [80]u8 = undefined;
  194. var lineno: usize = 0;
  195. while (lineno < 8) : (lineno += 1) {
  196. _ = try readLine(stderr, &buf);
  197. }
  198. }
  199. try check_output(step, ex, stderr);
  200. }
  201. }
  202. fn check_output(step: *Step, exercise: Exercise, reader: Reader) !void {
  203. const b = step.owner;
  204. var buf: [1024]u8 = undefined;
  205. if (exercise.skip) {
  206. {
  207. const actual = try readLine(reader, &buf) orelse "EOF";
  208. const expect = b.fmt("Skipping {s}", .{exercise.main_file});
  209. try check(step, exercise, expect, actual);
  210. }
  211. {
  212. const actual = try readLine(reader, &buf) orelse "EOF";
  213. try check(step, exercise, "", actual);
  214. }
  215. return;
  216. }
  217. {
  218. const actual = try readLine(reader, &buf) orelse "EOF";
  219. const expect = b.fmt("Compiling {s}...", .{exercise.main_file});
  220. try check(step, exercise, expect, actual);
  221. }
  222. {
  223. const actual = try readLine(reader, &buf) orelse "EOF";
  224. const expect = b.fmt("Checking {s}...", .{exercise.main_file});
  225. try check(step, exercise, expect, actual);
  226. }
  227. {
  228. const actual = try readLine(reader, &buf) orelse "EOF";
  229. const expect = "PASSED:";
  230. try check(step, exercise, expect, actual);
  231. }
  232. // Skip the exercise output.
  233. const nlines = 1 + mem.count(u8, exercise.output, "\n") + 1;
  234. var lineno: usize = 0;
  235. while (lineno < nlines) : (lineno += 1) {
  236. _ = try readLine(reader, &buf) orelse @panic("EOF");
  237. }
  238. }
  239. fn check(
  240. step: *Step,
  241. exercise: Exercise,
  242. expect: []const u8,
  243. actual: []const u8,
  244. ) !void {
  245. if (!mem.eql(u8, expect, actual)) {
  246. return step.fail("{s}: expected to see \"{s}\", found \"{s}\"", .{
  247. exercise.main_file,
  248. expect,
  249. actual,
  250. });
  251. }
  252. }
  253. fn readLine(reader: fs.File.Reader, buf: []u8) !?[]const u8 {
  254. if (try reader.readUntilDelimiterOrEof(buf, '\n')) |line| {
  255. return mem.trimRight(u8, line, " \r\n");
  256. }
  257. return null;
  258. }
  259. };
  260. /// Fails with a custom error message.
  261. const FailStep = struct {
  262. step: Step,
  263. error_msg: []const u8,
  264. pub fn create(owner: *Build, error_msg: []const u8) *FailStep {
  265. const self = owner.allocator.create(FailStep) catch @panic("OOM");
  266. self.* = .{
  267. .step = Step.init(.{
  268. .id = .custom,
  269. .name = "fail",
  270. .owner = owner,
  271. .makeFn = make,
  272. }),
  273. .error_msg = error_msg,
  274. };
  275. return self;
  276. }
  277. fn make(step: *Step, _: *std.Progress.Node) !void {
  278. const b = step.owner;
  279. const self = @fieldParentPtr(FailStep, "step", step);
  280. try step.result_error_msgs.append(b.allocator, self.error_msg);
  281. return error.MakeFailed;
  282. }
  283. };
  284. /// A variant of `std.Build.Step.fail` that does not return an error so that it
  285. /// can be used in the configuration phase. It returns a FailStep, so that the
  286. /// error will be cleanly handled by the build runner.
  287. fn fail(step: *Step, comptime format: []const u8, args: anytype) *Step {
  288. const b = step.owner;
  289. const fail_step = FailStep.create(b, b.fmt(format, args));
  290. step.dependOn(&fail_step.step);
  291. return step;
  292. }
  293. /// Heals the exercises.
  294. const HealStep = struct {
  295. step: Step,
  296. exercises: []const Exercise,
  297. work_path: []const u8,
  298. pub fn create(owner: *Build, exercises: []const Exercise, work_path: []const u8) *HealStep {
  299. const self = owner.allocator.create(HealStep) catch @panic("OOM");
  300. self.* = .{
  301. .step = Step.init(.{
  302. .id = .custom,
  303. .name = "heal",
  304. .owner = owner,
  305. .makeFn = make,
  306. }),
  307. .exercises = exercises,
  308. .work_path = work_path,
  309. };
  310. return self;
  311. }
  312. fn make(step: *Step, _: *std.Progress.Node) !void {
  313. const b = step.owner;
  314. const self = @fieldParentPtr(HealStep, "step", step);
  315. return heal(b.allocator, self.exercises, self.work_path);
  316. }
  317. };
  318. /// Heals all the exercises.
  319. fn heal(allocator: Allocator, exercises: []const Exercise, work_path: []const u8) !void {
  320. const join = fs.path.join;
  321. const exercises_path = "exercises";
  322. const patches_path = "patches/patches";
  323. for (exercises) |ex| {
  324. const name = ex.name();
  325. const file = try join(allocator, &.{ exercises_path, ex.main_file });
  326. const patch = b: {
  327. const patch_name = try fmt.allocPrint(allocator, "{s}.patch", .{name});
  328. break :b try join(allocator, &.{ patches_path, patch_name });
  329. };
  330. const output = try join(allocator, &.{ work_path, ex.main_file });
  331. const argv = &.{ "patch", "-i", patch, "-o", output, "-s", file };
  332. var child = Child.init(argv, allocator);
  333. _ = try child.spawnAndWait();
  334. }
  335. }
  336. /// This function is the same as the one in std.Build.makeTempPath, with the
  337. /// difference that returns an error when the temp path cannot be created.
  338. pub fn makeTempPath(b: *Build) ![]const u8 {
  339. const rand_int = std.crypto.random.int(u64);
  340. const tmp_dir_sub_path = "tmp" ++ fs.path.sep_str ++ Build.hex64(rand_int);
  341. const path = b.cache_root.join(b.allocator, &.{tmp_dir_sub_path}) catch
  342. @panic("OOM");
  343. try b.cache_root.handle.makePath(tmp_dir_sub_path);
  344. return path;
  345. }
  346. //
  347. // Missing functions from std.Build.RunStep
  348. //
  349. /// Adds a check for stderr match. Does not add any other checks.
  350. pub fn expectStdErrMatch(self: *RunStep, bytes: []const u8) void {
  351. const new_check: RunStep.StdIo.Check = .{
  352. .expect_stderr_match = self.step.owner.dupe(bytes),
  353. };
  354. self.addCheck(new_check);
  355. }
  356. /// Adds a check for stdout match as well as a check for exit code 0, if
  357. /// there is not already an expected termination check.
  358. pub fn expectStdOutMatch(self: *RunStep, bytes: []const u8) void {
  359. const new_check: RunStep.StdIo.Check = .{
  360. .expect_stdout_match = self.step.owner.dupe(bytes),
  361. };
  362. self.addCheck(new_check);
  363. if (!self.hasTermCheck()) {
  364. self.expectExitCode(0);
  365. }
  366. }