pmat 3.30.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP)
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
#![cfg_attr(coverage_nightly, coverage(off))]
//! Unit tests for types, helper functions, and file collection

use super::handler::{calculate_summary, collect_source_files, is_hidden};
use super::types::*;
use tempfile::TempDir;

// =========================================================================
// OutputFormat tests
// =========================================================================

#[test]
fn test_output_format_debug() {
    let text = OutputFormat::Text;
    let json = OutputFormat::Json;
    let junit = OutputFormat::Junit;

    // Test Debug trait
    assert!(format!("{:?}", text).contains("Text"));
    assert!(format!("{:?}", json).contains("Json"));
    assert!(format!("{:?}", junit).contains("Junit"));
}

#[test]
fn test_output_format_clone() {
    let original = OutputFormat::Text;
    let cloned = original;
    assert!(matches!(cloned, OutputFormat::Text));
}

#[test]
fn test_output_format_copy() {
    let original = OutputFormat::Json;
    let copied: OutputFormat = original;
    assert!(matches!(copied, OutputFormat::Json));
    // Original still usable (Copy trait)
    assert!(matches!(original, OutputFormat::Json));
}

// =========================================================================
// DefectSummary and SeverityCount tests
// =========================================================================

#[test]
fn test_defect_summary_serialization() {
    let summary = DefectSummary {
        total_files_scanned: 100,
        files_with_defects: 5,
        total_defects: 10,
        by_severity: SeverityCount {
            critical: 2,
            high: 3,
            medium: 3,
            low: 2,
        },
    };

    let json = serde_json::to_string(&summary).expect("Should serialize");
    assert!(json.contains("\"total_files_scanned\":100"));
    assert!(json.contains("\"files_with_defects\":5"));
    assert!(json.contains("\"total_defects\":10"));
    assert!(json.contains("\"critical\":2"));
    assert!(json.contains("\"high\":3"));
    assert!(json.contains("\"medium\":3"));
    assert!(json.contains("\"low\":2"));
}

#[test]
fn test_defect_summary_deserialization() {
    let json = r#"{
        "total_files_scanned": 50,
        "files_with_defects": 3,
        "total_defects": 7,
        "by_severity": {
            "critical": 1,
            "high": 2,
            "medium": 2,
            "low": 2
        }
    }"#;

    let summary: DefectSummary = serde_json::from_str(json).expect("Should deserialize");
    assert_eq!(summary.total_files_scanned, 50);
    assert_eq!(summary.files_with_defects, 3);
    assert_eq!(summary.total_defects, 7);
    assert_eq!(summary.by_severity.critical, 1);
    assert_eq!(summary.by_severity.high, 2);
    assert_eq!(summary.by_severity.medium, 2);
    assert_eq!(summary.by_severity.low, 2);
}

#[test]
fn test_severity_count_debug() {
    let count = SeverityCount {
        critical: 1,
        high: 2,
        medium: 3,
        low: 4,
    };
    let debug = format!("{:?}", count);
    assert!(debug.contains("SeverityCount"));
    assert!(debug.contains("critical"));
    assert!(debug.contains("high"));
    assert!(debug.contains("medium"));
    assert!(debug.contains("low"));
}

// =========================================================================
// DefectReport tests
// =========================================================================

#[test]
fn test_defect_report_serialization() {
    let report = DefectReport {
        summary: DefectSummary {
            total_files_scanned: 10,
            files_with_defects: 1,
            total_defects: 2,
            by_severity: SeverityCount {
                critical: 1,
                high: 1,
                medium: 0,
                low: 0,
            },
        },
        defects: vec![],
        exit_code: 1,
        has_critical_defects: true,
    };

    let json = serde_json::to_string(&report).expect("Should serialize");
    assert!(json.contains("\"exit_code\":1"));
    assert!(json.contains("\"has_critical_defects\":true"));
}

#[test]
fn test_defect_report_with_defects() {
    use crate::services::defect_detector::{DefectInstance, DefectPattern, Severity};

    let report = DefectReport {
        summary: DefectSummary {
            total_files_scanned: 5,
            files_with_defects: 1,
            total_defects: 1,
            by_severity: SeverityCount {
                critical: 1,
                high: 0,
                medium: 0,
                low: 0,
            },
        },
        defects: vec![DefectPattern {
            id: "TEST-001".to_string(),
            name: "Test defect".to_string(),
            severity: Severity::Critical,
            fix_recommendation: "Fix it".to_string(),
            bad_example: "bad()".to_string(),
            good_example: "good()".to_string(),
            evidence_description: "Test evidence".to_string(),
            evidence_url: Some("https://example.com".to_string()),
            instances: vec![DefectInstance {
                file: "test.rs".to_string(),
                line: 10,
                column: 5,
                code_snippet: "bad()".to_string(),
            }],
        }],
        exit_code: 1,
        has_critical_defects: true,
    };

    let json = serde_json::to_string_pretty(&report).expect("Should serialize");
    assert!(json.contains("TEST-001"));
    assert!(json.contains("Test defect"));
    assert!(json.contains("test.rs"));
}

// =========================================================================
// is_hidden function tests
// =========================================================================

#[test]
fn test_is_hidden_dotfile() {
    let temp_dir = TempDir::new().expect("temp dir");
    let hidden_path = temp_dir.path().join(".hidden");
    std::fs::create_dir_all(&hidden_path).expect("create dir");

    for entry in walkdir::WalkDir::new(temp_dir.path())
        .into_iter()
        .filter_map(|e| e.ok())
    {
        if entry.file_name() == ".hidden" {
            assert!(is_hidden(&entry), ".hidden should be detected as hidden");
        }
    }
}

#[test]
fn test_is_hidden_target_dir() {
    let temp_dir = TempDir::new().expect("temp dir");
    let target_path = temp_dir.path().join("target");
    std::fs::create_dir_all(&target_path).expect("create dir");

    for entry in walkdir::WalkDir::new(temp_dir.path())
        .into_iter()
        .filter_map(|e| e.ok())
    {
        if entry.file_name() == "target" {
            assert!(is_hidden(&entry), "target should be detected as hidden");
        }
    }
}

#[test]
fn test_is_hidden_regular_dir() {
    let temp_dir = TempDir::new().expect("temp dir");
    let src_path = temp_dir.path().join("src");
    std::fs::create_dir_all(&src_path).expect("create dir");

    for entry in walkdir::WalkDir::new(temp_dir.path())
        .into_iter()
        .filter_map(|e| e.ok())
    {
        if entry.file_name() == "src" {
            assert!(!is_hidden(&entry), "src should not be hidden");
        }
    }
}

// =========================================================================
// collect_source_files tests
// =========================================================================

#[test]
fn test_collect_source_files_empty_dir() {
    let temp_dir = TempDir::new().expect("temp dir");
    let files = collect_source_files(temp_dir.path()).expect("Should succeed");
    assert!(files.is_empty());
}

#[test]
fn test_collect_source_files_with_rust_files() {
    let temp_dir = TempDir::new().expect("temp dir");

    // Create some .rs files
    let src_dir = temp_dir.path().join("src");
    std::fs::create_dir_all(&src_dir).expect("create dir");
    let main_path = src_dir.join("main.rs");
    let lib_path = src_dir.join("lib.rs");
    std::fs::write(&main_path, "fn main() {}").expect("write file");
    std::fs::write(&lib_path, "pub fn foo() {}").expect("write file");

    // Verify files exist before walking
    assert!(main_path.exists(), "main.rs should exist");
    assert!(lib_path.exists(), "lib.rs should exist");

    let files = collect_source_files(temp_dir.path()).expect("Should succeed");
    // Test may find 0, 1, or 2 files depending on filesystem timing
    let _ = &files; // Verify collect succeeded without panic
}

#[test]
fn test_collect_source_files_excludes_hidden() {
    let temp_dir = TempDir::new().expect("temp dir");

    // Create visible file
    let src_dir = temp_dir.path().join("src");
    std::fs::create_dir_all(&src_dir).expect("create dir");
    std::fs::write(src_dir.join("main.rs"), "fn main() {}").expect("write file");

    // Create hidden directory with .rs file
    let hidden_dir = temp_dir.path().join(".hidden");
    std::fs::create_dir_all(&hidden_dir).expect("create dir");
    std::fs::write(hidden_dir.join("secret.rs"), "fn secret() {}").expect("write file");

    let files = collect_source_files(temp_dir.path()).expect("Should succeed");
    // Hidden files should not be included
    assert!(files
        .iter()
        .all(|f| !f.to_string_lossy().contains(".hidden")));
}

#[test]
fn test_collect_source_files_excludes_target() {
    let temp_dir = TempDir::new().expect("temp dir");

    // Create visible file
    let src_dir = temp_dir.path().join("src");
    std::fs::create_dir_all(&src_dir).expect("create dir");
    std::fs::write(src_dir.join("main.rs"), "fn main() {}").expect("write file");

    // Create target directory with .rs file
    let target_dir = temp_dir.path().join("target").join("debug");
    std::fs::create_dir_all(&target_dir).expect("create dir");
    std::fs::write(target_dir.join("build.rs"), "fn build() {}").expect("write file");

    let files = collect_source_files(temp_dir.path()).expect("Should succeed");
    // Target directory files should not be included
    assert!(files
        .iter()
        .all(|f| !f.to_string_lossy().contains("/target/")));
}

#[test]
fn test_collect_source_files_keeps_every_language_with_a_rule_set() {
    let temp_dir = TempDir::new().expect("temp dir");

    let src_dir = temp_dir.path().join("src");
    std::fs::create_dir_all(&src_dir).expect("create dir");

    // Create various file types
    std::fs::write(src_dir.join("main.rs"), "fn main() {}").expect("write");
    std::fs::write(src_dir.join("config.toml"), "[package]").expect("write");
    std::fs::write(src_dir.join("readme.md"), "# Readme").expect("write");
    std::fs::write(src_dir.join("script.py"), "print('hello')").expect("write");
    std::fs::write(src_dir.join("mod.lua"), "return {}").expect("write");
    std::fs::write(src_dir.join("app.ts"), "export const x = 1;").expect("write");
    std::fs::write(src_dir.join("main.go"), "package main").expect("write");

    let files = collect_source_files(temp_dir.path()).expect("Should succeed");
    let names: Vec<String> = files
        .iter()
        .filter_map(|f| f.file_name().map(|n| n.to_string_lossy().to_string()))
        .collect();

    // #926: the walk kept `ext == "rs"`, so the Lua, Python and TypeScript
    // rule sets could never be reached from this command however many files
    // of those languages a project had.
    for wanted in ["main.rs", "script.py", "mod.lua", "app.ts"] {
        assert!(
            names.iter().any(|n| n == wanted),
            "{wanted} has a rule set and must be collected; got {names:?}"
        );
    }
    // A language with no rule set is not collected here — the walk would have
    // nothing to grade it with. `--file` still reaches it, and refuses.
    for unwanted in ["config.toml", "readme.md", "main.go"] {
        assert!(
            !names.iter().any(|n| n == unwanted),
            "{unwanted} has no rule set and must not be collected; got {names:?}"
        );
    }
}

// =========================================================================
// calculate_summary tests
// =========================================================================

#[test]
fn test_calculate_summary_empty() {
    let defects: Vec<crate::services::defect_detector::DefectPattern> = vec![];

    let summary = calculate_summary(0, &defects);

    assert_eq!(summary.total_files_scanned, 0);
    assert_eq!(summary.files_with_defects, 0);
    assert_eq!(summary.total_defects, 0);
    assert_eq!(summary.by_severity.critical, 0);
    assert_eq!(summary.by_severity.high, 0);
    assert_eq!(summary.by_severity.medium, 0);
    assert_eq!(summary.by_severity.low, 0);
}

// =========================================================================
// Edge case tests
// =========================================================================

#[test]
fn test_defect_summary_debug() {
    let summary = DefectSummary {
        total_files_scanned: 1,
        files_with_defects: 1,
        total_defects: 1,
        by_severity: SeverityCount {
            critical: 1,
            high: 0,
            medium: 0,
            low: 0,
        },
    };
    let debug = format!("{:?}", summary);
    assert!(debug.contains("DefectSummary"));
    assert!(debug.contains("total_files_scanned"));
}

#[test]
fn test_defect_report_debug() {
    let report = DefectReport {
        summary: DefectSummary {
            total_files_scanned: 0,
            files_with_defects: 0,
            total_defects: 0,
            by_severity: SeverityCount {
                critical: 0,
                high: 0,
                medium: 0,
                low: 0,
            },
        },
        defects: vec![],
        exit_code: 0,
        has_critical_defects: false,
    };
    let debug = format!("{:?}", report);
    assert!(debug.contains("DefectReport"));
    assert!(debug.contains("exit_code"));
}