pmat 3.17.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#![cfg_attr(coverage_nightly, coverage(off))]
//! Mutation scoring and analysis

use super::types::*;
use std::collections::HashMap;
use std::path::PathBuf;

/// Mutation scorer for analyzing test suite quality
pub struct MutationScorer {
    results: Vec<MutationResult>,
}

impl MutationScorer {
    /// Create new scorer from results
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn new(results: Vec<MutationResult>) -> Self {
        Self { results }
    }

    /// Calculate mutation score
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "score_range")]
    pub fn calculate_score(&self) -> MutationScore {
        MutationScore::from_results(&self.results)
    }

    /// Identify weak spots in test coverage
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn weak_spots(&self) -> Vec<WeakSpot> {
        let mut file_survivors: HashMap<PathBuf, Vec<&MutationResult>> = HashMap::new();

        // Group survived mutants by file
        for result in &self.results {
            if result.status == MutantStatus::Survived {
                file_survivors
                    .entry(result.mutant.original_file.clone())
                    .or_default()
                    .push(result);
            }
        }

        // Create weak spots for files with survived mutants
        let mut weak_spots = Vec::new();

        for (file, survivors) in file_survivors {
            if survivors.is_empty() {
                continue;
            }

            // Find line range
            let min_line = survivors
                .iter()
                .map(|r| r.mutant.location.line)
                .min()
                .unwrap_or(0);
            let max_line = survivors
                .iter()
                .map(|r| r.mutant.location.end_line)
                .max()
                .unwrap_or(0);

            // Generate suggestions
            let suggestions = generate_suggestions(&file, survivors.len());

            weak_spots.push(WeakSpot {
                file,
                line_range: (min_line, max_line),
                survived_mutants: survivors.len(),
                suggestions,
            });
        }

        // Sort by survived mutants (most critical first)
        weak_spots.sort_by(|a, b| b.survived_mutants.cmp(&a.survived_mutants));

        weak_spots
    }

    /// Get summary statistics
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn summary(&self) -> MutationSummary {
        let score = self.calculate_score();
        let weak_spots = self.weak_spots();

        MutationSummary {
            total_mutants: score.total,
            killed: score.killed,
            survived: score.survived,
            compile_errors: score.compile_errors,
            timeouts: score.timeouts,
            equivalent: score.equivalent,
            mutation_score: score.score,
            weak_spots,
        }
    }
}

/// Mutation testing summary
#[derive(Debug, Clone)]
pub struct MutationSummary {
    pub total_mutants: usize,
    pub killed: usize,
    pub survived: usize,
    pub compile_errors: usize,
    pub timeouts: usize,
    pub equivalent: usize,
    pub mutation_score: f64,
    pub weak_spots: Vec<WeakSpot>,
}

/// Generate test improvement suggestions
fn generate_suggestions(file: &PathBuf, survived_count: usize) -> Vec<String> {
    let mut suggestions = Vec::new();

    suggestions.push(format!(
        "Add {} test(s) to cover mutations in {}",
        survived_count,
        file.display()
    ));

    if survived_count > 5 {
        suggestions.push("Consider adding property-based tests to catch edge cases".to_string());
    }

    suggestions.push("Review boundary conditions and error handling in this file".to_string());

    suggestions
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;

    fn create_result(status: MutantStatus, file: &str, line: usize) -> MutationResult {
        MutationResult {
            mutant: Mutant {
                id: "test".to_string(),
                original_file: PathBuf::from(file),
                mutated_source: String::new(),
                location: SourceLocation {
                    line,
                    column: 1,
                    end_line: line,
                    end_column: 10,
                },
                operator: MutationOperatorType::ArithmeticReplacement,
                hash: "hash".to_string(),
                status: status.clone(),
            },
            status,
            test_failures: vec![],
            execution_time_ms: 100,
            error_message: None,
        }
    }

    #[test]
    fn test_mutation_scorer_calculate_score() {
        let results = vec![
            create_result(MutantStatus::Killed, "foo.rs", 10),
            create_result(MutantStatus::Killed, "foo.rs", 20),
            create_result(MutantStatus::Survived, "foo.rs", 30),
        ];

        let scorer = MutationScorer::new(results);
        let score = scorer.calculate_score();

        assert_eq!(score.total, 3);
        assert_eq!(score.killed, 2);
        assert_eq!(score.survived, 1);
        assert!((score.score - 0.666).abs() < 0.01);
    }

    #[test]
    fn test_mutation_scorer_weak_spots() {
        let results = vec![
            create_result(MutantStatus::Survived, "foo.rs", 10),
            create_result(MutantStatus::Survived, "foo.rs", 15),
            create_result(MutantStatus::Survived, "bar.rs", 5),
            create_result(MutantStatus::Killed, "baz.rs", 1),
        ];

        let scorer = MutationScorer::new(results);
        let weak_spots = scorer.weak_spots();

        assert_eq!(weak_spots.len(), 2);

        // foo.rs should be first (2 survivors)
        assert_eq!(weak_spots[0].file, PathBuf::from("foo.rs"));
        assert_eq!(weak_spots[0].survived_mutants, 2);
        assert_eq!(weak_spots[0].line_range, (10, 15));

        // bar.rs should be second (1 survivor)
        assert_eq!(weak_spots[1].file, PathBuf::from("bar.rs"));
        assert_eq!(weak_spots[1].survived_mutants, 1);
    }

    #[test]
    fn test_mutation_scorer_summary() {
        let results = vec![
            create_result(MutantStatus::Killed, "foo.rs", 10),
            create_result(MutantStatus::Survived, "foo.rs", 20),
            create_result(MutantStatus::CompileError, "bar.rs", 5),
        ];

        let scorer = MutationScorer::new(results);
        let summary = scorer.summary();

        assert_eq!(summary.total_mutants, 3);
        assert_eq!(summary.killed, 1);
        assert_eq!(summary.survived, 1);
        assert_eq!(summary.compile_errors, 1);
        assert_eq!(summary.weak_spots.len(), 1);
    }

    // Sprint 25: Dogfooding - Additional edge case tests

    #[test]
    fn test_weak_spots_empty_results() {
        let results = vec![];
        let scorer = MutationScorer::new(results);
        let weak_spots = scorer.weak_spots();

        assert_eq!(
            weak_spots.len(),
            0,
            "Empty results should have no weak spots"
        );
    }

    #[test]
    fn test_weak_spots_no_survivors() {
        let results = vec![
            create_result(MutantStatus::Killed, "foo.rs", 10),
            create_result(MutantStatus::Killed, "bar.rs", 20),
            create_result(MutantStatus::Equivalent, "baz.rs", 30),
        ];

        let scorer = MutationScorer::new(results);
        let weak_spots = scorer.weak_spots();

        assert_eq!(
            weak_spots.len(),
            0,
            "No survivors should mean no weak spots"
        );
    }

    #[test]
    fn test_weak_spots_single_survivor() {
        let results = vec![
            create_result(MutantStatus::Killed, "foo.rs", 10),
            create_result(MutantStatus::Survived, "bar.rs", 20),
        ];

        let scorer = MutationScorer::new(results);
        let weak_spots = scorer.weak_spots();

        assert_eq!(weak_spots.len(), 1);
        assert_eq!(weak_spots[0].file, PathBuf::from("bar.rs"));
        assert_eq!(weak_spots[0].survived_mutants, 1);
        assert_eq!(weak_spots[0].line_range, (20, 20));
    }

    #[test]
    fn test_weak_spots_all_survived() {
        let results = vec![
            create_result(MutantStatus::Survived, "foo.rs", 10),
            create_result(MutantStatus::Survived, "foo.rs", 20),
            create_result(MutantStatus::Survived, "foo.rs", 30),
        ];

        let scorer = MutationScorer::new(results);
        let weak_spots = scorer.weak_spots();

        assert_eq!(weak_spots.len(), 1);
        assert_eq!(weak_spots[0].file, PathBuf::from("foo.rs"));
        assert_eq!(weak_spots[0].survived_mutants, 3);
        assert_eq!(weak_spots[0].line_range, (10, 30));
    }

    #[test]
    fn test_weak_spots_sorting_by_survivor_count() {
        let results = vec![
            create_result(MutantStatus::Survived, "low.rs", 10),
            create_result(MutantStatus::Survived, "high.rs", 20),
            create_result(MutantStatus::Survived, "high.rs", 25),
            create_result(MutantStatus::Survived, "high.rs", 30),
            create_result(MutantStatus::Survived, "medium.rs", 40),
            create_result(MutantStatus::Survived, "medium.rs", 45),
        ];

        let scorer = MutationScorer::new(results);
        let weak_spots = scorer.weak_spots();

        assert_eq!(weak_spots.len(), 3);
        // Should be sorted by survivor count (descending)
        assert_eq!(weak_spots[0].file, PathBuf::from("high.rs"));
        assert_eq!(weak_spots[0].survived_mutants, 3);
        assert_eq!(weak_spots[1].file, PathBuf::from("medium.rs"));
        assert_eq!(weak_spots[1].survived_mutants, 2);
        assert_eq!(weak_spots[2].file, PathBuf::from("low.rs"));
        assert_eq!(weak_spots[2].survived_mutants, 1);
    }

    #[test]
    fn test_generate_suggestions_basic() {
        let file = PathBuf::from("test.rs");
        let suggestions = generate_suggestions(&file, 3);

        assert_eq!(suggestions.len(), 2);
        assert!(suggestions[0].contains("3 test(s)"));
        assert!(suggestions[0].contains("test.rs"));
        assert!(suggestions[1].contains("boundary conditions"));
    }

    #[test]
    fn test_generate_suggestions_many_survivors() {
        let file = PathBuf::from("test.rs");
        let suggestions = generate_suggestions(&file, 10);

        assert_eq!(suggestions.len(), 3);
        assert!(suggestions[0].contains("10 test(s)"));
        assert!(suggestions[1].contains("property-based tests"));
        assert!(suggestions[2].contains("boundary conditions"));
    }

    #[test]
    fn test_generate_suggestions_boundary_five() {
        let file = PathBuf::from("test.rs");

        // Exactly 5 should NOT include property-based test suggestion
        let suggestions_five = generate_suggestions(&file, 5);
        assert_eq!(suggestions_five.len(), 2);
        assert!(!suggestions_five
            .iter()
            .any(|s| s.contains("property-based")));

        // 6 or more SHOULD include property-based test suggestion
        let suggestions_six = generate_suggestions(&file, 6);
        assert_eq!(suggestions_six.len(), 3);
        assert!(suggestions_six.iter().any(|s| s.contains("property-based")));
    }

    #[test]
    fn test_summary_empty_results() {
        let results = vec![];
        let scorer = MutationScorer::new(results);
        let summary = scorer.summary();

        assert_eq!(summary.total_mutants, 0);
        assert_eq!(summary.killed, 0);
        assert_eq!(summary.survived, 0);
        assert_eq!(summary.mutation_score, 0.0);
        assert_eq!(summary.weak_spots.len(), 0);
    }

    #[test]
    fn test_summary_all_killed() {
        let results = vec![
            create_result(MutantStatus::Killed, "foo.rs", 10),
            create_result(MutantStatus::Killed, "bar.rs", 20),
            create_result(MutantStatus::Killed, "baz.rs", 30),
        ];

        let scorer = MutationScorer::new(results);
        let summary = scorer.summary();

        assert_eq!(summary.total_mutants, 3);
        assert_eq!(summary.killed, 3);
        assert_eq!(summary.survived, 0);
        assert_eq!(summary.mutation_score, 1.0);
        assert_eq!(
            summary.weak_spots.len(),
            0,
            "Perfect score should have no weak spots"
        );
    }

    #[test]
    fn test_summary_mixed_with_multiple_weak_spots() {
        let results = vec![
            create_result(MutantStatus::Killed, "foo.rs", 10),
            create_result(MutantStatus::Survived, "weak1.rs", 20),
            create_result(MutantStatus::Survived, "weak2.rs", 30),
            create_result(MutantStatus::Survived, "weak2.rs", 35),
            create_result(MutantStatus::CompileError, "error.rs", 40),
        ];

        let scorer = MutationScorer::new(results);
        let summary = scorer.summary();

        assert_eq!(summary.total_mutants, 5);
        assert_eq!(summary.killed, 1);
        assert_eq!(summary.survived, 3);
        assert_eq!(summary.compile_errors, 1);
        assert_eq!(summary.weak_spots.len(), 2);
        // weak2.rs should be first (2 survivors)
        assert_eq!(summary.weak_spots[0].survived_mutants, 2);
        // weak1.rs should be second (1 survivor)
        assert_eq!(summary.weak_spots[1].survived_mutants, 1);
    }
}