Skip to main content

vtcode_eval/
test_quality.rs

1//! Test-quality signal for agentic testing (Dan Luu `agentic-testing`).
2//!
3//! `pass@k` measures whether runs pass. This module measures whether the
4//! *tests themselves* are high-value: asymmetric/boundary coverage, structured
5//! property-based testing with shrinking, and avoidance of panic-only or
6//! identical-fixture traps.
7//!
8//! Heuristics are intentionally cheap string analyses over test sources so they
9//! can run in CI without executing mutations. They are a triage signal, not a
10//! proof of correctness.
11
12use serde::{Deserialize, Serialize};
13
14/// Aggregate facts about a test source file or inline test module.
15#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
16pub struct TestQualitySummary {
17    /// Number of test cases (`#[test]`-family attributes).
18    pub total_tests: u64,
19    /// Tests with no oracle (`assert*`, `prop_assert*`, `insta::*`).
20    pub panic_only_tests: u64,
21    /// Tests exercising asymmetric, boundary, order-swap, or reversal cases.
22    pub asymmetric_tests: u64,
23    /// Property tests using structured strategies (`prop_oneof`, `prop_compose`, `Just`, `strategy`).
24    pub structured_pbt_tests: u64,
25}
26
27impl TestQualitySummary {
28    /// Fraction of tests with no value oracle. Lower is better.
29    pub fn panic_only_ratio(&self) -> f64 {
30        if self.total_tests == 0 {
31            return 0.0;
32        }
33        self.panic_only_tests as f64 / self.total_tests as f64
34    }
35
36    /// Fraction of tests covering asymmetric/boundary behavior. Higher is better.
37    pub fn asymmetric_coverage(&self) -> f64 {
38        if self.total_tests == 0 {
39            return 0.0;
40        }
41        self.asymmetric_tests as f64 / self.total_tests as f64
42    }
43
44    /// Fraction of tests using structured PBT. Higher is better.
45    pub fn structured_pbt_ratio(&self) -> f64 {
46        if self.total_tests == 0 {
47            return 0.0;
48        }
49        self.structured_pbt_tests as f64 / self.total_tests as f64
50    }
51
52    /// Luu-inspired bar: mostly oracle-backed, some asymmetric coverage.
53    pub fn meets_agentic_testing_bar(&self) -> bool {
54        self.total_tests > 0 && self.panic_only_ratio() <= 0.5 && self.asymmetric_coverage() >= 0.2
55    }
56
57    /// Merge another summary into this aggregate.
58    pub fn merge(&mut self, other: &Self) {
59        self.total_tests = self.total_tests.saturating_add(other.total_tests);
60        self.panic_only_tests = self.panic_only_tests.saturating_add(other.panic_only_tests);
61        self.asymmetric_tests = self.asymmetric_tests.saturating_add(other.asymmetric_tests);
62        self.structured_pbt_tests = self.structured_pbt_tests.saturating_add(other.structured_pbt_tests);
63    }
64}
65
66/// Analyze a Rust test source string with cheap heuristics.
67pub fn analyze_test_source(source: &str) -> TestQualitySummary {
68    let mut summary = TestQualitySummary::default();
69    for block in split_test_blocks(source) {
70        summary.total_tests = summary.total_tests.saturating_add(1);
71        if is_panic_only(block) {
72            summary.panic_only_tests = summary.panic_only_tests.saturating_add(1);
73        }
74        if is_asymmetric(block) {
75            summary.asymmetric_tests = summary.asymmetric_tests.saturating_add(1);
76        }
77        if is_structured_pbt(block) {
78            summary.structured_pbt_tests = summary.structured_pbt_tests.saturating_add(1);
79        }
80    }
81    summary
82}
83
84fn split_test_blocks(source: &str) -> Vec<&str> {
85    let mut blocks = Vec::new();
86    let mut rest = source;
87    loop {
88        // Prefer `#[test]`-family markers so a `proptest!` header is never
89        // counted as its own test; fall back to bare `proptest!` only when no
90        // inner test attribute exists.
91        let attr_pos = ["#[test]", "#[tokio::test]", "#[rstest]"]
92            .iter()
93            .filter_map(|marker| rest.find(marker))
94            .min();
95        let pos = match attr_pos {
96            Some(pos) => pos,
97            None => match rest.find("proptest!") {
98                Some(pos) => pos,
99                None => break,
100            },
101        };
102        let next_attr = ["#[test]", "#[tokio::test]", "#[rstest]"]
103            .iter()
104            .filter_map(|marker| rest.get(pos + 1..)?.find(marker).map(|next| pos + 1 + next))
105            .min();
106        let next_prop = rest
107            .get(pos + 1..)
108            .and_then(|tail| tail.find("proptest!").map(|next| pos + 1 + next));
109        let next_test = match (next_attr, next_prop) {
110            (Some(attr), _) => Some(attr),
111            (None, prop) => prop,
112        };
113        let end = next_test.unwrap_or(rest.len());
114        let Some(block) = rest.get(pos..end) else { break };
115        blocks.push(block);
116        if next_test.is_none() {
117            break;
118        }
119        let Some(tail) = rest.get(end..) else { break };
120        rest = tail;
121    }
122    blocks
123}
124
125fn is_panic_only(block: &str) -> bool {
126    // `prop_assume!` filters inputs and `panic!` fails explicitly; neither is a
127    // value oracle. `assert!`/`assert_*` covers `assert_*`/`prop_assert*` while
128    // avoiding prose matches like `assertion`.
129    !(block.contains("assert!") || block.contains("assert_") || block.contains("insta::") || block.contains("expect("))
130}
131
132fn is_asymmetric(block: &str) -> bool {
133    let lowered = block.to_ascii_lowercase();
134    if lowered.contains("both sides") {
135        return true;
136    }
137    // Match whole tokens so `bright`/`leftover`/`border` do not count as
138    // `right`/`left`/`order` coverage.
139    let tokens: Vec<&str> = lowered
140        .split(|character: char| !character.is_ascii_alphanumeric())
141        .filter(|token| !token.is_empty())
142        .collect();
143    const STEMS: &[&str] = &[
144        "asymmetr",
145        "boundary",
146        "boundaries",
147        "revers",
148        "swap",
149        "transpos",
150        "palindrom",
151        "identical",
152    ];
153    const WORDS: &[&str] = &["order", "left", "right"];
154    tokens
155        .iter()
156        .any(|token| STEMS.iter().any(|stem| token.contains(stem)) || WORDS.contains(token))
157}
158
159fn is_structured_pbt(block: &str) -> bool {
160    block.contains("prop_oneof")
161        || block.contains("prop_compose")
162        || block.contains("Just(")
163        || block.contains("strategy")
164        || block.contains("prop::")
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    #[test]
172    fn counts_oracle_backed_and_asymmetric_tests() {
173        let source = r#"
174            #[test]
175            fn transposed_order_is_rejected_asymmetric_boundary() {
176                assert_ne!(vec!["a", "b"], vec!["b", "a"]);
177            }
178            #[test]
179            fn never_panics_smoke() {
180                let _value = vec![1, 2, 3].len();
181            }
182        "#;
183        let summary = analyze_test_source(source);
184        assert_eq!(summary.total_tests, 2);
185        assert_eq!(summary.panic_only_tests, 1);
186        assert_eq!(summary.asymmetric_tests, 1);
187        assert!((summary.panic_only_ratio() - 0.5).abs() < f64::EPSILON);
188        assert!((summary.asymmetric_coverage() - 0.5).abs() < f64::EPSILON);
189    }
190
191    #[test]
192    fn detects_structured_proptest_strategies() {
193        let source = r#"
194            proptest! {
195                #[test]
196                fn order_swap_uses_structured_strategy(a in prop::option::of(Just(1))) {
197                    prop_assert!(a.is_some());
198                }
199            }
200        "#;
201        let summary = analyze_test_source(source);
202        assert_eq!(summary.total_tests, 1);
203        assert_eq!(summary.panic_only_tests, 0);
204        assert_eq!(summary.structured_pbt_tests, 1);
205        assert!(summary.meets_agentic_testing_bar());
206    }
207
208    #[test]
209    fn empty_source_meets_no_bar_but_reports_zero_ratios() {
210        let summary = analyze_test_source("");
211        assert_eq!(summary.total_tests, 0);
212        assert_eq!(summary.panic_only_ratio(), 0.0);
213        assert_eq!(summary.asymmetric_coverage(), 0.0);
214        assert!(!summary.meets_agentic_testing_bar());
215    }
216
217    #[test]
218    fn prop_assume_and_panic_are_not_oracles() {
219        let assume_only = "#[test] fn filtered() { prop_assume!(true); }";
220        assert_eq!(analyze_test_source(assume_only).panic_only_tests, 1);
221        let panic_only = "#[test] fn todo() { panic!(\"todo\"); }";
222        assert_eq!(analyze_test_source(panic_only).panic_only_tests, 1);
223        let asserted = "#[test] fn checked() { assert!(true); }";
224        assert_eq!(analyze_test_source(asserted).panic_only_tests, 0);
225    }
226
227    #[test]
228    fn asymmetric_matching_uses_word_boundaries() {
229        assert_eq!(analyze_test_source("#[test] fn b() { let brightness = 1; assert!(true); }").asymmetric_tests, 0);
230        assert_eq!(analyze_test_source("#[test] fn b() { let leftover = 1; assert!(true); }").asymmetric_tests, 0);
231        assert_eq!(analyze_test_source("#[test] fn b() { fn render_border() {} assert!(true); }").asymmetric_tests, 0);
232        assert_eq!(
233            analyze_test_source("#[test] fn swapped() { assert_ne!(vec![\"a\"], vec![\"b\"]); }").asymmetric_tests,
234            1
235        );
236    }
237
238    #[test]
239    fn counts_tokio_tests() {
240        let source = "#[tokio::test] async fn async_case() { assert!(true); }";
241        assert_eq!(analyze_test_source(source).total_tests, 1);
242    }
243
244    #[test]
245    fn merge_sums_counters() {
246        let mut left = analyze_test_source("#[test] fn a() { assert!(true); }");
247        let right = analyze_test_source("#[test] fn b() { let _x = 1; }");
248        left.merge(&right);
249        assert_eq!(left.total_tests, 2);
250        assert_eq!(left.panic_only_tests, 1);
251    }
252}