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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_comprehensive_handler_params() {
        // Basic parameter validation test
        assert_eq!(
            ComprehensiveOutputFormat::Json as i32,
            ComprehensiveOutputFormat::Json as i32
        );
    }

    #[test]
    fn test_find_project_root() {
        use std::fs;
        use tempfile::TempDir;

        // Create a temporary directory structure
        let temp_dir = TempDir::new().unwrap();
        let project_root = temp_dir.path();
        let src_dir = project_root.join("src");
        let sub_dir = src_dir.join("module");

        // Create directories
        fs::create_dir_all(&sub_dir).unwrap();

        // Create Cargo.toml at project root
        fs::write(
            project_root.join("Cargo.toml"),
            "[package]\nname = \"test\"",
        )
        .unwrap();

        // Create a test file deep in the structure
        let test_file = sub_dir.join("test.rs");
        fs::write(&test_file, "// test file").unwrap();

        // Test finding project root from file
        let found_root = find_project_root(&test_file).unwrap();
        assert_eq!(found_root, project_root);

        // Test finding project root from directory
        let found_root = find_project_root(&sub_dir).unwrap();
        assert_eq!(found_root, project_root);

        // Test when no Cargo.toml exists
        let isolated_dir = TempDir::new().unwrap();
        let isolated_file = isolated_dir.path().join("isolated.rs");
        fs::write(&isolated_file, "// isolated file").unwrap();

        let found_root = find_project_root(&isolated_file).unwrap();
        assert_eq!(found_root, isolated_dir.path());
    }

    #[tokio::test]
    async fn test_comprehensive_single_file_filter() {
        use crate::models::defect_report::{Defect, DefectCategory, Severity};
        use std::collections::HashMap;

        // Create test defects for different files
        let defects = [
            Defect {
                id: "1".to_string(),
                category: DefectCategory::Complexity,
                severity: Severity::High,
                file_path: PathBuf::from("src/main.rs"),
                line_start: 10,
                line_end: Some(20),
                column_start: Some(5),
                column_end: Some(10),
                message: "High complexity in main".to_string(),
                rule_id: "complexity".to_string(),
                fix_suggestion: Some("Refactor".to_string()),
                metrics: HashMap::from([("confidence".to_string(), 0.8)]),
            },
            Defect {
                id: "2".to_string(),
                category: DefectCategory::Complexity,
                severity: Severity::Medium,
                file_path: PathBuf::from("src/lib.rs"),
                line_start: 15,
                line_end: Some(25),
                column_start: Some(3),
                column_end: Some(8),
                message: "Medium complexity in lib".to_string(),
                rule_id: "complexity".to_string(),
                fix_suggestion: Some("Consider refactoring".to_string()),
                metrics: HashMap::from([("confidence".to_string(), 0.7)]),
            },
        ];

        // Test single file filtering
        let target_file = Some(PathBuf::from("src/main.rs"));
        let filtered: Vec<_> = defects
            .iter()
            .filter(|d| {
                if let Some(ref tf) = target_file {
                    d.file_path == *tf
                } else {
                    true
                }
            })
            .collect();

        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].id, "1");
        assert_eq!(filtered[0].file_path, PathBuf::from("src/main.rs"));
    }

    // ========================================================================
    // Helpers for analysis-helper coverage tests (Wave 31)
    // ========================================================================

    fn build_empty_config() -> ComprehensiveConfig {
        ComprehensiveConfig {
            project_path: PathBuf::from("."),
            file: None,
            files: vec![],
            format: ComprehensiveOutputFormat::Json,
            include_duplicates: false,
            include_dead_code: false,
            include_defects: false,
            include_complexity: false,
            include_tdg: false,
            confidence_threshold: 0.0,
            min_lines: 0,
            include: None,
            exclude: None,
            output: None,
            perf: false,
            executive_summary: false,
        }
    }

    fn build_defect(id: &str, file: &str, confidence: f64) -> crate::models::defect_report::Defect {
        use crate::models::defect_report::{Defect, DefectCategory, Severity};
        use std::collections::HashMap;
        Defect {
            id: id.to_string(),
            severity: Severity::Medium,
            category: DefectCategory::Complexity,
            file_path: PathBuf::from(file),
            line_start: 1,
            line_end: None,
            column_start: None,
            column_end: None,
            message: String::new(),
            rule_id: "rule".to_string(),
            fix_suggestion: None,
            metrics: HashMap::from([("confidence".to_string(), confidence)]),
        }
    }

    fn build_empty_report() -> crate::models::defect_report::DefectReport {
        use crate::models::defect_report::{DefectReport, DefectSummary, ReportMetadata};
        use chrono::Utc;
        use std::collections::BTreeMap;
        DefectReport {
            metadata: ReportMetadata {
                tool: "pmat".to_string(),
                version: "test".to_string(),
                generated_at: Utc::now(),
                project_root: PathBuf::from("."),
                total_files_analyzed: 0,
                analysis_duration_ms: 0,
            },
            defects: vec![],
            summary: DefectSummary {
                total_defects: 0,
                by_severity: BTreeMap::new(),
                by_category: BTreeMap::new(),
                hotspot_files: vec![],
            },
            file_index: BTreeMap::new(),
        }
    }

    // ========================================================================
    // is_system_root
    // ========================================================================

    #[test]
    fn test_is_system_root_tmp() {
        assert!(is_system_root(Path::new("/tmp")));
    }

    #[test]
    fn test_is_system_root_root() {
        assert!(is_system_root(Path::new("/")));
    }

    #[test]
    fn test_is_system_root_home() {
        assert!(is_system_root(Path::new("/home")));
    }

    #[test]
    fn test_is_system_root_other_path_false() {
        assert!(!is_system_root(Path::new("/usr/local")));
        assert!(!is_system_root(Path::new("/home/user")));
        assert!(!is_system_root(Path::new("./relative")));
    }

    // ========================================================================
    // walk_up_to_cargo_toml
    // ========================================================================

    #[test]
    fn test_walk_up_to_cargo_toml_finds_self() {
        use std::fs;
        use tempfile::TempDir;
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join("Cargo.toml"), "[package]\nname=\"x\"").unwrap();
        let found = walk_up_to_cargo_toml(tmp.path());
        assert_eq!(found, Some(tmp.path().to_path_buf()));
    }

    #[test]
    fn test_walk_up_to_cargo_toml_finds_ancestor() {
        use std::fs;
        use tempfile::TempDir;
        let tmp = TempDir::new().unwrap();
        let nested = tmp.path().join("a").join("b").join("c");
        fs::create_dir_all(&nested).unwrap();
        fs::write(tmp.path().join("Cargo.toml"), "[package]\nname=\"x\"").unwrap();
        let found = walk_up_to_cargo_toml(&nested);
        assert_eq!(found, Some(tmp.path().to_path_buf()));
    }

    #[test]
    fn test_walk_up_to_cargo_toml_stops_at_system_root() {
        // Walking up from /tmp directly returns None because is_system_root(parent)
        // short-circuits before reaching anything with Cargo.toml.
        let found = walk_up_to_cargo_toml(Path::new("/tmp/definitely-not-a-real-project-xyz"));
        assert!(found.is_none());
    }

    // ========================================================================
    // get_enabled_analyses
    // ========================================================================

    #[test]
    fn test_get_enabled_analyses_none() {
        let cfg = build_empty_config();
        assert!(get_enabled_analyses(&cfg).is_empty());
    }

    #[test]
    fn test_get_enabled_analyses_complexity_only() {
        let mut cfg = build_empty_config();
        cfg.include_complexity = true;
        assert_eq!(get_enabled_analyses(&cfg), vec!["Complexity"]);
    }

    #[test]
    fn test_get_enabled_analyses_tdg_only() {
        let mut cfg = build_empty_config();
        cfg.include_tdg = true;
        assert_eq!(get_enabled_analyses(&cfg), vec!["TDG"]);
    }

    #[test]
    fn test_get_enabled_analyses_defects_only() {
        let mut cfg = build_empty_config();
        cfg.include_defects = true;
        assert_eq!(get_enabled_analyses(&cfg), vec!["Defects"]);
    }

    #[test]
    fn test_get_enabled_analyses_dead_code_only() {
        let mut cfg = build_empty_config();
        cfg.include_dead_code = true;
        assert_eq!(get_enabled_analyses(&cfg), vec!["Dead Code"]);
    }

    #[test]
    fn test_get_enabled_analyses_duplicates_only() {
        let mut cfg = build_empty_config();
        cfg.include_duplicates = true;
        assert_eq!(get_enabled_analyses(&cfg), vec!["Duplicates"]);
    }

    #[test]
    fn test_get_enabled_analyses_all_in_order() {
        let mut cfg = build_empty_config();
        cfg.include_complexity = true;
        cfg.include_tdg = true;
        cfg.include_defects = true;
        cfg.include_dead_code = true;
        cfg.include_duplicates = true;
        assert_eq!(
            get_enabled_analyses(&cfg),
            vec!["Complexity", "TDG", "Defects", "Dead Code", "Duplicates"]
        );
    }

    // ========================================================================
    // filter_defects
    // ========================================================================

    #[test]
    fn test_filter_defects_threshold_keeps_high_confidence() {
        let defects = vec![
            build_defect("a", "src/x.rs", 0.9),
            build_defect("b", "src/y.rs", 0.4),
        ];
        let kept = filter_defects(&defects, false, &[], 0.5);
        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].id, "a");
    }

    #[test]
    fn test_filter_defects_threshold_default_confidence_when_missing() {
        // Defects without "confidence" metric default to 1.0 and are always kept.
        let mut defect = build_defect("a", "src/x.rs", 0.0);
        defect.metrics.clear();
        let kept = filter_defects(&[defect], false, &[], 0.99);
        assert_eq!(kept.len(), 1);
    }

    #[test]
    fn test_filter_defects_single_file_mode_keeps_target() {
        let defects = vec![
            build_defect("a", "src/main.rs", 1.0),
            build_defect("b", "src/lib.rs", 1.0),
        ];
        let targets = vec![PathBuf::from("src/main.rs")];
        let kept = filter_defects(&defects, true, &targets, 0.0);
        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].id, "a");
    }

    #[test]
    fn test_filter_defects_single_file_mode_empty_targets_keeps_all() {
        // When single_file_mode is true but target_files is empty, the
        // file-targeting filter is skipped and all confidence-passing defects pass.
        let defects = vec![
            build_defect("a", "src/x.rs", 1.0),
            build_defect("b", "src/y.rs", 1.0),
        ];
        let kept = filter_defects(&defects, true, &[], 0.0);
        assert_eq!(kept.len(), 2);
    }

    #[test]
    fn test_filter_defects_project_mode_ignores_targets() {
        let defects = vec![
            build_defect("a", "src/main.rs", 1.0),
            build_defect("b", "src/lib.rs", 1.0),
        ];
        let targets = vec![PathBuf::from("src/main.rs")];
        let kept = filter_defects(&defects, false, &targets, 0.0);
        assert_eq!(kept.len(), 2);
    }

    // ========================================================================
    // determine_analysis_mode
    // ========================================================================

    #[test]
    fn test_determine_analysis_mode_project_path() {
        let mut cfg = build_empty_config();
        cfg.project_path = PathBuf::from("/my/project");
        let (path, single, targets) = determine_analysis_mode(&cfg).unwrap();
        assert_eq!(path, PathBuf::from("/my/project"));
        assert!(!single);
        assert!(targets.is_empty());
    }

    #[test]
    fn test_determine_analysis_mode_single_file_promotes_to_target() {
        use std::fs;
        use tempfile::TempDir;
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join("Cargo.toml"), "[package]\nname=\"x\"").unwrap();
        let file = tmp.path().join("src.rs");
        fs::write(&file, "// src").unwrap();

        let mut cfg = build_empty_config();
        cfg.file = Some(file.clone());
        let (path, single, targets) = determine_analysis_mode(&cfg).unwrap();
        assert_eq!(path, tmp.path());
        assert!(single);
        assert_eq!(targets, vec![file]);
    }

    #[test]
    fn test_determine_analysis_mode_files_override_takes_precedence() {
        let mut cfg = build_empty_config();
        cfg.files = vec![PathBuf::from("a.rs"), PathBuf::from("b.rs")];
        cfg.file = Some(PathBuf::from("ignored.rs"));
        // file is Some, so single_file_mode is true; but targets come from `files` (non-empty).
        // determine_analysis_mode also calls find_project_root on the `file` path.
        // Use a real path to keep find_project_root happy via fallback.
        cfg.file = None;
        let (_path, single, targets) = determine_analysis_mode(&cfg).unwrap();
        assert!(!single);
        assert_eq!(targets, vec![PathBuf::from("a.rs"), PathBuf::from("b.rs")]);
    }

    // ========================================================================
    // format_report
    // ========================================================================

    #[test]
    fn test_format_report_json() {
        let svc = crate::services::defect_report_service::DefectReportService::new();
        let report = build_empty_report();
        let mut cfg = build_empty_config();
        cfg.format = ComprehensiveOutputFormat::Json;
        let out = format_report(&svc, &report, vec![], &cfg).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert!(parsed.is_object());
        assert!(parsed.get("defects").is_some());
    }

    #[test]
    fn test_format_report_summary_yields_text() {
        let svc = crate::services::defect_report_service::DefectReportService::new();
        let report = build_empty_report();
        let mut cfg = build_empty_config();
        cfg.format = ComprehensiveOutputFormat::Summary;
        let out = format_report(&svc, &report, vec![], &cfg).unwrap();
        assert!(!out.is_empty());
    }

    #[test]
    fn test_format_report_detailed_yields_text() {
        let svc = crate::services::defect_report_service::DefectReportService::new();
        let report = build_empty_report();
        let mut cfg = build_empty_config();
        cfg.format = ComprehensiveOutputFormat::Detailed;
        let out = format_report(&svc, &report, vec![], &cfg).unwrap();
        assert!(!out.is_empty());
    }

    #[test]
    fn test_format_report_markdown_yields_text() {
        let svc = crate::services::defect_report_service::DefectReportService::new();
        let report = build_empty_report();
        let mut cfg = build_empty_config();
        cfg.format = ComprehensiveOutputFormat::Markdown;
        let out = format_report(&svc, &report, vec![], &cfg).unwrap();
        assert!(!out.is_empty());
    }

    #[test]
    fn test_format_report_sarif_yields_json() {
        let svc = crate::services::defect_report_service::DefectReportService::new();
        let report = build_empty_report();
        let mut cfg = build_empty_config();
        cfg.format = ComprehensiveOutputFormat::Sarif;
        let out = format_report(&svc, &report, vec![], &cfg).unwrap();
        // Sarif arm produces JSON via serde_json::to_string_pretty
        let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert!(parsed.is_object());
    }

    #[test]
    fn test_format_report_overrides_defects_with_filtered() {
        let svc = crate::services::defect_report_service::DefectReportService::new();
        let report = build_empty_report();
        let mut cfg = build_empty_config();
        cfg.format = ComprehensiveOutputFormat::Json;

        let filtered = vec![build_defect("seen", "src/x.rs", 1.0)];
        let out = format_report(&svc, &report, filtered, &cfg).unwrap();
        assert!(out.contains("\"seen\""));
    }

    // ========================================================================
    // warn_ignored_parameters / print_performance_metrics
    // (no-op + info!() side effects only — exercise without panic)
    // ========================================================================

    #[test]
    fn test_warn_ignored_parameters_is_noop() {
        warn_ignored_parameters(&build_empty_config());
    }

    #[test]
    fn test_print_performance_metrics_runs() {
        let report = build_empty_report();
        print_performance_metrics(std::time::Duration::from_millis(1), &report);
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod property_tests {
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn basic_property_stability(_input in ".*") {
            // Basic property test for coverage
            prop_assert!(true);
        }

        #[test]
        fn module_consistency_check(_x in 0u32..1000) {
            // Module consistency verification
            prop_assert!(_x < 1001);
        }
    }
}