Skip to main content

mir_analyzer/
test_utils.rs

1//! Test utilities for fixture-based testing.
2//!
3//! Provides helpers to run `.phpt` fixture files against the analyzer
4//! and compare actual vs expected issues.
5
6use std::path::PathBuf;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use crate::project::ProjectAnalyzer;
10use mir_issues::{Issue, IssueKind};
11
12static COUNTER: AtomicU64 = AtomicU64::new(0);
13
14/// Run the full analyzer on an inline PHP string.
15/// Creates a unique temp file, analyzes it, deletes it, and returns all
16/// unsuppressed issues.
17pub fn check(src: &str) -> Vec<Issue> {
18    check_with_opts(src, false)
19}
20
21/// Like [`check`] but also runs the dead-code detector
22/// (`UnusedMethod`, `UnusedProperty`).
23pub fn check_dead_code(src: &str) -> Vec<Issue> {
24    check_with_opts(src, true)
25}
26
27fn check_with_opts(src: &str, find_dead_code: bool) -> Vec<Issue> {
28    let id = COUNTER.fetch_add(1, Ordering::Relaxed);
29    let tmp: PathBuf = std::env::temp_dir().join(format!("mir_test_{}.php", id));
30    std::fs::write(&tmp, src)
31        .unwrap_or_else(|e| panic!("failed to write temp PHP file {}: {}", tmp.display(), e));
32    let mut analyzer = ProjectAnalyzer::new();
33    analyzer.find_dead_code = find_dead_code;
34    let result = analyzer.analyze(std::slice::from_ref(&tmp));
35    let tmp_str = tmp.to_string_lossy().into_owned();
36    std::fs::remove_file(&tmp).ok();
37    result
38        .issues
39        .into_iter()
40        .filter(|i| !i.suppressed)
41        // When dead-code analysis is enabled the analyzer walks the entire
42        // codebase (including PHP stubs).  Filter to issues originating from
43        // the test file only so that stub-side false positives don't pollute
44        // the fixture output.
45        .filter(|i| !find_dead_code || i.location.file.as_ref() == tmp_str.as_str())
46        .collect()
47}
48
49// ---------------------------------------------------------------------------
50// Fixture-based test support
51// ---------------------------------------------------------------------------
52
53/// One expected issue from a `.phpt` fixture's `===expect===` section.
54///
55/// Format: `KindName: full human-readable message`
56pub struct ExpectedIssue {
57    pub kind_name: String,
58    pub message: String,
59}
60
61/// Parse a `.phpt` fixture file into `(php_source, expected_issues)`.
62///
63/// Fixture format:
64/// ```text
65/// ===source===
66/// <?php
67/// ...
68/// ===expect===
69/// UndefinedClass: Class 'UnknownClass' not found
70/// UndefinedFunction: Function 'foo' not found
71/// ```
72/// An empty `===expect===` section means no issues are expected.
73pub fn parse_phpt(content: &str, path: &str) -> (String, Vec<ExpectedIssue>) {
74    let source_marker = "===source===";
75    let expect_marker = "===expect===";
76
77    let source_pos = content
78        .find(source_marker)
79        .unwrap_or_else(|| panic!("fixture {} missing ===source=== section", path));
80    let expect_pos = content
81        .find(expect_marker)
82        .unwrap_or_else(|| panic!("fixture {} missing ===expect=== section", path));
83
84    assert!(
85        source_pos < expect_pos,
86        "fixture {}: ===source=== must come before ===expect===",
87        path
88    );
89
90    let source = content[source_pos + source_marker.len()..expect_pos]
91        .trim()
92        .to_string();
93    let expect_section = content[expect_pos + expect_marker.len()..].trim();
94
95    let expected: Vec<ExpectedIssue> = expect_section
96        .lines()
97        .map(str::trim)
98        .filter(|l| !l.is_empty() && !l.starts_with('#'))
99        .map(|l| parse_expected_line(l, path))
100        .collect();
101
102    (source, expected)
103}
104
105/// Extract only the source section from a fixture file (used in UPDATE_FIXTURES mode
106/// to avoid parsing potentially stale/old-format expect sections).
107fn parse_phpt_source_only(content: &str, path: &str) -> String {
108    let source_marker = "===source===";
109    let expect_marker = "===expect===";
110
111    let source_pos = content
112        .find(source_marker)
113        .unwrap_or_else(|| panic!("fixture {} missing ===source=== section", path));
114    let expect_pos = content
115        .find(expect_marker)
116        .unwrap_or_else(|| panic!("fixture {} missing ===expect=== section", path));
117
118    content[source_pos + source_marker.len()..expect_pos]
119        .trim()
120        .to_string()
121}
122
123fn parse_expected_line(line: &str, fixture_path: &str) -> ExpectedIssue {
124    // Format: "KindName: full human-readable message"
125    let parts: Vec<&str> = line.splitn(2, ": ").collect();
126    assert_eq!(
127        parts.len(),
128        2,
129        "fixture {}: invalid expect line {:?} — expected \"KindName: message\"",
130        fixture_path,
131        line
132    );
133    ExpectedIssue {
134        kind_name: parts[0].trim().to_string(),
135        message: parts[1].trim().to_string(),
136    }
137}
138
139/// Run a `.phpt` fixture file: parse, analyze, and assert the issues match
140/// the `===expect===` section exactly (no missing, no unexpected).
141///
142/// If the environment variable `UPDATE_FIXTURES` is set to `1`, the fixture
143/// file is rewritten with the actual issues instead of asserting.
144///
145/// Called by the auto-generated test functions in `build.rs`.
146pub fn run_fixture(path: &str) {
147    run_fixture_with_opts(path, false);
148}
149
150/// Like [`run_fixture`] but also enables the dead-code detector for issue kinds
151/// such as `UnusedMethod` and `UnusedProperty` that require it.
152pub fn run_fixture_dead_code(path: &str) {
153    run_fixture_with_opts(path, true);
154}
155
156fn run_fixture_with_opts(path: &str, find_dead_code: bool) {
157    let content = std::fs::read_to_string(path)
158        .unwrap_or_else(|e| panic!("failed to read fixture {}: {}", path, e));
159
160    if std::env::var("UPDATE_FIXTURES").as_deref() == Ok("1") {
161        let source = parse_phpt_source_only(&content, path);
162        let actual = check_with_opts(&source, find_dead_code);
163        rewrite_fixture(path, &content, &actual);
164        return;
165    }
166
167    let (source, expected) = parse_phpt(&content, path);
168    let actual = check_with_opts(&source, find_dead_code);
169
170    let mut failures: Vec<String> = Vec::new();
171
172    for exp in &expected {
173        let found = actual
174            .iter()
175            .any(|a| a.kind.name() == exp.kind_name && a.kind.message() == exp.message.as_str());
176        if !found {
177            failures.push(format!("  MISSING  {}: {}", exp.kind_name, exp.message));
178        }
179    }
180
181    for act in &actual {
182        let expected_it = expected
183            .iter()
184            .any(|e| e.kind_name == act.kind.name() && e.message == act.kind.message());
185        if !expected_it {
186            failures.push(format!(
187                "  UNEXPECTED {}: {}",
188                act.kind.name(),
189                act.kind.message(),
190            ));
191        }
192    }
193
194    if !failures.is_empty() {
195        panic!(
196            "fixture {} FAILED:\n{}\n\nAll actual issues:\n{}",
197            path,
198            failures.join("\n"),
199            fmt_issues(&actual)
200        );
201    }
202}
203
204/// Rewrite the fixture file's `===expect===` section with the actual issues.
205/// Preserves the `===source===` section unchanged.
206fn rewrite_fixture(path: &str, content: &str, actual: &[Issue]) {
207    let source_marker = "===source===";
208    let expect_marker = "===expect===";
209
210    let source_pos = content.find(source_marker).expect("missing ===source===");
211    let expect_pos = content.find(expect_marker).expect("missing ===expect===");
212
213    let source_section = &content[source_pos..expect_pos];
214
215    let mut new_content = String::new();
216    new_content.push_str(source_section);
217    new_content.push_str(expect_marker);
218    new_content.push('\n');
219
220    // Sort issues by (line, col, kind) for deterministic output.
221    let mut sorted: Vec<&Issue> = actual.iter().collect();
222    sorted.sort_by_key(|i| (i.location.line, i.location.col_start, i.kind.name()));
223
224    for issue in sorted {
225        new_content.push_str(&format!(
226            "{}: {}\n",
227            issue.kind.name(),
228            issue.kind.message()
229        ));
230    }
231
232    std::fs::write(path, &new_content)
233        .unwrap_or_else(|e| panic!("failed to write fixture {}: {}", path, e));
234}
235
236// ---------------------------------------------------------------------------
237// Assertion helpers (used by inline tests)
238// ---------------------------------------------------------------------------
239
240/// Assert that `issues` contains at least one issue with the exact `IssueKind`
241/// at `line` and `col_start`. Panics with the full issue list on failure.
242pub fn assert_issue(issues: &[Issue], kind: IssueKind, line: u32, col_start: u16) {
243    let found = issues
244        .iter()
245        .any(|i| i.kind == kind && i.location.line == line && i.location.col_start == col_start);
246    if !found {
247        panic!(
248            "Expected issue {:?} at line {}, col {}.\nActual issues:\n{}",
249            kind,
250            line,
251            col_start,
252            fmt_issues(issues),
253        );
254    }
255}
256
257/// Assert that `issues` contains at least one issue whose `kind.name()` equals
258/// `kind_name`, at `line` and `col_start`. Use this when the exact IssueKind
259/// field values are complex (e.g. type-format strings in InvalidArgument).
260pub fn assert_issue_kind(issues: &[Issue], kind_name: &str, line: u32, col_start: u16) {
261    let found = issues.iter().any(|i| {
262        i.kind.name() == kind_name && i.location.line == line && i.location.col_start == col_start
263    });
264    if !found {
265        panic!(
266            "Expected issue {} at line {}, col {}.\nActual issues:\n{}",
267            kind_name,
268            line,
269            col_start,
270            fmt_issues(issues),
271        );
272    }
273}
274
275/// Assert that `issues` contains no issue whose `kind.name()` equals `kind_name`.
276/// Panics with the matching issues on failure.
277pub fn assert_no_issue(issues: &[Issue], kind_name: &str) {
278    let found: Vec<_> = issues
279        .iter()
280        .filter(|i| i.kind.name() == kind_name)
281        .collect();
282    if !found.is_empty() {
283        panic!(
284            "Expected no {} issues, but found:\n{}",
285            kind_name,
286            fmt_issues(&found.into_iter().cloned().collect::<Vec<_>>()),
287        );
288    }
289}
290
291fn fmt_issues(issues: &[Issue]) -> String {
292    if issues.is_empty() {
293        return "  (none)".to_string();
294    }
295    issues
296        .iter()
297        .map(|i| format!("  {}: {}", i.kind.name(), i.kind.message()))
298        .collect::<Vec<_>>()
299        .join("\n")
300}