Skip to main content

gdtest_analysis/
lib.rs

1//! Discovery helpers for gdtest.
2//!
3//! Two layers:
4//! 1. [`resolve`] turns user-supplied paths (files, directories, `res://…`)
5//!    into a flat list of `res://…` paths, filtered by discovery include/exclude globs.
6//! 2. [`list_tests_in`] parses one GDScript file with gdsyntax
7//!    and returns every `func test_*()` name in source order.
8//!
9//! Default patterns:
10//!   - `test/**/*.gd`  — any `.gd` file inside a `test/` directory tree
11//!   - `**/*.test.gd`  — co-located test files anywhere in the project
12//!
13//! Users can override via `gdtest.toml`:  `include = ["test/**/*.gd", "**/*.test.gd"]`
14//!
15//! When walking a folder, hidden folders (`.godot`, `.git`…), `addons`,
16//! folders with a `.gdignore`, and nested Godot projects are skipped, as the
17//! Godot editor does, so an addon's own tests never run as the project's.
18//! A folder or file named directly is always used.
19//!
20//! Target: discovering 500 tests across 50 files in <100 ms on a warm cache
21//!.
22
23/// Default discovery globs used when no `include` key is in `gdtest.toml`.
24pub const DEFAULT_PATTERNS: &[&str] = &["test/**/*.gd", "**/*.test.gd"];
25
26pub mod coverage;
27pub mod deps;
28pub mod gdunit4_migrate;
29pub mod gut_migrate;
30pub mod mutate;
31pub mod rewrite;
32pub use gdunit4_migrate::{
33    GdUnit4MigrationAction, GdUnit4MigrationIssue, GdUnit4MigrationOutput, GdUnit4MigrationStatus,
34    is_gdunit4_test_file, is_gdunit4_test_source, migrate_gdunit4_file, migrate_gdunit4_source,
35};
36pub use gut_migrate::{
37    GutMigrationAction, GutMigrationIssue, GutMigrationOutput, GutMigrationStatus,
38    is_gut_test_file, is_gut_test_source, migrate_gut_file, migrate_gut_source,
39};
40pub use rewrite::{RewriteOutput, rewrite_file, rewrite_source};
41
42use std::path::{Path, PathBuf};
43
44use anyhow::{Context, Result, anyhow};
45use gdsyntax::ast::{AstNode, Member};
46use walkdir::WalkDir;
47
48/// Normalise every input path into a list of `res://…` test-file paths.
49///
50/// `patterns` is a slice of glob strings (relative to project root) used when
51/// walking directories. `exclude_patterns` is a slice of discovery-exclude
52/// globs, also relative to project root. Pass [`DEFAULT_PATTERNS`] and `[]`
53/// when no custom config is set.
54pub fn resolve(
55    inputs: &[String],
56    project_path: &Path,
57    patterns: &[String],
58    exclude_patterns: &[String],
59) -> Result<Vec<String>> {
60    let project_abs = project_path
61        .canonicalize()
62        .with_context(|| format!("project path does not exist: {}", project_path.display()))?;
63    let mut out: Vec<String> = Vec::new();
64    for input in inputs {
65        let path = match input.strip_prefix("res://") {
66            // A folder is walked like any other; a file is kept as given.
67            Some(res) if project_abs.join(res).is_dir() => PathBuf::from(res),
68            Some(res) => {
69                out.push(format!("res://{res}"));
70                continue;
71            }
72            None => PathBuf::from(input),
73        };
74        let abs = if path.is_absolute() {
75            path.clone()
76        } else {
77            project_abs.join(&path)
78        };
79        // Canonicalize so the \\?\ UNC prefix (Windows) matches project_abs.
80        let abs = abs.canonicalize().unwrap_or(abs);
81        if abs.is_file() {
82            if abs.extension().and_then(|e| e.to_str()) != Some("gd") {
83                return Err(anyhow!("not a .gd file: {}", abs.display()));
84            }
85            out.push(to_res_path(&abs, &project_abs)?);
86        } else if abs.is_dir() {
87            let walker = WalkDir::new(&abs)
88                .follow_links(false)
89                .into_iter()
90                .filter_entry(|entry| entry.depth() == 0 || !is_skipped_dir(entry));
91            for entry in walker {
92                let entry = entry.with_context(|| format!("walking {}", abs.display()))?;
93                if !entry.file_type().is_file() {
94                    continue;
95                }
96                if entry.path().extension().and_then(|e| e.to_str()) != Some("gd") {
97                    continue;
98                }
99                let ep = entry
100                    .path()
101                    .canonicalize()
102                    .unwrap_or_else(|_| entry.path().to_path_buf());
103                // Match against project-root-relative path with forward slashes.
104                let rel = ep.strip_prefix(&project_abs).unwrap_or(&ep);
105                let rel_str = rel.to_string_lossy().replace('\\', "/");
106                if !patterns.iter().any(|p| glob_match(p, &rel_str)) {
107                    continue;
108                }
109                if exclude_patterns.iter().any(|p| glob_match(p, &rel_str)) {
110                    continue;
111                }
112                out.push(to_res_path(&ep, &project_abs)?);
113            }
114        } else {
115            return Err(anyhow!("path not found: {}", abs.display()));
116        }
117    }
118    out.sort();
119    out.dedup();
120    Ok(out)
121}
122
123/// Folders a walk skips, as the Godot editor does: hidden ones, `addons`,
124/// those with a `.gdignore`, and nested Godot projects.
125fn is_skipped_dir(entry: &walkdir::DirEntry) -> bool {
126    if !entry.file_type().is_dir() {
127        return false;
128    }
129    let name = entry.file_name().to_string_lossy();
130    name.starts_with('.')
131        || name == "addons"
132        || entry.path().join(".gdignore").exists()
133        || entry.path().join("project.godot").exists()
134}
135
136/// Match a relative path (forward-slash separated) against a simple glob pattern.
137/// Supports `**` (zero or more path segments) and `*` (any chars within one segment).
138pub fn glob_match(pattern: &str, path: &str) -> bool {
139    let pat: Vec<&str> = pattern.split('/').collect();
140    let seg: Vec<&str> = path.split('/').collect();
141    glob_seg(&pat, &seg)
142}
143
144fn glob_seg(pat: &[&str], seg: &[&str]) -> bool {
145    if pat.is_empty() {
146        return seg.is_empty();
147    }
148    if pat[0] == "**" {
149        for i in 0..=seg.len() {
150            if glob_seg(&pat[1..], &seg[i..]) {
151                return true;
152            }
153        }
154        return false;
155    }
156    if seg.is_empty() {
157        return false;
158    }
159    if seg_matches(pat[0], seg[0]) {
160        return glob_seg(&pat[1..], &seg[1..]);
161    }
162    false
163}
164
165/// Match a single path segment against a pattern that may contain `*` wildcards.
166fn seg_matches(pattern: &str, s: &str) -> bool {
167    if !pattern.contains('*') {
168        return pattern == s;
169    }
170    let parts: Vec<&str> = pattern.split('*').collect();
171    let mut pos = 0usize;
172    for (i, part) in parts.iter().enumerate() {
173        if i == 0 {
174            if !s.starts_with(part) {
175                return false;
176            }
177            pos += part.len();
178        } else if i == parts.len() - 1 {
179            return s[pos..].ends_with(part);
180        } else {
181            match s[pos..].find(part) {
182                None => return false,
183                Some(idx) => pos += idx + part.len(),
184            }
185        }
186    }
187    true
188}
189
190/// If `path` contains a component named `describe_<Name>`, return that component name.
191/// Used to prefix test function names for directory-based sub-suites.
192pub fn extract_describe_dir(path: &Path) -> Option<String> {
193    path.components()
194        .filter_map(|c| match c {
195            std::path::Component::Normal(s) => s.to_str(),
196            _ => None,
197        })
198        .rfind(|s| s.starts_with("describe_"))
199        .map(|s| s.to_string())
200}
201
202/// Classification of a discovered test function.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub enum TestKind {
205    /// `test_*` — runs normally.
206    Normal,
207    /// `bench_*` — benchmark; only runs when `--bench` is passed.
208    Bench,
209}
210
211/// Per-test isolation override discovered from source comments.
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub enum IsolationDirective {
214    File,
215    Test,
216}
217
218/// A discovered test function with its run classification.
219#[derive(Debug, Clone)]
220pub struct TestEntry {
221    pub name: String,
222    pub kind: TestKind,
223    /// Tags collected from `## @tag <name>` doc comments immediately preceding the function.
224    pub tags: Vec<String>,
225    /// Isolation override from source comments.
226    pub isolation: Option<IsolationDirective>,
227}
228
229/// Return every `func test_*()` and `func bench_*()` in the given GDScript file, in source order.
230///
231/// If the file lives inside a `describe_<Name>/` directory, all returned
232/// entry names are prefixed with `describe_<Name>/` to match the reporting
233/// format of inner-class describe blocks.
234pub fn list_test_entries_in(script_path: &Path) -> Result<Vec<TestEntry>> {
235    let source =
236        std::fs::read(script_path).with_context(|| format!("reading {}", script_path.display()))?;
237    let mut entries = list_test_entries_in_source(&source)?;
238    if let Some(prefix) = extract_describe_dir(script_path) {
239        for entry in &mut entries {
240            entry.name = format!("{prefix}/{}", entry.name);
241        }
242    }
243    Ok(entries)
244}
245
246pub fn list_test_entries_in_source(source: &[u8]) -> Result<Vec<TestEntry>> {
247    // Discovery works on lines, which invalid UTF-8 replaced by gdsyntax
248    // cannot move.
249    let tree = gdsyntax::parse_bytes(source);
250    let file_isolation = extract_file_isolation(source);
251    let mut out = Vec::new();
252    collect_test_entries(
253        &tree,
254        tree.file().members(),
255        source,
256        None,
257        file_isolation,
258        &mut out,
259    );
260    Ok(out)
261}
262
263/// Parse a `## @tag <name>` doc comment. Returns the tag name or `None`.
264fn parse_tag_comment(text: &str) -> Option<String> {
265    let body = text.trim().strip_prefix("##")?.trim_start();
266    let name = body.strip_prefix("@tag")?.trim();
267    if name.is_empty() || name.contains(char::is_whitespace) {
268        return None;
269    }
270    Some(name.to_string())
271}
272
273fn parse_isolation_comment(text: &str) -> Option<IsolationDirective> {
274    let trimmed = text.trim();
275    let doc_body = trimmed.strip_prefix("##").map(str::trim_start);
276    let plain_body = trimmed.strip_prefix('#').map(str::trim_start);
277
278    if let Some(body) = doc_body
279        && let Some(value) = body.strip_prefix("@isolation").map(str::trim)
280    {
281        return match value {
282            "file" => Some(IsolationDirective::File),
283            "test" => Some(IsolationDirective::Test),
284            _ => None,
285        };
286    }
287
288    if let Some(body) = plain_body
289        && let Some(value) = body
290            .strip_prefix("gdtest:")
291            .map(str::trim_start)
292            .and_then(|rest| rest.strip_prefix("isolation="))
293            .map(str::trim)
294    {
295        return match value {
296            "file" => Some(IsolationDirective::File),
297            "test" => Some(IsolationDirective::Test),
298            _ => None,
299        };
300    }
301
302    None
303}
304
305/// Scan source lines immediately before `func_row` and collect `## @tag` names.
306/// Stops at a blank line or any line that is neither a `## @tag` nor a plain `#` comment.
307fn extract_tags_preceding(source: &[u8], func_row: usize) -> Vec<String> {
308    let lines: Vec<&[u8]> = source.split(|&b| b == b'\n').collect();
309    let mut tags = Vec::new();
310    let mut row = func_row;
311    while row > 0 {
312        row -= 1;
313        let line = std::str::from_utf8(lines[row]).unwrap_or("").trim();
314        if line.is_empty() {
315            break;
316        }
317        if let Some(tag) = parse_tag_comment(line) {
318            tags.push(tag);
319        } else if line.starts_with('#') {
320            // plain comment — keep scanning upward
321        } else {
322            break;
323        }
324    }
325    tags.reverse();
326    tags
327}
328
329fn extract_isolation_preceding(source: &[u8], func_row: usize) -> Option<IsolationDirective> {
330    let lines: Vec<&[u8]> = source.split(|&b| b == b'\n').collect();
331    let mut row = func_row;
332    while row > 0 {
333        row -= 1;
334        let line = std::str::from_utf8(lines[row]).unwrap_or("").trim();
335        if line.is_empty() {
336            break;
337        }
338        if let Some(isolation) = parse_isolation_comment(line) {
339            return Some(isolation);
340        }
341        if line.starts_with('#') {
342            continue;
343        }
344        break;
345    }
346    None
347}
348
349fn extract_file_isolation(source: &[u8]) -> Option<IsolationDirective> {
350    for raw_line in source.split(|&b| b == b'\n') {
351        let line = std::str::from_utf8(raw_line).unwrap_or("").trim();
352        if line.is_empty() {
353            continue;
354        }
355        if let Some(isolation) = parse_isolation_comment(line) {
356            return Some(isolation);
357        }
358        if line.starts_with('#') {
359            continue;
360        }
361        break;
362    }
363    None
364}
365
366/// Classify a function name into its TestKind, or `None` if it's not a test.
367fn classify_func(name: &str) -> Option<TestKind> {
368    if name.starts_with("bench_") {
369        Some(TestKind::Bench)
370    } else if name.starts_with("test_") {
371        Some(TestKind::Normal)
372    } else {
373        None
374    }
375}
376
377/// Collect test entries from the members of a file or of a `describe_*` class.
378/// `describe` is the name of the enclosing `describe_*` inner class, if any.
379fn collect_test_entries(
380    tree: &gdsyntax::SyntaxTree,
381    members: impl Iterator<Item = Member>,
382    source: &[u8],
383    describe: Option<&str>,
384    file_isolation: Option<IsolationDirective>,
385    out: &mut Vec<TestEntry>,
386) {
387    for member in members {
388        match member {
389            Member::Func(func) => {
390                let Some(name_token) = func.name() else {
391                    continue;
392                };
393                let fname = name_token.text();
394                let Some(kind) = classify_func(fname) else {
395                    continue;
396                };
397                let name = match describe {
398                    Some(cls) => format!("{cls}/{fname}"),
399                    None => fname.to_string(),
400                };
401                // The node starts at the function's first annotation, so tags
402                // and directives are read from the lines above it.
403                let row = tree
404                    .position(func.syntax().text_range().start().into())
405                    .line
406                    - 1;
407                let tags = extract_tags_preceding(source, row);
408                let isolation = extract_isolation_preceding(source, row).or(file_isolation);
409                out.push(TestEntry {
410                    name,
411                    kind,
412                    tags,
413                    isolation,
414                });
415            }
416            // Only top-level `describe_*` inner classes hold tests; the worker
417            // instantiates them by name, so classes nested deeper are skipped.
418            Member::Class(class) if describe.is_none() => {
419                if let Some(name_token) = class.name()
420                    && name_token.text().starts_with("describe_")
421                {
422                    let members: Vec<Member> = class
423                        .body()
424                        .map(|body| body.members().collect())
425                        .unwrap_or_default();
426                    collect_test_entries(
427                        tree,
428                        members.into_iter(),
429                        source,
430                        Some(name_token.text()),
431                        file_isolation,
432                        out,
433                    );
434                }
435            }
436            _ => {}
437        }
438    }
439}
440
441/// Convenience wrapper: returns the names of tests that would actually run
442/// (excludes `bench_*`).
443pub fn list_tests_in(script_path: &Path) -> Result<Vec<String>> {
444    let entries = list_test_entries_in(script_path)?;
445    Ok(entries
446        .into_iter()
447        .filter(|e| e.kind == TestKind::Normal)
448        .map(|e| e.name)
449        .collect())
450}
451
452/// Translate an absolute on-disk path to the res:// form used by the
453/// worker. Caller guarantees `file` is inside `project_abs`.
454pub fn to_res_path(file: &Path, project_abs: &Path) -> Result<String> {
455    let rel = file.strip_prefix(project_abs).with_context(|| {
456        format!(
457            "{} is outside project {}",
458            file.display(),
459            project_abs.display()
460        )
461    })?;
462    let s = rel.to_string_lossy().replace('\\', "/");
463    Ok(format!("res://{s}"))
464}
465
466/// Translate a res:// path to its on-disk absolute form.
467pub fn res_to_abs(res_path: &str, project_abs: &Path) -> Result<PathBuf> {
468    let rel = res_path
469        .strip_prefix("res://")
470        .ok_or_else(|| anyhow!("expected res:// prefix: {res_path}"))?;
471    Ok(project_abs.join(rel))
472}
473
474#[cfg(test)]
475mod tests {
476    use super::*;
477    use std::fs;
478    use std::path::PathBuf;
479    use std::time::{SystemTime, UNIX_EPOCH};
480
481    fn make_temp_project(prefix: &str) -> PathBuf {
482        let nonce = SystemTime::now()
483            .duration_since(UNIX_EPOCH)
484            .unwrap()
485            .as_nanos();
486        let dir = std::env::temp_dir().join(format!("gdtest-{prefix}-{nonce}"));
487        fs::create_dir_all(&dir).unwrap();
488        dir
489    }
490
491    #[test]
492    fn extracts_test_functions() {
493        let src = br#"
494extends RefCounted
495
496func _helper() -> void:
497    pass
498
499func test_alpha() -> void:
500    pass
501
502func test_beta(arg: int) -> void:
503    # func test_inside_comment() should NOT be picked up
504    pass
505
506func not_a_test() -> void:
507    pass
508
509# Async test
510func test_gamma() -> void:
511    await physics_frame
512"#;
513        let entries = list_test_entries_in_source(src).unwrap();
514        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
515        assert_eq!(names, vec!["test_alpha", "test_beta", "test_gamma"]);
516        assert!(entries.iter().all(|e| e.kind == TestKind::Normal));
517    }
518
519    #[test]
520    fn unknown_prefixes_are_not_tests() {
521        let src = br#"
522func test_normal() -> void:
523    pass
524func xtest_skipped() -> void:
525    pass
526func ftest_focused() -> void:
527    pass
528func helper() -> void:
529    pass
530"#;
531        let entries = list_test_entries_in_source(src).unwrap();
532        // xtest_* and ftest_* are not recognized — only test_* is.
533        assert_eq!(entries.len(), 1);
534        assert_eq!(entries[0].name, "test_normal");
535        assert_eq!(entries[0].kind, TestKind::Normal);
536    }
537
538    #[test]
539    fn parses_tag_comments() {
540        let src = br#"
541extends GdTest
542
543## @tag slow
544## @tag integration
545func test_heavy() -> void:
546    pass
547
548## regular comment, not a tag
549func test_untagged() -> void:
550    pass
551
552func test_also_untagged() -> void:
553    pass
554"#;
555        let entries = list_test_entries_in_source(src).unwrap();
556        assert_eq!(entries.len(), 3);
557        assert_eq!(entries[0].name, "test_heavy");
558        assert_eq!(entries[0].tags, vec!["slow", "integration"]);
559        assert!(entries[1].tags.is_empty());
560        assert!(entries[2].tags.is_empty());
561    }
562
563    #[test]
564    fn parses_file_header_isolation_directive() {
565        let src = br#"
566# gdtest: isolation=test
567extends GdTest
568
569func test_one() -> void:
570    pass
571
572func test_two() -> void:
573    pass
574"#;
575        let entries = list_test_entries_in_source(src).unwrap();
576        assert_eq!(entries.len(), 2);
577        assert_eq!(entries[0].isolation, Some(IsolationDirective::Test));
578        assert_eq!(entries[1].isolation, Some(IsolationDirective::Test));
579    }
580
581    #[test]
582    fn function_isolation_overrides_file_header() {
583        let src = br#"
584## @isolation test
585extends GdTest
586
587## @isolation file
588func test_one() -> void:
589    pass
590
591func test_two() -> void:
592    pass
593"#;
594        let entries = list_test_entries_in_source(src).unwrap();
595        assert_eq!(entries.len(), 2);
596        assert_eq!(entries[0].isolation, Some(IsolationDirective::File));
597        assert_eq!(entries[1].isolation, Some(IsolationDirective::Test));
598    }
599
600    #[test]
601    fn classifies_bench_funcs() {
602        let src = br#"
603func test_normal() -> void:
604    pass
605func bench_pathfinding() -> void:
606    pass
607"#;
608        let entries = list_test_entries_in_source(src).unwrap();
609        assert_eq!(entries.len(), 2);
610        assert_eq!(entries[0].kind, TestKind::Normal);
611        assert_eq!(entries[1].kind, TestKind::Bench);
612        // bench_* excluded from list_tests_in
613        let runnable: Vec<String> = entries
614            .into_iter()
615            .filter(|e| e.kind == TestKind::Normal)
616            .map(|e| e.name)
617            .collect();
618        assert_eq!(runnable, vec!["test_normal"]);
619    }
620
621    #[test]
622    fn empty_on_parse_error_tolerates_partial() {
623        let src = br#"func test_recoverable(): pass
624!@#$%garbage that breaks parsing"#;
625        let _entries = list_test_entries_in_source(src).unwrap();
626    }
627
628    #[test]
629    fn discovers_describe_class_tests() {
630        let src = br#"
631extends GdTest
632
633func test_top_level() -> void:
634    pass
635
636class describe_Movement:
637    func test_moves_right() -> void:
638        pass
639    func test_moves_left() -> void:
640        pass
641    func helper_not_a_test() -> void:
642        pass
643
644class IgnoredClass:
645    func test_inside_ignored() -> void:
646        pass
647"#;
648        let entries = list_test_entries_in_source(src).unwrap();
649        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
650        assert_eq!(
651            names,
652            vec![
653                "test_top_level",
654                "describe_Movement/test_moves_right",
655                "describe_Movement/test_moves_left",
656            ]
657        );
658        assert!(entries.iter().all(|e| e.kind == TestKind::Normal));
659    }
660
661    #[test]
662    fn discovers_non_ascii_test_names() {
663        let src = "func test_日本語() -> void:\n\tpass\n".as_bytes();
664        let entries = list_test_entries_in_source(src).unwrap();
665        assert_eq!(entries[0].name, "test_日本語");
666    }
667
668    #[test]
669    fn reads_tags_above_annotations() {
670        let src = br#"
671## @tag slow
672@warning_ignore("unused_variable")
673func test_annotated() -> void:
674    var x := 1
675"#;
676        let entries = list_test_entries_in_source(src).unwrap();
677        assert_eq!(entries[0].tags, vec!["slow"]);
678    }
679
680    #[test]
681    fn finds_tests_after_a_syntax_error() {
682        let src = b"func broken(:\n\tpass\n\nfunc test_after() -> void:\n\tpass\n";
683        let entries = list_test_entries_in_source(src).unwrap();
684        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
685        assert_eq!(names, vec!["test_after"]);
686    }
687
688    #[test]
689    fn skips_classes_nested_in_describe_classes() {
690        let src = br#"
691class describe_Outer:
692    func test_outer() -> void:
693        pass
694    class describe_Inner:
695        func test_inner() -> void:
696            pass
697"#;
698        let entries = list_test_entries_in_source(src).unwrap();
699        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
700        assert_eq!(names, vec!["describe_Outer/test_outer"]);
701    }
702
703    // ── glob_match tests ──────────────────────────────────────────────────────
704
705    #[test]
706    fn glob_match_test_dir_pattern() {
707        assert!(glob_match("test/**/*.gd", "test/battle.gd"));
708        assert!(glob_match("test/**/*.gd", "test/docs/test_foo.gd"));
709        assert!(glob_match("test/**/*.gd", "test/docs/dungeon/battle.gd"));
710        assert!(!glob_match("test/**/*.gd", "src/battle.gd"));
711        assert!(!glob_match("test/**/*.gd", "test/battle.tscn"));
712    }
713
714    #[test]
715    fn glob_match_colocated_pattern() {
716        assert!(glob_match("**/*.test.gd", "battle.test.gd"));
717        assert!(glob_match("**/*.test.gd", "src/battle/battle.test.gd"));
718        assert!(glob_match("**/*.test.gd", "deep/nested/dir/foo.test.gd"));
719        assert!(!glob_match("**/*.test.gd", "test_battle.gd"));
720        assert!(!glob_match("**/*.test.gd", "battle.gd"));
721    }
722
723    #[test]
724    fn glob_match_star_prefix_legacy() {
725        // Backward-compat: users may set patterns = ["test/test_*.gd"]
726        assert!(glob_match("test/test_*.gd", "test/test_battle.gd"));
727        assert!(!glob_match("test/test_*.gd", "test/battle.gd"));
728    }
729
730    // ── extract_describe_dir tests ────────────────────────────────────────────
731
732    #[test]
733    fn extract_describe_dir_finds_prefix() {
734        use std::path::PathBuf;
735        let p = PathBuf::from("test/describe_Battle/basic_hit.gd");
736        assert_eq!(
737            extract_describe_dir(&p),
738            Some("describe_Battle".to_string())
739        );
740    }
741
742    #[test]
743    fn extract_describe_dir_none_for_normal() {
744        use std::path::PathBuf;
745        let p = PathBuf::from("test/docs/test_foo.gd");
746        assert_eq!(extract_describe_dir(&p), None);
747    }
748
749    #[test]
750    fn extract_describe_dir_returns_last() {
751        use std::path::PathBuf;
752        // Nested describe dirs: return innermost
753        let p = PathBuf::from("test/describe_Outer/describe_Inner/foo.gd");
754        assert_eq!(extract_describe_dir(&p), Some("describe_Inner".to_string()));
755    }
756
757    #[test]
758    fn resolve_excludes_discovery_globs_for_directory_walks() {
759        let project = make_temp_project("resolve-exclude-dir");
760        fs::create_dir_all(project.join("test/helpers")).unwrap();
761        fs::create_dir_all(project.join("test/cases")).unwrap();
762        fs::write(
763            project.join("test/helpers/helper.gd"),
764            "extends RefCounted\n",
765        )
766        .unwrap();
767        fs::write(
768            project.join("test/cases/test_ok.gd"),
769            "extends RefCounted\n",
770        )
771        .unwrap();
772
773        let inputs = vec!["test".to_string()];
774        let patterns = vec!["test/**/*.gd".to_string()];
775        let excludes = vec!["test/helpers/**".to_string()];
776        let resolved = resolve(&inputs, &project, &patterns, &excludes).unwrap();
777
778        assert_eq!(resolved, vec!["res://test/cases/test_ok.gd"]);
779
780        fs::remove_dir_all(project).ok();
781    }
782
783    #[test]
784    fn resolve_walks_res_folders_like_relative_ones() {
785        let project = make_temp_project("resolve-res-dir");
786        fs::create_dir_all(project.join("test/cases")).unwrap();
787        fs::write(
788            project.join("test/cases/test_ok.gd"),
789            "extends RefCounted
790",
791        )
792        .unwrap();
793        let patterns = vec!["test/**/*.gd".to_string()];
794
795        for input in ["res://test/", "res://test", "res://test/cases/test_ok.gd"] {
796            let resolved = resolve(&[input.to_string()], &project, &patterns, &[]).unwrap();
797            assert_eq!(resolved, vec!["res://test/cases/test_ok.gd"], "{input}");
798        }
799
800        fs::remove_dir_all(project).ok();
801    }
802
803    #[test]
804    fn resolve_keeps_explicit_file_targets_even_if_excluded() {
805        let project = make_temp_project("resolve-explicit-file");
806        fs::create_dir_all(project.join("test/helpers")).unwrap();
807        let helper = project.join("test/helpers/helper.gd");
808        fs::write(&helper, "extends RefCounted\n").unwrap();
809
810        let inputs = vec![helper.to_string_lossy().into_owned()];
811        let patterns = vec!["test/**/*.gd".to_string()];
812        let excludes = vec!["test/helpers/**".to_string()];
813        let resolved = resolve(&inputs, &project, &patterns, &excludes).unwrap();
814
815        assert_eq!(resolved, vec!["res://test/helpers/helper.gd"]);
816
817        fs::remove_dir_all(project).ok();
818    }
819
820    #[test]
821    fn walking_skips_addons_hidden_ignored_and_nested_projects() {
822        let project = make_temp_project("resolve-skips");
823        for (path, content) in [
824            ("test/test_ok.gd", ""),
825            ("feature/thing.test.gd", ""),
826            ("addons/plugin/plugin.test.gd", ""),
827            ("addons/plugin/test/test_plugin.gd", ""),
828            (".godot/cache/old.test.gd", ""),
829            ("generated/.gdignore", ""),
830            ("generated/gen.test.gd", ""),
831            ("server/project.godot", ""),
832            ("server/net.test.gd", ""),
833        ] {
834            let path = project.join(path);
835            fs::create_dir_all(path.parent().unwrap()).unwrap();
836            fs::write(path, content).unwrap();
837        }
838        let patterns: Vec<String> = DEFAULT_PATTERNS.iter().map(|p| p.to_string()).collect();
839
840        let resolved = resolve(&[".".to_string()], &project, &patterns, &[]).unwrap();
841        assert_eq!(
842            resolved,
843            vec!["res://feature/thing.test.gd", "res://test/test_ok.gd"]
844        );
845
846        // A skipped folder named directly is walked.
847        let resolved = resolve(&["addons/plugin".to_string()], &project, &patterns, &[]).unwrap();
848        assert_eq!(resolved, vec!["res://addons/plugin/plugin.test.gd"]);
849
850        fs::remove_dir_all(project).ok();
851    }
852}