Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 33.6 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid verify` end to end, on small repositories whose test is a script
5//! of their own, `check.sh`, which fails while a file named `broken` is
6//! there: the green ref, bisecting to the changeset that broke the tests,
7//! reverting it, and the limits on reverting.
8
9use std::path::{Path, PathBuf};
10use std::process::{Command, Output};
11
12use serde_json::Value;
13
14/// The project's test, committed in every repository here.
15const CHECK: &str = "test ! -f broken\n";
16
17fn braid_with(dir: &Path, args: &[&str], envs: &[(&str, &str)]) -> Output {
18 Command::new(env!("CARGO_BIN_EXE_braid"))
19 .current_dir(dir)
20 .args(args)
21 .env("BRAID_AGENT", "tester")
22 .env("BRAID_AUTHOR", "Ada <ada@example.org>")
23 .env("BRAID_HUB", "off")
24 .envs(envs.iter().copied())
25 .output()
26 .unwrap()
27}
28
29/// Runs braid with `--json`, expecting exit status `code`.
30fn run(dir: &Path, args: &[&str], code: i32) -> Value {
31 let mut all = vec!["--json"];
32 all.extend_from_slice(args);
33 let out = braid_with(dir, &all, &[]);
34 assert_eq!(
35 out.status.code(),
36 Some(code),
37 "braid {args:?}: {}{}",
38 String::from_utf8_lossy(&out.stdout),
39 String::from_utf8_lossy(&out.stderr)
40 );
41 serde_json::from_slice(&out.stdout).unwrap_or(Value::Null)
42}
43
44fn id(value: &Value) -> String {
45 value.as_str().unwrap().to_owned()
46}
47
48struct Repo {
49 _temp: tempfile::TempDir,
50 /// A directory outside the repository, for the tests' own files.
51 outside: PathBuf,
52 dir: PathBuf,
53}
54
55impl Repo {
56 /// A repository whose `main` holds `check.sh` and a notes file.
57 fn new() -> Repo {
58 let temp = tempfile::tempdir().unwrap();
59 let base = std::fs::canonicalize(temp.path()).unwrap();
60 let dir = base.join("repo");
61 let outside = base.join("outside");
62 std::fs::create_dir(&outside).unwrap();
63 run(&base, &["init", dir.to_str().unwrap()], 0);
64 let repo = Repo {
65 _temp: temp,
66 outside,
67 dir,
68 };
69 repo.land(&[("check.sh", CHECK), ("notes", "1\n2\n3\n")], &[], "Seed");
70 repo
71 }
72
73 /// Lands a change on `main` that sets and deletes paths, and returns
74 /// the changeset that holds it on `main`.
75 fn land(&self, sets: &[(&str, &str)], deletes: &[&str], message: &str) -> String {
76 let base = self.head().unwrap_or_else(|| "none".to_owned());
77 let mut args = vec!["change", "create", "--base", &base, "-m", message];
78 let mut owned = Vec::new();
79 for (n, (path, text)) in sets.iter().enumerate() {
80 let file = self.outside.join(format!("{message}-{n}"));
81 std::fs::write(&file, text).unwrap();
82 owned.push(format!("{path}=@{}", file.display()));
83 }
84 for set in &owned {
85 args.extend(["--set", set]);
86 }
87 for path in deletes {
88 args.extend(["--delete", path]);
89 }
90 args.extend(["--land", "main"]);
91 let out = run(&self.dir, &args, 0);
92 id(&out["land"]["head"])
93 }
94
95 fn head(&self) -> Option<String> {
96 self.reference("main")
97 }
98
99 fn green(&self) -> Option<String> {
100 self.reference("braid/green/main")
101 }
102
103 fn reference(&self, name: &str) -> Option<String> {
104 let refs = run(&self.dir, &["refs"], 0);
105 refs["refs"][name].as_str().map(str::to_owned)
106 }
107
108 /// Runs `braid verify` with `flags`, then `--` and `command`, expecting
109 /// exit status `code`.
110 fn verify_env(
111 &self,
112 flags: &[&str],
113 command: &[&str],
114 envs: &[(&str, &str)],
115 code: i32,
116 ) -> Value {
117 let mut args = vec!["--json", "verify"];
118 args.extend_from_slice(flags);
119 args.push("--");
120 args.extend_from_slice(command);
121 let out = braid_with(&self.dir, &args, envs);
122 assert_eq!(
123 out.status.code(),
124 Some(code),
125 "braid {args:?}: {}{}",
126 String::from_utf8_lossy(&out.stdout),
127 String::from_utf8_lossy(&out.stderr)
128 );
129 serde_json::from_slice(&out.stdout).unwrap()
130 }
131
132 fn verify(&self, flags: &[&str], code: i32) -> Value {
133 self.verify_env(flags, &["sh", "check.sh"], &[], code)
134 }
135
136 /// The test command of a repository whose failing changesets are listed
137 /// in a file outside it: a changeset fails when its id is in the list.
138 fn listed(&self) -> (PathBuf, Vec<String>) {
139 let list = self.outside.join("failing");
140 std::fs::write(&list, "").unwrap();
141 let script = self.outside.join("listed.sh");
142 std::fs::write(
143 &script,
144 "if grep -qx \"$BRAID_VERIFY_CHANGESET\" \"$1\"; then exit 1; fi\n",
145 )
146 .unwrap();
147 let command = vec![
148 "sh".to_owned(),
149 script.display().to_string(),
150 list.display().to_string(),
151 ];
152 (list, command)
153 }
154
155 fn has_record(&self) -> bool {
156 // The branch's name in hex.
157 self.dir.join(".braid/verify/6d61696e.json").is_file()
158 }
159
160 /// Forgets the local record of verify's reverts, as a fresh clone
161 /// never had it.
162 fn forget_record(&self) {
163 std::fs::remove_dir_all(self.dir.join(".braid/verify")).unwrap();
164 }
165}
166
167/// A repository where `main` was verified green at the seed, then had four
168/// changesets landed, the second of which broke the tests. Returns the
169/// seed and the four.
170fn broken_after_green() -> (Repo, String, Vec<String>) {
171 let r = Repo::new();
172 let seed = r.head().unwrap();
173 let out = r.verify(&[], 0);
174 assert_eq!(out["outcome"], "pass");
175 let ids = vec![
176 r.land(&[("a", "a\n")], &[], "Add a"),
177 r.land(&[("broken", "x\n")], &[], "Break the tests"),
178 r.land(&[("b", "b\n")], &[], "Add b"),
179 r.land(&[("c", "c\n")], &[], "Add c"),
180 ];
181 (r, seed, ids)
182}
183
184#[test]
185fn a_pass_moves_the_green_ref_and_status_shows_it() {
186 let r = Repo::new();
187 let tip = r.head().unwrap();
188 let out = r.verify(&[], 0);
189 assert_eq!(out["outcome"], "pass");
190 assert_eq!(out["branch"], "main");
191 assert_eq!(out["tip"], tip.as_str());
192 assert_eq!(out["green_before"], Value::Null);
193 assert_eq!(out["green"], tip.as_str());
194 assert_eq!(out["tests_run"], 1);
195 assert_eq!(out["culprit"], Value::Null);
196 assert_eq!(out["revert"], Value::Null);
197 assert_eq!(r.green().as_deref(), Some(tip.as_str()));
198
199 // The move is an operation of its own, by braid-verify.
200 let log = run(&r.dir, &["op", "log", "-n", "1"], 0);
201 assert_eq!(log[0]["agent"], "braid-verify");
202 assert_eq!(log[0]["updates"][0]["name"], "braid/green/main");
203
204 // Nothing to run while the head is green.
205 let again = r.verify(&[], 0);
206 assert_eq!(again["outcome"], "pass");
207 assert_eq!(again["tests_run"], 0);
208
209 run(&r.dir, &["workspace", "add", "w"], 0);
210 let status = run(&r.dir, &["status", "--workspace", "w"], 0);
211 assert_eq!(status["green"], tip.as_str());
212
213 let text = braid_with(&r.dir, &["verify", "--", "sh", "check.sh"], &[]);
214 assert!(text.status.success());
215 let text = String::from_utf8(text.stdout).unwrap();
216 assert!(text.starts_with("main is green at"), "{text}");
217}
218
219#[test]
220fn a_dry_run_moves_no_green_ref() {
221 let r = Repo::new();
222 let out = r.verify(&["--dry-run"], 0);
223 assert_eq!(out["outcome"], "pass");
224 assert_eq!(out["dry_run"], true);
225 assert_eq!(out["green"], Value::Null);
226 assert!(id(&out["reason"]).contains("dry run"));
227 assert_eq!(r.green(), None);
228}
229
230#[test]
231fn red_on_the_head_bisects_to_the_changeset_that_broke_it() {
232 let (r, seed, ids) = broken_after_green();
233 let out = r.verify(&["--reruns", "0"], 4);
234 assert_eq!(out["outcome"], "red");
235 assert_eq!(out["tip"], ids[3].as_str());
236 assert_eq!(out["culprit"], ids[1].as_str());
237 assert_eq!(out["green_before"], seed.as_str());
238 assert_eq!(out["green"], seed.as_str());
239 assert_eq!(out["revert"], Value::Null);
240 // The head, then the second and the first changesets after green.
241 assert_eq!(out["tests_run"], 3);
242 assert!(id(&out["reason"]).contains("--revert"));
243 assert_eq!(r.green(), Some(seed));
244 assert_eq!(r.head().as_deref(), Some(ids[3].as_str()));
245}
246
247#[test]
248fn without_a_green_ref_only_the_head_is_tested_unless_from_says() {
249 let r = Repo::new();
250 let seed = r.head().unwrap();
251 let culprit = r.land(&[("broken", "x\n")], &[], "Break");
252 r.land(&[("a", "a\n")], &[], "Add a");
253 let out = r.verify(&[], 4);
254 assert_eq!(out["outcome"], "red");
255 assert_eq!(out["culprit"], Value::Null);
256 // The head, and the rerun.
257 assert_eq!(out["tests_run"], 2);
258 assert!(id(&out["reason"]).contains("--from"));
259
260 let out = r.verify(&["--from", &seed, "--reruns", "0"], 4);
261 assert_eq!(out["culprit"], culprit.as_str());
262 assert_eq!(r.green(), None);
263}
264
265#[test]
266fn a_revert_lands_and_the_green_ref_stays_until_the_next_pass() {
267 let (r, seed, ids) = broken_after_green();
268 let out = r.verify(&["--revert", "--reruns", "0"], 4);
269 assert_eq!(out["outcome"], "reverted");
270 assert_eq!(out["culprit"], ids[1].as_str());
271 let revert = id(&out["revert"]);
272 assert_eq!(out["land"]["outcome"], "rebased");
273 assert_eq!(out["green"], seed.as_str());
274 assert_eq!(r.green().as_deref(), Some(seed.as_str()));
275 let head = r.head().unwrap();
276 assert_eq!(out["land"]["head"], head.as_str());
277 assert!(r.has_record());
278
279 // The revert names its culprit, and braid-verify made it.
280 let shown = run(&r.dir, &["show", "main"], 0);
281 assert_eq!(shown["agent"], "braid-verify");
282 assert!(
283 shown["extras"]
284 .as_array()
285 .unwrap()
286 .contains(&serde_json::json!(["rebased-from", revert]))
287 );
288 assert!(
289 shown["changes"]
290 .as_array()
291 .unwrap()
292 .iter()
293 .any(|c| c["path"] == "broken" && c["op"] == "delete")
294 );
295
296 // The next pass tests the new head, which passes.
297 let next = r.verify(&["--revert"], 0);
298 assert_eq!(next["outcome"], "pass");
299 assert_eq!(next["green"], head.as_str());
300}
301
302#[test]
303fn a_dry_run_finds_the_culprit_and_reverts_nothing() {
304 let (r, seed, ids) = broken_after_green();
305 let out = r.verify(&["--revert", "--dry-run", "--reruns", "0"], 4);
306 assert_eq!(out["outcome"], "red");
307 assert_eq!(out["culprit"], ids[1].as_str());
308 assert_eq!(out["revert"], Value::Null);
309 assert!(id(&out["reason"]).contains("dry run"));
310 assert_eq!(r.head().as_deref(), Some(ids[3].as_str()));
311 assert_eq!(r.green(), Some(seed));
312 assert!(!r.has_record());
313}
314
315#[test]
316fn reverts_stop_at_the_hourly_cap() {
317 let (r, _, ids) = broken_after_green();
318 let none = r.verify(
319 &["--revert", "--reruns", "0", "--max-reverts-per-hour", "0"],
320 4,
321 );
322 assert_eq!(none["outcome"], "refused");
323 assert!(id(&none["reason"]).contains("--max-reverts-per-hour"));
324 assert_eq!(r.head().as_deref(), Some(ids[3].as_str()));
325
326 let first = r.verify(
327 &["--revert", "--reruns", "0", "--max-reverts-per-hour", "1"],
328 4,
329 );
330 assert_eq!(first["outcome"], "reverted");
331 // Green again, then broken again: the cap of one an hour is spent. It
332 // is counted on the branch, so a clone without verify's record, as CI
333 // has, counts it too.
334 assert_eq!(r.verify(&[], 0)["outcome"], "pass");
335 let again = r.land(&[("broken", "again\n")], &[], "Break again");
336 r.forget_record();
337 let second = r.verify(
338 &["--revert", "--reruns", "0", "--max-reverts-per-hour", "1"],
339 4,
340 );
341 assert_eq!(second["outcome"], "refused");
342 assert!(id(&second["reason"]).contains("1 revert on main in the last hour"));
343 assert_eq!(r.head(), Some(again));
344 assert_eq!(second["revert"], Value::Null);
345}
346
347#[test]
348fn verify_does_not_revert_its_own_revert() {
349 let r = Repo::new();
350 let (list, command) = r.listed();
351 let command: Vec<&str> = command.iter().map(String::as_str).collect();
352 let seed = r.head().unwrap();
353 let green = r.verify_env(&[], &command, &[], 0);
354 assert_eq!(green["green"], seed.as_str());
355
356 let culprit = r.land(&[("a", "a\n")], &[], "Change a");
357 std::fs::write(&list, format!("{culprit}\n")).unwrap();
358 let out = r.verify_env(&["--revert", "--reruns", "0"], &command, &[], 4);
359 assert_eq!(out["outcome"], "reverted");
360 let revert = r.head().unwrap();
361
362 // Now the revert fails and the change it undid passes: the culprit is
363 // the revert, which verify leaves alone, by what the revert says of
364 // itself, without its record.
365 std::fs::write(&list, format!("{revert}\n")).unwrap();
366 r.forget_record();
367 let out = r.verify_env(&["--revert", "--reruns", "0"], &command, &[], 4);
368 assert_eq!(out["outcome"], "refused");
369 assert_eq!(out["culprit"], revert.as_str());
370 assert!(id(&out["reason"]).contains("its own reverts"));
371 assert_eq!(r.head(), Some(revert));
372}
373
374#[test]
375fn a_failure_before_every_changeset_in_range_has_no_culprit() {
376 let r = Repo::new();
377 let (list, command) = r.listed();
378 let command: Vec<&str> = command.iter().map(String::as_str).collect();
379 let seed = r.head().unwrap();
380 r.verify_env(&[], &command, &[], 0);
381 let change = r.land(&[("a", "a\n")], &[], "Change a");
382 // Something outside the repository broke: the green changeset fails too.
383 std::fs::write(&list, format!("{seed}\n{change}\n")).unwrap();
384 let out = r.verify_env(&["--revert", "--reruns", "0"], &command, &[], 4);
385 assert_eq!(out["outcome"], "no_culprit");
386 assert_eq!(out["culprit"], Value::Null);
387 assert_eq!(out["tests_run"], 2);
388 assert_eq!(r.head(), Some(change));
389}
390
391#[test]
392fn a_revert_that_conflicts_exits_with_2_and_moves_nothing() {
393 let r = Repo::new();
394 r.verify(&[], 0);
395 r.land(&[("notes", "1\nbad\n3\n"), ("broken", "x\n")], &[], "Break");
396 let later = r.land(&[("notes", "1\nworse\n3\n")], &[], "Edit the same line");
397 let out = r.verify(&["--revert", "--reruns", "0"], 2);
398 assert_eq!(out["outcome"], "revert_conflicts");
399 assert_eq!(out["land"]["outcome"], "conflicts");
400 assert_eq!(out["land"]["conflicts"][0]["path"], "notes");
401 assert_eq!(r.head(), Some(later));
402}
403
404#[test]
405fn a_run_that_fails_then_passes_is_flaky() {
406 let r = Repo::new();
407 let marker = r.outside.join("ran-once");
408 let script = format!(
409 "if [ -f '{0}' ]; then exit 0; fi; touch '{0}'; exit 1",
410 marker.display()
411 );
412 let out = r.verify_env(&[], &["sh", "-c", &script], &[], 0);
413 assert_eq!(out["outcome"], "flaky");
414 assert_eq!(out["tests_run"], 2);
415 // A flaky pass leaves the green ref where it was, unless asked.
416 assert_eq!(out["green"], Value::Null);
417 assert!(id(&out["reason"]).contains("--flaky-moves-green"));
418 assert_eq!(r.green(), None);
419 std::fs::remove_file(&marker).unwrap();
420 let out = r.verify_env(&["--flaky-moves-green"], &["sh", "-c", &script], &[], 0);
421 assert_eq!(out["outcome"], "flaky");
422 assert_eq!(out["green"], r.head().unwrap().as_str());
423}
424
425#[test]
426fn the_tests_get_a_clean_copy_and_no_credentials() {
427 let r = Repo::new();
428 let tip = r.head().unwrap();
429 let script = format!(
430 "test -z \"$BRAID_TOKEN\" && test -z \"$BRAID_HUB_URL\" && test -z \"$BRAID_HUB\" \
431 && test \"$BRAID_VERIFY_CHANGESET\" = {tip} && test \"$BRAID_VERIFY_BRANCH\" = main \
432 && test -f check.sh && test -f notes && test ! -e .braid && test ! -e .git"
433 );
434 let envs = [
435 ("BRAID_TOKEN", "brd_secret"),
436 ("BRAID_HUB_URL", "https://hub.example.org"),
437 ];
438 let out = r.verify_env(&["--dry-run"], &["sh", "-c", &script], &envs, 0);
439 assert_eq!(out["outcome"], "pass");
440 // Braid's other variables reach the tests.
441 let leak = "test -n \"$BRAID_AGENT\"";
442 let out = r.verify_env(&["--dry-run"], &["sh", "-c", leak], &envs, 0);
443 assert_eq!(out["outcome"], "pass");
444 // The environment as `env` prints it, with no shell to change it: PWD
445 // names the copy, and OLDPWD, which named the repository, is gone.
446 let envs = [
447 ("BRAID_TOKEN", "brd_secret"),
448 ("BRAID_HUB_URL", "https://hub.example.org"),
449 ("OLDPWD", r.dir.to_str().unwrap()),
450 ("PWD", r.dir.to_str().unwrap()),
451 ];
452 let out = braid_with(&r.dir, &["verify", "--dry-run", "--", "env"], &envs);
453 assert!(out.status.success());
454 let printed = String::from_utf8_lossy(&out.stderr);
455 let var = |name: &str| {
456 printed
457 .lines()
458 .find_map(|line| line.strip_prefix(&format!("{name}=")))
459 .map(str::to_owned)
460 };
461 assert_eq!(var("BRAID_TOKEN"), None);
462 assert_eq!(var("BRAID_HUB_URL"), None);
463 assert_eq!(var("OLDPWD"), None);
464 let pwd = var("PWD").unwrap();
465 assert!(pwd.contains("braid-verify-"), "{pwd}");
466 assert_eq!(var("BRAID_VERIFY_BRANCH").as_deref(), Some("main"));
467 // A command that cannot run is an error, not a red branch.
468 let out = braid_with(&r.dir, &["verify", "--", "no-such-command-for-braid"], &[]);
469 assert_eq!(out.status.code(), Some(1));
470 assert!(out.stdout.is_empty());
471}
472
473#[cfg(unix)]
474#[test]
475fn a_timeout_kills_the_command_and_what_it_started() {
476 let r = Repo::new();
477 let pid_file = r.outside.join("pid");
478 let script = format!(
479 "sleep 120 > /dev/null 2>&1 & echo $! > '{}'; wait",
480 pid_file.display()
481 );
482 let out = r.verify_env(
483 &["--timeout", "1s", "--reruns", "0"],
484 &["sh", "-c", &script],
485 &[],
486 4,
487 );
488 assert_eq!(out["outcome"], "red");
489 assert_eq!(out["tests_run"], 1);
490 let pid = std::fs::read_to_string(&pid_file).unwrap();
491 let pid = pid.trim();
492 // The background sleep went with its group: gone, or a zombie waiting
493 // to be reaped.
494 let mut alive = true;
495 for _ in 0..100 {
496 let ps = Command::new("ps")
497 .args(["-o", "stat=", "-p", pid])
498 .output()
499 .unwrap();
500 let state = String::from_utf8_lossy(&ps.stdout).trim().to_owned();
501 if state.is_empty() || state.starts_with('Z') {
502 alive = false;
503 break;
504 }
505 std::thread::sleep(std::time::Duration::from_millis(50));
506 }
507 assert!(!alive, "the background process {pid} outlived the timeout");
508}
509
510/// Whether the process `pid` is gone, or a zombie waiting to be reaped,
511/// within a few seconds.
512#[cfg(unix)]
513fn gone(pid: &str) -> bool {
514 for _ in 0..100 {
515 let ps = Command::new("ps")
516 .args(["-o", "stat=", "-p", pid])
517 .output()
518 .unwrap();
519 let state = String::from_utf8_lossy(&ps.stdout).trim().to_owned();
520 if state.is_empty() || state.starts_with('Z') {
521 return true;
522 }
523 std::thread::sleep(std::time::Duration::from_millis(50));
524 }
525 false
526}
527
528/// The contents of `path` once a command wrote them, within a few seconds.
529#[cfg(unix)]
530fn written(path: &Path) -> String {
531 for _ in 0..200 {
532 if let Ok(text) = std::fs::read_to_string(path)
533 && text.ends_with('\n')
534 {
535 return text.trim().to_owned();
536 }
537 std::thread::sleep(std::time::Duration::from_millis(50));
538 }
539 panic!("{} was never written", path.display());
540}
541
542#[cfg(unix)]
543#[test]
544fn what_a_passing_command_leaves_running_is_killed() {
545 let r = Repo::new();
546 let pid_file = r.outside.join("pid");
547 let script = format!(
548 "sleep 120 > /dev/null 2>&1 & echo $! > '{}'",
549 pid_file.display()
550 );
551 let out = r.verify_env(&["--dry-run"], &["sh", "-c", &script], &[], 0);
552 assert_eq!(out["outcome"], "pass");
553 let pid = written(&pid_file);
554 assert!(gone(&pid), "the background process {pid} outlived its test");
555}
556
557#[cfg(unix)]
558#[test]
559fn stopping_braid_stops_the_tests_and_removes_their_copy() {
560 let r = Repo::new();
561 let shell_file = r.outside.join("shell");
562 let sleep_file = r.outside.join("sleep");
563 let dir_file = r.outside.join("dir");
564 let script = format!(
565 "pwd > '{dir}'; echo $$ > '{shell}'; sleep 120 > /dev/null 2>&1 & echo $! > '{sleep}'; wait",
566 dir = dir_file.display(),
567 shell = shell_file.display(),
568 sleep = sleep_file.display(),
569 );
570 let mut braid = Command::new(env!("CARGO_BIN_EXE_braid"))
571 .current_dir(&r.dir)
572 .args(["verify", "--", "sh", "-c", &script])
573 .env("BRAID_HUB", "off")
574 .stdout(std::process::Stdio::null())
575 .stderr(std::process::Stdio::null())
576 .spawn()
577 .unwrap();
578 let sleep = written(&sleep_file);
579 let shell = written(&shell_file);
580 let dir = PathBuf::from(written(&dir_file));
581 assert!(dir.is_dir());
582 // Only the braid this test started.
583 let term = Command::new("kill")
584 .args(["-TERM", &braid.id().to_string()])
585 .status()
586 .unwrap();
587 assert!(term.success());
588 braid.wait().unwrap();
589 assert!(gone(&shell), "the test's shell {shell} outlived braid");
590 assert!(gone(&sleep), "the test's sleep {sleep} outlived braid");
591 let mut removed = false;
592 for _ in 0..100 {
593 if !dir.exists() {
594 removed = true;
595 break;
596 }
597 std::thread::sleep(std::time::Duration::from_millis(50));
598 }
599 assert!(removed, "{} is still there", dir.display());
600}
601
602#[test]
603fn a_revert_verify_made_earlier_does_not_stall_the_bisect() {
604 // Green at the seed; C broke the tests and verify reverted it; then D
605 // broke them again. Bisecting from the seed meets C first: verify sees
606 // its revert, tests it, and goes on after it to find D.
607 let r = Repo::new();
608 assert_eq!(r.verify(&[], 0)["outcome"], "pass");
609 let c = r.land(&[("broken", "c\n")], &[], "C breaks the tests");
610 let first = r.verify(&["--revert", "--reruns", "0"], 4);
611 assert_eq!(first["outcome"], "reverted");
612 assert_eq!(first["culprit"], c.as_str());
613 let d = r.land(
614 &[("broken", "d\n"), ("d", "d\n")],
615 &[],
616 "D breaks them again",
617 );
618 let second = r.verify(&["--revert", "--reruns", "0"], 4);
619 assert_eq!(second["outcome"], "reverted", "{second}");
620 assert_eq!(second["culprit"], d.as_str());
621 // The head, C, C's revert, then the green one is not needed.
622 assert_eq!(second["tests_run"], 3);
623 assert_eq!(r.verify(&[], 0)["outcome"], "pass");
624}
625
626#[test]
627fn a_changeset_that_cannot_be_written_here_is_skipped() {
628 // Two names that differ only in case are one file where the file
629 // system ignores case: such a changeset cannot be tested there.
630 let probe = tempfile::tempdir().unwrap();
631 std::fs::write(probe.path().join("Aa"), "").unwrap();
632 if !probe.path().join("aA").exists() {
633 return;
634 }
635 let r = Repo::new();
636 assert_eq!(r.verify(&[], 0)["outcome"], "pass");
637 r.land(&[("a", "a\n")], &[], "Add a");
638 let twins = r.land(&[("Case", "1\n"), ("case", "2\n")], &[], "Add twins");
639 r.land(&[], &["case"], "Remove a twin");
640 let culprit = r.land(&[("broken", "x\n")], &[], "Break");
641 r.land(&[("z", "z\n")], &[], "Add z");
642 let out = r.verify(&["--reruns", "0"], 4);
643 assert_eq!(out["outcome"], "red");
644 assert_eq!(out["culprit"], culprit.as_str());
645 assert_eq!(out["skipped"], serde_json::json!([twins]));
646}
647
648#[cfg(unix)]
649#[test]
650fn an_error_after_the_revert_landed_keeps_it_in_the_report() {
651 use std::os::unix::fs::PermissionsExt;
652 let (r, _, ids) = broken_after_green();
653 // Verify's record cannot be written.
654 let record = r.dir.join(".braid/verify");
655 std::fs::create_dir(&record).unwrap();
656 std::fs::set_permissions(&record, std::fs::Permissions::from_mode(0o555)).unwrap();
657 if std::fs::write(record.join("probe"), "").is_ok() {
658 // Modes do not hold here, as for root in a container: nothing to
659 // test.
660 return;
661 }
662 let out = r.verify(&["--revert", "--reruns", "0"], 1);
663 std::fs::set_permissions(&record, std::fs::Permissions::from_mode(0o755)).unwrap();
664 assert_eq!(out["outcome"], "error");
665 assert_eq!(out["culprit"], ids[1].as_str());
666 let revert = id(&out["revert"]);
667 assert_eq!(out["land"]["outcome"], "rebased");
668 let head = r.head().unwrap();
669 assert_eq!(out["land"]["head"], head.as_str());
670 assert_ne!(head, ids[3]);
671 assert!(!revert.is_empty());
672 // The branch says verify made it, so the next pass will not undo it.
673 let shown = run(&r.dir, &["show", "main"], 0);
674 assert_eq!(shown["agent"], "braid-verify");
675}
676
677/// Starts braid's own watchdog for `dir`, as verify does, and reads its
678/// handshake.
679#[cfg(unix)]
680fn start_watchdog(dir: &Path) -> std::process::Child {
681 use std::io::{BufRead, BufReader};
682 let mut watchdog = Command::new(env!("CARGO_BIN_EXE_braid"))
683 .arg("__verify-watchdog")
684 .arg(dir)
685 .stdin(std::process::Stdio::piped())
686 .stdout(std::process::Stdio::piped())
687 .stderr(std::process::Stdio::null())
688 .spawn()
689 .unwrap();
690 let mut line = String::new();
691 BufReader::new(watchdog.stdout.take().unwrap())
692 .read_line(&mut line)
693 .unwrap();
694 assert_eq!(line, "braid verify watchdog 2 ready\n");
695 watchdog
696}
697
698#[cfg(unix)]
699#[test]
700fn the_watchdog_stops_the_group_and_removes_the_copy_unless_told_done() {
701 use std::io::Write;
702 use std::os::unix::process::{CommandExt, ExitStatusExt};
703 // Directories named as verify names its copies, where the watchdog
704 // looks for them.
705 let base = std::env::temp_dir();
706 let dir = |n: u32| {
707 let dir = base.join(format!("braid-verify-test-{}-{n}", std::process::id()));
708 std::fs::create_dir(&dir).unwrap();
709 std::fs::write(dir.join("file"), "x").unwrap();
710 dir
711 };
712 // A process of this test's own, in a group of its own, as a test run is.
713 let sleeper = || {
714 Command::new("sleep")
715 .arg("60")
716 .process_group(0)
717 .spawn()
718 .unwrap()
719 };
720
721 // Braid goes away: its end of the watchdog's input closes.
722 let gone = dir(1);
723 let mut test = sleeper();
724 let mut watchdog = start_watchdog(&gone);
725 let mut input = watchdog.stdin.take().unwrap();
726 writeln!(input, "group {}", test.id()).unwrap();
727 drop(input);
728 watchdog.wait().unwrap();
729 assert_eq!(test.wait().unwrap().signal(), Some(9));
730 assert!(!gone.exists());
731
732 // The run ended and braid said so: nothing is touched.
733 let kept = dir(2);
734 let mut test = sleeper();
735 let mut watchdog = start_watchdog(&kept);
736 let mut input = watchdog.stdin.take().unwrap();
737 writeln!(input, "group {}\ndone", test.id()).unwrap();
738 drop(input);
739 watchdog.wait().unwrap();
740 assert!(test.try_wait().unwrap().is_none());
741 assert!(kept.join("file").is_file());
742 // This test's own process, by its id.
743 test.kill().unwrap();
744 test.wait().unwrap();
745 std::fs::remove_dir_all(&kept).unwrap();
746}
747
748#[test]
749fn acting_as_braid_verify_is_warned_about() {
750 let r = Repo::new();
751 let warned = |args: &[&str], envs: &[(&str, &str)]| {
752 let out = braid_with(&r.dir, args, envs);
753 assert!(out.status.success(), "{args:?}");
754 String::from_utf8_lossy(&out.stderr).contains("warning: the agent braid-verify")
755 };
756 assert!(warned(&["--agent", "braid-verify", "refs"], &[]));
757 assert!(warned(&["refs"], &[("BRAID_AGENT", "braid-verify")]));
758 assert!(!warned(&["refs"], &[]));
759}
760
761/// Git without the user's or the system's configuration.
762const GIT_ENV: [(&str, &str); 6] = [
763 ("GIT_CONFIG_GLOBAL", "/dev/null"),
764 ("GIT_CONFIG_NOSYSTEM", "1"),
765 ("GIT_AUTHOR_NAME", "Ada Lovelace"),
766 ("GIT_AUTHOR_EMAIL", "ada@example.org"),
767 ("GIT_COMMITTER_NAME", "Ada Lovelace"),
768 ("GIT_COMMITTER_EMAIL", "ada@example.org"),
769];
770
771fn git(dir: &Path, args: &[&str], envs: &[(&str, &str)]) {
772 let out = Command::new("git")
773 .current_dir(dir)
774 .args(args)
775 .envs(GIT_ENV)
776 .envs(envs.iter().copied())
777 .output()
778 .expect("git must be installed to run this test");
779 assert!(
780 out.status.success(),
781 "git {args:?}: {}",
782 String::from_utf8_lossy(&out.stderr)
783 );
784}
785
786#[test]
787fn an_old_date_between_reverts_does_not_reset_the_hourly_cap() {
788 let (r, _, _) = broken_after_green();
789 let first = r.verify(
790 &["--revert", "--reruns", "0", "--max-reverts-per-hour", "1"],
791 4,
792 );
793 assert_eq!(first["outcome"], "reverted");
794
795 // On top of the revert, by a fast-forward, a git commit made two days
796 // ago.
797 let mirror = r.outside.join("mirror.git");
798 let clone = r.outside.join("clone");
799 git(
800 &r.outside,
801 &["init", "-q", "--bare", mirror.to_str().unwrap()],
802 &[],
803 );
804 run(
805 &r.dir,
806 &["git", "export", mirror.to_str().unwrap(), "--ref", "main"],
807 0,
808 );
809 git(
810 &r.outside,
811 &[
812 "clone",
813 "-q",
814 "-b",
815 "main",
816 mirror.to_str().unwrap(),
817 clone.to_str().unwrap(),
818 ],
819 &[],
820 );
821 std::fs::write(clone.join("old"), "old\n").unwrap();
822 git(&clone, &["add", "old"], &[]);
823 let now = std::time::SystemTime::now()
824 .duration_since(std::time::UNIX_EPOCH)
825 .unwrap()
826 .as_secs();
827 let two_days_ago = format!("{} +0000", now - 2 * 86_400);
828 git(
829 &clone,
830 &["commit", "-q", "-m", "Made two days ago"],
831 &[
832 ("GIT_AUTHOR_DATE", &two_days_ago),
833 ("GIT_COMMITTER_DATE", &two_days_ago),
834 ],
835 );
836 run(&r.dir, &["git", "import", clone.to_str().unwrap()], 0);
837 let shown = run(&r.dir, &["show", "main"], 0);
838 assert_eq!(shown["message"], "Made two days ago\n");
839 assert!(shown["committer"]["seconds"].as_u64().unwrap() <= now - 2 * 86_400);
840
841 // Green again, then broken again: the revert below the old date still
842 // counts, also without verify's own record.
843 assert_eq!(r.verify(&[], 0)["outcome"], "pass");
844 let again = r.land(&[("broken", "again\n")], &[], "Break again");
845 r.forget_record();
846 let second = r.verify(
847 &["--revert", "--reruns", "0", "--max-reverts-per-hour", "1"],
848 4,
849 );
850 assert_eq!(second["outcome"], "refused", "{second}");
851 assert!(id(&second["reason"]).contains("1 revert on main in the last hour"));
852 assert_eq!(r.head(), Some(again));
853}
854
855/// The processes whose parent is `parent`.
856#[cfg(unix)]
857fn children_of(parent: u32) -> Vec<String> {
858 let ps = Command::new("ps")
859 .args(["-A", "-o", "pid=,ppid="])
860 .output()
861 .unwrap();
862 String::from_utf8_lossy(&ps.stdout)
863 .lines()
864 .filter_map(|line| {
865 let mut fields = line.split_whitespace();
866 let pid = fields.next()?;
867 let ppid = fields.next()?;
868 (ppid == parent.to_string()).then(|| pid.to_owned())
869 })
870 .collect()
871}
872
873#[cfg(unix)]
874#[test]
875fn a_run_cut_short_counts_and_its_report_is_printed() {
876 let r = Repo::new();
877 let shell_file = r.outside.join("shell");
878 let script = format!("echo $$ > '{}'; sleep 60", shell_file.display());
879 let braid = Command::new(env!("CARGO_BIN_EXE_braid"))
880 .current_dir(&r.dir)
881 .args(["--json", "verify", "--", "sh", "-c", &script])
882 .env("BRAID_HUB", "off")
883 .stdout(std::process::Stdio::piped())
884 .stderr(std::process::Stdio::null())
885 .spawn()
886 .unwrap();
887 let shell = written(&shell_file);
888 // Braid's children are the test's shell and the watchdog: stop the
889 // watchdog, by its id, under the running test.
890 let watchdog: Vec<String> = children_of(braid.id())
891 .into_iter()
892 .filter(|pid| *pid != shell)
893 .collect();
894 assert_eq!(watchdog.len(), 1, "{watchdog:?}");
895 let stopped = Command::new("kill")
896 .args(["-KILL", &watchdog[0]])
897 .status()
898 .unwrap();
899 assert!(stopped.success());
900 let out = braid.wait_with_output().unwrap();
901 assert_eq!(out.status.code(), Some(1));
902 let report: Value = serde_json::from_slice(&out.stdout).unwrap();
903 assert_eq!(report["outcome"], "error");
904 assert_eq!(report["tests_run"], 1);
905 assert!(
906 id(&report["reason"]).contains("watchdog stopped"),
907 "{report}"
908 );
909 assert!(
910 gone(&shell),
911 "the test's shell {shell} outlived its watchdog"
912 );
913}
914
915#[cfg(unix)]
916#[test]
917fn the_watchdog_still_takes_the_arguments_braid_0_1_1_gives() {
918 use std::io::Write;
919 use std::os::unix::process::{CommandExt, ExitStatusExt};
920 // As braid 0.1.1 starts it: after the test, with the test's process
921 // group and then the directory, and told nothing but `done`.
922 let start = |test: &std::process::Child, dir: &Path| {
923 Command::new(env!("CARGO_BIN_EXE_braid"))
924 .arg("__verify-watchdog")
925 .arg(test.id().to_string())
926 .arg(dir)
927 .stdin(std::process::Stdio::piped())
928 .stdout(std::process::Stdio::null())
929 .stderr(std::process::Stdio::null())
930 .process_group(0)
931 .spawn()
932 .unwrap()
933 };
934 let sleeper = || {
935 Command::new("sleep")
936 .arg("60")
937 .process_group(0)
938 .spawn()
939 .unwrap()
940 };
941 let base = std::env::temp_dir();
942 let dir = |n: u32| {
943 let dir = base.join(format!("braid-verify-old-{}-{n}", std::process::id()));
944 std::fs::create_dir(&dir).unwrap();
945 dir
946 };
947
948 // That braid went away.
949 let gone = dir(1);
950 let mut test = sleeper();
951 let mut watchdog = start(&test, &gone);
952 drop(watchdog.stdin.take());
953 watchdog.wait().unwrap();
954 assert_eq!(test.wait().unwrap().signal(), Some(9));
955 assert!(!gone.exists());
956
957 // That braid finished its run.
958 let kept = dir(2);
959 let mut test = sleeper();
960 let mut watchdog = start(&test, &kept);
961 let mut input = watchdog.stdin.take().unwrap();
962 input.write_all(b"done\n").unwrap();
963 drop(input);
964 watchdog.wait().unwrap();
965 assert!(test.try_wait().unwrap().is_none());
966 assert!(kept.is_dir());
967 // This test's own process, by its id.
968 test.kill().unwrap();
969 test.wait().unwrap();
970 std::fs::remove_dir(&kept).unwrap();
971}