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,
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 {
87            println!("Tests regenerated for: {}", self.root.display());
88            Ok(())
89        }
90        else {
91            Ok(())
92        }
93    }
94
95    fn find_test_files(&self) -> Result<Vec<PathBuf>, OakError> {
96        let mut files = Vec::new();
97
98        for entry in WalkDir::new(&self.root) {
99            let entry = entry.unwrap();
100            let path = entry.path();
101
102            if path.is_file() {
103                if let Some(ext) = path.extension() {
104                    let ext_str = ext.to_str().unwrap_or("");
105                    if self.extensions.iter().any(|e| e == ext_str) {
106                        // Ignore output files generated by the Tester itself to prevent recursive inclusion
107                        let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
108                        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");
109
110                        if !is_output_file {
111                            files.push(path.to_path_buf());
112                        }
113                    }
114                }
115            }
116        }
117
118        Ok(files)
119    }
120
121    fn test_single_file<L, B>(&self, file_path: &Path, builder: &B, force_regenerated: bool) -> Result<bool, OakError>
122    where
123        B: Builder<L> + Send + Sync,
124        L: Language + Send + Sync,
125        L::TypedRoot: Serialize + Debug + Sync + Send,
126    {
127        let source = source_from_path(file_path)?;
128
129        // Perform build in a thread and construct test results, with main thread handling timeout control
130        use std::sync::mpsc;
131        let (tx, rx) = mpsc::channel();
132        let timeout = self.timeout;
133        let file_path_string = file_path.display().to_string();
134
135        std::thread::scope(|s| {
136            s.spawn(move || {
137                let mut cache = oak_core::parser::ParseSession::<L>::new(1024);
138                let build_out = builder.build(&source, &[], &mut cache);
139
140                // Build typed root structure if build succeeded
141                let (success, typed_root) = match &build_out.result {
142                    Ok(root) => {
143                        // Serialize the typed root to JSON for comparison
144                        match serde_json::to_value(root) {
145                            Ok(content) => {
146                                let typed_root_data = TypedRootData { type_name: std::any::type_name::<L::TypedRoot>().to_string(), content };
147                                (true, Some(typed_root_data))
148                            }
149                            Err(_) => {
150                                // If serialization fails, still mark as success but with no typed root data
151                                (true, None)
152                            }
153                        }
154                    }
155                    Err(_) => (false, None),
156                };
157
158                // Collect error messages
159                let mut error_messages: Vec<String> = build_out.diagnostics.iter().map(|e| e.to_string()).collect();
160                if let Err(e) = &build_out.result {
161                    error_messages.push(e.to_string());
162                }
163
164                let test_result = BuilderTestExpected { success, typed_root, errors: error_messages };
165
166                let _ = tx.send(Ok::<BuilderTestExpected, OakError>(test_result));
167            });
168
169            let mut regenerated = false;
170            match rx.recv_timeout(timeout) {
171                Ok(Ok(test_result)) => {
172                    let expected_file = file_path.with_extension(format!("{}.built.json", file_path.extension().unwrap_or_default().to_str().unwrap_or("")));
173
174                    // Migration: If the new naming convention file doesn't exist, but the old one does, rename it
175                    if !expected_file.exists() {
176                        let legacy_file = file_path.with_extension("expected.json");
177                        if legacy_file.exists() {
178                            let _ = std::fs::rename(&legacy_file, &expected_file);
179                        }
180                    }
181
182                    if expected_file.exists() && !force_regenerated {
183                        let expected_json = json_from_path(&expected_file)?;
184                        let expected: BuilderTestExpected = serde_json::from_value(expected_json).map_err(|e| OakError::custom_error(e.to_string()))?;
185                        if test_result != expected {
186                            return Err(OakError::test_failure(file_path.to_path_buf(), format!("{:#?}", expected), format!("{:#?}", test_result)));
187                        }
188                    }
189                    else {
190                        use std::io::Write;
191                        let mut file = create_file(&expected_file)?;
192                        let json_val = serde_json::to_string_pretty(&test_result).map_err(|e| OakError::custom_error(e.to_string()))?;
193                        file.write_all(json_val.as_bytes()).map_err(|e| OakError::custom_error(e.to_string()))?;
194                        regenerated = true;
195                    }
196                }
197                Ok(Err(e)) => return Err(e),
198                Err(mpsc::RecvTimeoutError::Timeout) => return Err(OakError::custom_error(format!("Builder test timed out after {:?} for file: {}", timeout, file_path_string))),
199                Err(mpsc::RecvTimeoutError::Disconnected) => return Err(OakError::custom_error("Builder thread disconnected unexpectedly")),
200            }
201            Ok(regenerated)
202        })
203    }
204}