tests.zig 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 Build = std.build;
  9. const FileSource = std.Build.FileSource;
  10. const Reader = fs.File.Reader;
  11. const RunStep = std.Build.RunStep;
  12. const Step = Build.Step;
  13. const Exercise = root.Exercise;
  14. pub fn addCliTests(b: *std.Build, exercises: []const Exercise) *Step {
  15. const step = b.step("test-cli", "Test the command line interface");
  16. // We should use a temporary path, but it will make the implementation of
  17. // `build.zig` more complex.
  18. const outdir = "patches/healed";
  19. fs.cwd().makePath(outdir) catch |err| {
  20. return fail(step, "unable to make '{s}': {s}\n", .{ outdir, @errorName(err) });
  21. };
  22. heal(b.allocator, exercises, outdir) catch |err| {
  23. return fail(step, "unable to heal exercises: {s}\n", .{@errorName(err)});
  24. };
  25. {
  26. // Test that `zig build -Dn=n -Dhealed test` selects the nth exercise.
  27. const case_step = createCase(b, "case-1");
  28. var i: usize = 0;
  29. for (exercises[0 .. exercises.len - 1]) |ex| {
  30. i += 1;
  31. if (ex.skip) continue;
  32. const cmd = b.addSystemCommand(
  33. &.{ b.zig_exe, "build", b.fmt("-Dn={}", .{i}), "-Dhealed", "test" },
  34. );
  35. cmd.setName(b.fmt("zig build -D={} -Dhealed test", .{i}));
  36. cmd.expectExitCode(0);
  37. // Some exercise output has an extra space character.
  38. if (ex.check_stdout)
  39. expectStdOutMatch(cmd, ex.output)
  40. else
  41. expectStdErrMatch(cmd, ex.output);
  42. case_step.dependOn(&cmd.step);
  43. }
  44. step.dependOn(case_step);
  45. }
  46. {
  47. // Test that `zig build -Dn=n -Dhealed test` skips disabled esercises.
  48. const case_step = createCase(b, "case-2");
  49. var i: usize = 0;
  50. for (exercises[0 .. exercises.len - 1]) |ex| {
  51. i += 1;
  52. if (!ex.skip) continue;
  53. const cmd = b.addSystemCommand(
  54. &.{ b.zig_exe, "build", b.fmt("-Dn={}", .{i}), "-Dhealed", "test" },
  55. );
  56. cmd.setName(b.fmt("zig build -D={} -Dhealed test", .{i}));
  57. cmd.expectExitCode(0);
  58. cmd.expectStdOutEqual("");
  59. expectStdErrMatch(cmd, b.fmt("{s} skipped", .{ex.main_file}));
  60. case_step.dependOn(&cmd.step);
  61. }
  62. step.dependOn(case_step);
  63. }
  64. {
  65. // Test that `zig build -Dhealed` process all the exercises in order.
  66. const case_step = createCase(b, "case-3");
  67. // TODO: when an exercise is modified, the cache is not invalidated.
  68. const cmd = b.addSystemCommand(&.{ b.zig_exe, "build", "-Dhealed" });
  69. cmd.setName("zig build -Dhealed");
  70. cmd.expectExitCode(0);
  71. const stderr = cmd.captureStdErr();
  72. const verify = CheckStep.create(b, exercises, stderr, true);
  73. verify.step.dependOn(&cmd.step);
  74. case_step.dependOn(&verify.step);
  75. step.dependOn(case_step);
  76. }
  77. {
  78. // Test that `zig build -Dhealed -Dn=1 start` process all the exercises
  79. // in order.
  80. const case_step = createCase(b, "case-4");
  81. // TODO: when an exercise is modified, the cache is not invalidated.
  82. const cmd = b.addSystemCommand(
  83. &.{ b.zig_exe, "build", "-Dhealed", "-Dn=1", "start" },
  84. );
  85. cmd.setName("zig build -Dhealed -Dn=1 start");
  86. cmd.expectExitCode(0);
  87. const stderr = cmd.captureStdErr();
  88. const verify = CheckStep.create(b, exercises, stderr, false);
  89. verify.step.dependOn(&cmd.step);
  90. case_step.dependOn(&verify.step);
  91. step.dependOn(case_step);
  92. }
  93. // Don't add the cleanup step, since it may delete outdir while a test case
  94. // is running.
  95. //const cleanup = b.addRemoveDirTree(outdir);
  96. //step.dependOn(&cleanup.step);
  97. return step;
  98. }
  99. fn createCase(b: *Build, name: []const u8) *Step {
  100. const case_step = b.allocator.create(Step) catch @panic("OOM");
  101. case_step.* = Step.init(.{
  102. .id = .custom,
  103. .name = name,
  104. .owner = b,
  105. });
  106. return case_step;
  107. }
  108. // Check the output of `zig build` or `zig build -Dn=1 start`.
  109. const CheckStep = struct {
  110. step: Step,
  111. exercises: []const Exercise,
  112. stderr: FileSource,
  113. has_logo: bool,
  114. pub fn create(
  115. owner: *Build,
  116. exercises: []const Exercise,
  117. stderr: FileSource,
  118. has_logo: bool,
  119. ) *CheckStep {
  120. const self = owner.allocator.create(CheckStep) catch @panic("OOM");
  121. self.* = .{
  122. .step = Step.init(.{
  123. .id = .custom,
  124. .name = "check",
  125. .owner = owner,
  126. .makeFn = make,
  127. }),
  128. .exercises = exercises,
  129. .stderr = stderr,
  130. .has_logo = has_logo,
  131. };
  132. return self;
  133. }
  134. fn make(step: *Step, _: *std.Progress.Node) !void {
  135. const b = step.owner;
  136. const self = @fieldParentPtr(CheckStep, "step", step);
  137. const exercises = self.exercises;
  138. const stderr_file = try fs.cwd().openFile(
  139. self.stderr.getPath(b),
  140. .{ .mode = .read_only },
  141. );
  142. defer stderr_file.close();
  143. const stderr = stderr_file.reader();
  144. for (exercises) |ex| {
  145. if (ex.number() == 1 and self.has_logo) {
  146. // Skip the logo.
  147. var buf: [80]u8 = undefined;
  148. var lineno: usize = 0;
  149. while (lineno < 8) : (lineno += 1) {
  150. _ = try readLine(stderr, &buf);
  151. }
  152. }
  153. try check_output(step, ex, stderr);
  154. }
  155. }
  156. fn check_output(step: *Step, exercise: Exercise, reader: Reader) !void {
  157. const b = step.owner;
  158. var buf: [1024]u8 = undefined;
  159. if (exercise.skip) {
  160. {
  161. const actual = try readLine(reader, &buf) orelse "EOF";
  162. const expect = b.fmt("Skipping {s}", .{exercise.main_file});
  163. try check(step, exercise, expect, actual);
  164. }
  165. {
  166. const actual = try readLine(reader, &buf) orelse "EOF";
  167. try check(step, exercise, "", actual);
  168. }
  169. return;
  170. }
  171. {
  172. const actual = try readLine(reader, &buf) orelse "EOF";
  173. const expect = b.fmt("Compiling {s}...", .{exercise.main_file});
  174. try check(step, exercise, expect, actual);
  175. }
  176. {
  177. const actual = try readLine(reader, &buf) orelse "EOF";
  178. const expect = b.fmt("Checking {s}...", .{exercise.main_file});
  179. try check(step, exercise, expect, actual);
  180. }
  181. {
  182. const actual = try readLine(reader, &buf) orelse "EOF";
  183. const expect = "PASSED:";
  184. try check(step, exercise, expect, actual);
  185. }
  186. // Skip the exercise output.
  187. const nlines = 1 + mem.count(u8, exercise.output, "\n") + 1;
  188. var lineno: usize = 0;
  189. while (lineno < nlines) : (lineno += 1) {
  190. _ = try readLine(reader, &buf) orelse @panic("EOF");
  191. }
  192. }
  193. fn check(
  194. step: *Step,
  195. exercise: Exercise,
  196. expect: []const u8,
  197. actual: []const u8,
  198. ) !void {
  199. if (!mem.eql(u8, expect, actual)) {
  200. return step.fail("{s}: expected to see \"{s}\", found \"{s}\"", .{
  201. exercise.main_file,
  202. expect,
  203. actual,
  204. });
  205. }
  206. }
  207. fn readLine(reader: fs.File.Reader, buf: []u8) !?[]const u8 {
  208. if (try reader.readUntilDelimiterOrEof(buf, '\n')) |line| {
  209. return mem.trimRight(u8, line, " \r\n");
  210. }
  211. return null;
  212. }
  213. };
  214. // A step that will fail.
  215. const FailStep = struct {
  216. step: Step,
  217. error_msg: []const u8,
  218. pub fn create(owner: *Build, error_msg: []const u8) *FailStep {
  219. const self = owner.allocator.create(FailStep) catch @panic("OOM");
  220. self.* = .{
  221. .step = Step.init(.{
  222. .id = .custom,
  223. .name = "fail",
  224. .owner = owner,
  225. .makeFn = make,
  226. }),
  227. .error_msg = error_msg,
  228. };
  229. return self;
  230. }
  231. fn make(step: *Step, _: *std.Progress.Node) !void {
  232. const b = step.owner;
  233. const self = @fieldParentPtr(FailStep, "step", step);
  234. try step.result_error_msgs.append(b.allocator, self.error_msg);
  235. return error.MakeFailed;
  236. }
  237. };
  238. // A variant of `std.Build.Step.fail` that does not return an error so that it
  239. // can be used in the configuration phase. It returns a FailStep, so that the
  240. // error will be cleanly handled by the build runner.
  241. fn fail(step: *Step, comptime format: []const u8, args: anytype) *Step {
  242. const b = step.owner;
  243. const fail_step = FailStep.create(b, b.fmt(format, args));
  244. step.dependOn(&fail_step.step);
  245. return step;
  246. }
  247. // Heals all the exercises.
  248. fn heal(allocator: Allocator, exercises: []const Exercise, outdir: []const u8) !void {
  249. const join = fs.path.join;
  250. const exercises_path = "exercises";
  251. const patches_path = "patches/patches";
  252. for (exercises) |ex| {
  253. const name = ex.baseName();
  254. // Use the POSIX patch variant.
  255. const file = try join(allocator, &.{ exercises_path, ex.main_file });
  256. const patch = b: {
  257. const patch_name = try fmt.allocPrint(allocator, "{s}.patch", .{name});
  258. break :b try join(allocator, &.{ patches_path, patch_name });
  259. };
  260. const output = try join(allocator, &.{ outdir, ex.main_file });
  261. const argv = &.{ "patch", "-i", patch, "-o", output, file };
  262. var child = std.process.Child.init(argv, allocator);
  263. child.stdout_behavior = .Ignore; // the POSIX standard says that stdout is not used
  264. _ = try child.spawnAndWait();
  265. }
  266. }
  267. //
  268. // Missing functions from std.Build.RunStep
  269. //
  270. /// Adds a check for stderr match. Does not add any other checks.
  271. pub fn expectStdErrMatch(self: *RunStep, bytes: []const u8) void {
  272. const new_check: RunStep.StdIo.Check = .{
  273. .expect_stderr_match = self.step.owner.dupe(bytes),
  274. };
  275. self.addCheck(new_check);
  276. }
  277. /// Adds a check for stdout match as well as a check for exit code 0, if
  278. /// there is not already an expected termination check.
  279. pub fn expectStdOutMatch(self: *RunStep, bytes: []const u8) void {
  280. const new_check: RunStep.StdIo.Check = .{
  281. .expect_stdout_match = self.step.owner.dupe(bytes),
  282. };
  283. self.addCheck(new_check);
  284. if (!self.hasTermCheck()) {
  285. self.expectExitCode(0);
  286. }
  287. }