1#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct RatchetVerdict {
10 pub ok: bool,
11 pub reason: String,
12}
13
14impl RatchetVerdict {
15 pub fn pass() -> Self {
16 Self {
17 ok: true,
18 reason: String::new(),
19 }
20 }
21}
22
23pub fn check_diff(diff: &str) -> RatchetVerdict {
30 let mut removed = 0i32;
31 let mut added = 0i32;
32 let mut removed_test_file = false;
33
34 for line in diff.lines() {
35 if line.starts_with("+++ ") && line.contains("/dev/null") {
37 }
40 if let Some(rest) = line.strip_prefix('-') {
41 if rest.starts_with("--") {
42 if is_test_path(rest) {
44 removed_test_file = true;
45 }
46 continue;
47 }
48 if looks_like_test(rest) {
49 removed += 1;
50 }
51 } else if let Some(rest) = line.strip_prefix('+') {
52 if rest.starts_with("++") {
53 continue;
54 }
55 if looks_like_test(rest) {
56 added += 1;
57 }
58 }
59 }
60
61 if removed_test_file {
62 return RatchetVerdict {
63 ok: false,
64 reason: "diff deletes a test file".into(),
65 };
66 }
67 if removed > added {
68 return RatchetVerdict {
69 ok: false,
70 reason: format!(
71 "diff removes {removed} test declaration(s) but adds {added} — tests weakened"
72 ),
73 };
74 }
75 RatchetVerdict::pass()
76}
77
78fn looks_like_test(line: &str) -> bool {
80 let t = line.trim();
81 t.contains("#[test]")
82 || t.contains("#[tokio::test]")
83 || t.starts_with("def test_")
84 || t.starts_with("func Test")
85 || t.starts_with("it(")
86 || t.starts_with("it.")
87 || t.starts_with("test(")
88 || t.starts_with("describe(")
89 || t.contains("@Test")
90}
91
92fn is_test_path(header: &str) -> bool {
94 let p = header.trim_start_matches('-').trim();
95 p.contains("test") || p.contains("spec") || p.contains("__tests__")
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101
102 #[test]
103 fn passes_a_normal_diff() {
104 let diff = "--- a/src/lib.rs\n+++ b/src/lib.rs\n@@\n-let x = 1;\n+let x = 2;\n";
105 assert!(check_diff(diff).ok);
106 }
107
108 #[test]
109 fn blocks_removing_a_test() {
110 let diff = "--- a/src/lib.rs\n+++ b/src/lib.rs\n@@\n- #[test]\n- fn it_works() { assert!(true); }\n";
111 let v = check_diff(diff);
112 assert!(!v.ok, "should block test deletion: {}", v.reason);
113 }
114
115 #[test]
116 fn allows_replacing_a_test() {
117 let diff = "@@\n- #[test]\n- fn old() {}\n+ #[test]\n+ fn renamed() {}\n";
118 assert!(check_diff(diff).ok);
119 }
120
121 #[test]
122 fn blocks_deleting_a_test_file() {
123 let diff = "--- a/src/foo_test.go\n+++ /dev/null\n@@\n-func TestFoo(t *testing.T) {}\n";
124 assert!(!check_diff(diff).ok);
125 }
126}