Skip to main content

oak_testing/
building.rs

1//! Builder testing utilities for the Oak ecosystem.
2//!
3//! This module provides comprehensive testing infrastructure for builders,
4//! including file-based testing, expected output comparison, timeout handling,
5//! and test result serialization for typed root structures.
6
7use crate::{create_file, json_from_path, source_from_path};
8use oak_core::{Builder, Language, errors::OakError};
9use serde::{Deserialize, Serialize};
10use serde_json::Value as JsonValue;
11
12use std::{
13    fmt::Debug,
14    path::{Path, PathBuf},
15    time::Duration,
16};
17use walkdir::WalkDir;
18
19/// A concurrent builder testing utility that can run tests against multiple files with timeout support.
20///
21/// The `BuilderTester` provides functionality to test builders against a directory
22/// of files with specific extensions, comparing actual output against expected
23/// results stored in JSON files, with configurable timeout protection.
24pub struct BuilderTester {
25    root: PathBuf,
26    extensions: Vec<String>,
27    timeout: Duration,
28}
29
30/// Expected builder test results for comparison.
31///
32/// This struct represents the expected output of a builder test, including
33/// success status, typed root structure, and any expected errors.
34#[derive(Debug, Serialize, Deserialize, PartialEq)]
35pub struct BuilderTestExpected {
36    pub success: bool,
37    pub typed_root: Option<TypedRootData>,
38    pub errors: Vec<String>,
39}
40
41/// Typed root data structure for builder testing.
42///
43/// Represents the typed root structure with its type name and serialized content
44/// used for testing builder output. Since TypedRoot can be any type, we serialize
45/// it as a generic structure for comparison.
46#[derive(Debug, Serialize, Deserialize, PartialEq)]
47pub struct TypedRootData {
48    pub type_name: String,
49    pub content: JsonValue,
50}
51
52impl BuilderTester {
53    /// Creates a new builder tester with the specified root directory and default 10-second timeout.
54    pub fn new<P: AsRef<Path>>(root: P) -> Self {
55        Self { root: root.as_ref().to_path_buf(), extensions: vec![], timeout: Duration::from_secs(10) }
56    }
57
58    /// Adds a file extension to test against.
59    pub fn with_extension(mut self, extension: impl ToString) -> Self {
60        self.extensions.push(extension.to_string());
61        self
62    }
63
64    /// Sets the timeout for building operations.
65    pub fn with_timeout(mut self, timeout: Duration) -> Self {
66        self.timeout = timeout;
67        self
68    }
69
70    /// Run tests for the given builder against all files in the root directory with the specified extensions.
71    pub fn run_tests<L, B>(self, builder: &B) -> Result<(), OakError>
72    where
73        B: Builder<L> + Send + Sync,
74        L: Language + Send + Sync + 'static,
75        L::TypedRoot: Serialize + Debug + Sync + Send,
76    {
77        let test_files = self.find_test_files()?;
78        let force_regenerated = std::env::var("REGENERATE_TESTS").unwrap_or("0".to_string()) == "1";
79        let mut regenerated_any = false;
80
81        for file_path in test_files {
82            println!("Testing file: {}", file_path.display());
83            regenerated_any |= self.test_single_file::<L, B>(&file_path, builder, force_regenerated)?;
84        }
85
86        if regenerated_any && force_regenerated { Err(OakError::test_regenerated(self.root)) } else { Ok(()) }
87    }
88
89    fn find_test_files(&self) -> Result<Vec<PathBuf>, OakError> {
90        let mut files = Vec::new();
91
92        for entry in WalkDir::new(&self.root) {
93            let entry = entry.unwrap();
94            let path = entry.path();
95
96            if path.is_file() {
97                if let Some(ext) = path.extension() {
98                    let ext_str = ext.to_str().unwrap_or("");
99                    if self.extensions.iter().any(|e| e == ext_str) {
100                        // 忽略由 Tester 自身生成的输出文件,防止递归包含
101                        let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
102                        let is_output_file = file_name.ends_with(".parsed.json") || file_name.ends_with(".lexed.json") || file_name.ends_with(".built.json") || file_name.ends_with(".expected.json");
103
104                        if !is_output_file {
105                            files.push(path.to_path_buf());
106                        }
107                    }
108                }
109            }
110        }
111
112        Ok(files)
113    }
114
115    fn test_single_file<L, B>(&self, file_path: &Path, builder: &B, force_regenerated: bool) -> Result<bool, OakError>
116    where
117        B: Builder<L> + Send + Sync,
118        L: Language + Send + Sync + 'static,
119        L::TypedRoot: Serialize + Debug + Sync + Send,
120    {
121        let source = source_from_path(file_path)?;
122
123        // Perform build in a thread and construct test results, with main thread handling timeout control
124        use std::sync::mpsc;
125        let (tx, rx) = mpsc::channel();
126        let timeout = self.timeout;
127        let file_path_string = file_path.display().to_string();
128
129        std::thread::scope(|s| {
130            s.spawn(move || {
131                let mut cache = oak_core::parser::ParseSession::<L>::new(1024);
132                let build_out = builder.build(&source, &[], &mut cache);
133
134                // Build typed root structure if build succeeded
135                let (success, typed_root) = match &build_out.result {
136                    Ok(root) => {
137                        // Serialize the typed root to JSON for comparison
138                        match serde_json::to_value(root) {
139                            Ok(content) => {
140                                let typed_root_data = TypedRootData { type_name: std::any::type_name::<L::TypedRoot>().to_string(), content };
141                                (true, Some(typed_root_data))
142                            }
143                            Err(_) => {
144                                // If serialization fails, still mark as success but with no typed root data
145                                (true, None)
146                            }
147                        }
148                    }
149                    Err(_) => (false, None),
150                };
151
152                // Collect error messages
153                let mut error_messages: Vec<String> = build_out.diagnostics.iter().map(|e| e.to_string()).collect();
154                if let Err(e) = &build_out.result {
155                    error_messages.push(e.to_string());
156                }
157
158                let test_result = BuilderTestExpected { success, typed_root, errors: error_messages };
159
160                let _ = tx.send(Ok::<BuilderTestExpected, OakError>(test_result));
161            });
162
163            let mut regenerated = false;
164            match rx.recv_timeout(timeout) {
165                Ok(Ok(test_result)) => {
166                    let expected_file = file_path.with_extension(format!("{}.built.json", file_path.extension().unwrap_or_default().to_str().unwrap_or("")));
167
168                    // Migration: If the new naming convention file doesn't exist, but the old one does, rename it
169                    if !expected_file.exists() {
170                        let legacy_file = file_path.with_extension("expected.json");
171                        if legacy_file.exists() {
172                            let _ = std::fs::rename(&legacy_file, &expected_file);
173                        }
174                    }
175
176                    if expected_file.exists() && !force_regenerated {
177                        let expected_json = json_from_path(&expected_file)?;
178                        let expected: BuilderTestExpected = serde_json::from_value(expected_json).map_err(|e| OakError::custom_error(e.to_string()))?;
179                        if test_result != expected {
180                            return Err(OakError::test_failure(file_path.to_path_buf(), format!("{:#?}", expected), format!("{:#?}", test_result)));
181                        }
182                    }
183                    else {
184                        use std::io::Write;
185                        let mut file = create_file(&expected_file)?;
186                        let json_val = serde_json::to_string_pretty(&test_result).map_err(|e| OakError::custom_error(e.to_string()))?;
187                        file.write_all(json_val.as_bytes()).map_err(|e| OakError::custom_error(e.to_string()))?;
188                        regenerated = true;
189                    }
190                }
191                Ok(Err(e)) => return Err(e),
192                Err(mpsc::RecvTimeoutError::Timeout) => {
193                    return Err(OakError::custom_error(format!("Builder test timed out after {:?} for file: {}", timeout, file_path_string)));
194                }
195                Err(mpsc::RecvTimeoutError::Disconnected) => {
196                    return Err(OakError::custom_error("Builder thread disconnected unexpectedly"));
197                }
198            }
199            Ok(regenerated)
200        })
201    }
202}