cargo-test-filter 0.1.0

A cargo subcommand for intelligent test filtering and compilation
Documentation
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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

/// Represents an individual test function with its metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestFunction {
    /// The name of the test function (e.g., "test_database_connection")
    pub name: String,
    /// The file containing this test
    pub file_path: PathBuf,
    /// The name of the test target (file stem for integration tests, "lib" for unit tests)
    pub target_name: String,
    /// The type of test (unit, integration, etc.)
    pub test_type: TestType,
    /// Tags associated with this specific test function
    pub tags: Vec<String>,
}

/// Legacy struct for file-level test targets (kept for compatibility)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestTarget {
    pub name: String,
    pub path: PathBuf,
    pub test_type: TestType,
    pub tags: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TestType {
    Unit,
    Integration,
    Doc,
}

pub struct TestDiscovery {
    project_root: PathBuf,
}

impl TestDiscovery {
    pub fn new(project_root: PathBuf) -> Self {
        Self { project_root }
    }

    /// Discover all individual test functions in the project
    pub fn discover_test_functions(&self) -> Result<Vec<TestFunction>> {
        let mut functions = Vec::new();

        // Discover integration test functions
        functions.extend(self.discover_integration_test_functions()?);

        // Discover unit test functions in src/
        functions.extend(self.discover_unit_test_functions()?);

        Ok(functions)
    }

    /// Legacy method: Discover test targets (file-level)
    pub fn discover_tests(&self) -> Result<Vec<TestTarget>> {
        let mut tests = Vec::new();

        // Discover integration tests
        tests.extend(self.discover_integration_tests()?);

        // Discover unit tests in src/
        tests.extend(self.discover_unit_tests()?);

        Ok(tests)
    }

    /// Discover integration test functions in tests/ directory
    fn discover_integration_test_functions(&self) -> Result<Vec<TestFunction>> {
        let tests_dir = self.project_root.join("tests");
        if !tests_dir.exists() {
            return Ok(Vec::new());
        }

        let mut functions = Vec::new();

        for entry in WalkDir::new(&tests_dir)
            .min_depth(1)
            .max_depth(3)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let path = entry.path();
            if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
                let target_name = path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("unknown")
                    .to_string();

                let file_functions = self.parse_test_functions(path, &target_name, TestType::Integration)?;
                functions.extend(file_functions);
            }
        }

        Ok(functions)
    }

    /// Discover unit test functions in src/ directory
    fn discover_unit_test_functions(&self) -> Result<Vec<TestFunction>> {
        let src_dir = self.project_root.join("src");
        if !src_dir.exists() {
            return Ok(Vec::new());
        }

        let mut functions = Vec::new();

        for entry in WalkDir::new(&src_dir)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let path = entry.path();
            if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
                let content = fs::read_to_string(path)
                    .with_context(|| format!("Failed to read {}", path.display()))?;

                if self.contains_tests(&content) {
                    let file_functions = self.parse_test_functions(path, "lib", TestType::Unit)?;
                    functions.extend(file_functions);
                }
            }
        }

        Ok(functions)
    }

    /// Parse a file to extract individual test functions with their tags
    fn parse_test_functions(&self, path: &Path, target_name: &str, test_type: TestType) -> Result<Vec<TestFunction>> {
        let content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read {}", path.display()))?;

        let mut functions = Vec::new();
        let lines: Vec<&str> = content.lines().collect();
        let mut i = 0;

        while i < lines.len() {
            let line = lines[i].trim();

            // Look for #[test] or #[tokio::test] or similar test attributes
            if self.is_test_attribute(line) {
                // Collect tags from preceding lines
                let tags = self.collect_preceding_tags(&lines, i);

                // Find the function name from the next lines
                let func_name = self.find_function_name(&lines, i + 1);

                if let Some(name) = func_name {
                    functions.push(TestFunction {
                        name,
                        file_path: path.to_path_buf(),
                        target_name: target_name.to_string(),
                        test_type: test_type.clone(),
                        tags,
                    });
                }
            }

            i += 1;
        }

        Ok(functions)
    }

    /// Check if a line is a test attribute
    fn is_test_attribute(&self, line: &str) -> bool {
        let line = line.trim();
        // Match various test attributes
        line == "#[test]"
            || line.starts_with("#[test(")
            || line.starts_with("#[tokio::test")
            || line.starts_with("#[async_std::test")
            || line.starts_with("#[rstest")
            || line.starts_with("#[test_case")
    }

    /// Collect tags from lines preceding a test attribute
    fn collect_preceding_tags(&self, lines: &[&str], test_line_idx: usize) -> Vec<String> {
        let mut tags = Vec::new();

        // Look backwards from the test attribute for tag comments
        let mut j = test_line_idx;
        while j > 0 {
            j -= 1;
            let line = lines[j].trim();

            // Stop if we hit an empty line or something that's not a comment/attribute
            if line.is_empty() {
                break;
            }

            // Parse tag from comment or attribute
            if let Some(tag) = self.parse_tag_line(line) {
                tags.push(tag);
            } else if !line.starts_with("//") && !line.starts_with("#[") {
                // Hit non-comment, non-attribute line - stop looking
                break;
            }
        }

        tags
    }

    /// Parse a tag from a line (supports multiple formats)
    fn parse_tag_line(&self, line: &str) -> Option<String> {
        let line = line.trim();

        // Support comment-based tags: // @tag: tagname or //@tag: tagname
        if line.starts_with("// @tag:") || line.starts_with("//@tag:") {
            let parts: Vec<&str> = line.splitn(2, ':').collect();
            if parts.len() >= 2 {
                return Some(parts[1].trim().to_string());
            }
        }

        // Support attribute-based tags: #[test_tag("tagname")]
        if line.starts_with("#[test_tag(") && line.ends_with(")]") {
            let start = line.find('"')?;
            let end = line.rfind('"')?;
            if start < end {
                return Some(line[start + 1..end].to_string());
            }
        }

        None
    }

    /// Find the function name after a test attribute
    fn find_function_name(&self, lines: &[&str], start_idx: usize) -> Option<String> {
        for line in lines.iter().skip(start_idx).take(5) {
            let line = line.trim();

            // Skip additional attributes
            if line.starts_with("#[") {
                continue;
            }

            // Look for function definition
            if line.starts_with("fn ") || line.starts_with("pub fn ") || line.starts_with("async fn ") || line.starts_with("pub async fn ") {
                // Extract function name
                let without_prefix = line
                    .trim_start_matches("pub ")
                    .trim_start_matches("async ")
                    .trim_start_matches("fn ");

                // Get the function name (everything before '(' or '<')
                let name_end = without_prefix.find(['(', '<', ' ']).unwrap_or(without_prefix.len());
                let name = without_prefix[..name_end].trim().to_string();

                if !name.is_empty() {
                    return Some(name);
                }
            }
        }

        None
    }

    /// Legacy: Discover integration tests in tests/ directory (file-level)
    fn discover_integration_tests(&self) -> Result<Vec<TestTarget>> {
        let tests_dir = self.project_root.join("tests");
        if !tests_dir.exists() {
            return Ok(Vec::new());
        }

        let mut targets = Vec::new();

        for entry in WalkDir::new(&tests_dir)
            .min_depth(1)
            .max_depth(3)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let path = entry.path();
            if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
                let tags = self.extract_file_tags(path)?;
                let name = path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("unknown")
                    .to_string();

                targets.push(TestTarget {
                    name,
                    path: path.to_path_buf(),
                    test_type: TestType::Integration,
                    tags,
                });
            }
        }

        Ok(targets)
    }

    /// Legacy: Discover unit tests in src/ directory (file-level)
    fn discover_unit_tests(&self) -> Result<Vec<TestTarget>> {
        let src_dir = self.project_root.join("src");
        if !src_dir.exists() {
            return Ok(Vec::new());
        }

        let mut targets = Vec::new();

        for entry in WalkDir::new(&src_dir)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let path = entry.path();
            if path.is_file() && path.extension().is_some_and(|e| e == "rs") {
                let content = fs::read_to_string(path)
                    .with_context(|| format!("Failed to read {}", path.display()))?;

                if self.contains_tests(&content) {
                    let tags = self.extract_file_tags(path)?;
                    let name = path
                        .file_stem()
                        .and_then(|s| s.to_str())
                        .unwrap_or("unknown")
                        .to_string();

                    targets.push(TestTarget {
                        name,
                        path: path.to_path_buf(),
                        test_type: TestType::Unit,
                        tags,
                    });
                }
            }
        }

        Ok(targets)
    }

    /// Check if a file contains test functions
    fn contains_tests(&self, content: &str) -> bool {
        content.contains("#[test]") || content.contains("#[cfg(test)]")
    }

    /// Extract all tags from a file (for legacy file-level support)
    fn extract_file_tags(&self, path: &Path) -> Result<Vec<String>> {
        let content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read {}", path.display()))?;

        let mut tags = Vec::new();

        for line in content.lines() {
            if let Some(tag) = self.parse_tag_line(line) {
                if !tags.contains(&tag) {
                    tags.push(tag);
                }
            }
        }

        Ok(tags)
    }

    /// Get the project root by looking for Cargo.toml
    pub fn find_project_root() -> Result<PathBuf> {
        let current_dir = std::env::current_dir()
            .context("Failed to get current directory")?;

        let mut dir = current_dir.as_path();
        loop {
            if dir.join("Cargo.toml").exists() {
                return Ok(dir.to_path_buf());
            }
            dir = dir.parent().context("Failed to find Cargo.toml in parent directories")?;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_test_attribute() {
        let discovery = TestDiscovery::new(PathBuf::from("."));

        assert!(discovery.is_test_attribute("#[test]"));
        assert!(discovery.is_test_attribute("#[tokio::test]"));
        assert!(discovery.is_test_attribute("#[async_std::test]"));
        assert!(!discovery.is_test_attribute("fn test_something()"));
        assert!(!discovery.is_test_attribute("// #[test]"));
    }

    #[test]
    fn test_parse_tag_line() {
        let discovery = TestDiscovery::new(PathBuf::from("."));

        assert_eq!(discovery.parse_tag_line("// @tag: fast"), Some("fast".to_string()));
        assert_eq!(discovery.parse_tag_line("//@tag: slow"), Some("slow".to_string()));
        assert_eq!(discovery.parse_tag_line("#[test_tag(\"database\")]"), Some("database".to_string()));
        assert_eq!(discovery.parse_tag_line("fn test()"), None);
    }

    #[test]
    fn test_find_function_name() {
        let discovery = TestDiscovery::new(PathBuf::from("."));

        let lines = vec![
            "fn test_something() {",
            "    assert!(true);",
            "}",
        ];
        assert_eq!(discovery.find_function_name(&lines, 0), Some("test_something".to_string()));

        let lines2 = vec![
            "pub fn test_public() {",
        ];
        assert_eq!(discovery.find_function_name(&lines2, 0), Some("test_public".to_string()));

        let lines3 = vec![
            "async fn test_async() {",
        ];
        assert_eq!(discovery.find_function_name(&lines3, 0), Some("test_async".to_string()));
    }
}