Skip to content

Commit ce250d4

Browse files
authored
Evaluation tests suite (#2660)
1 parent 7f9e749 commit ce250d4

9 files changed

Lines changed: 474 additions & 7 deletions

File tree

‎engine/baml-runtime/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ reedline = "0.37"
197197

198198

199199
[features]
200-
defaults = ["skip-integ-tests", "interpreter"]
200+
defaults = ["skip-integ-tests"]
201201
internal = []
202202
skip-integ-tests = []
203203
# Use the THIR interpreter runtime instead of the VM bytecode runtime
Lines changed: 377 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,377 @@
1+
//! Interpreter evaluation tests.
2+
//!
3+
//! These tests evaluate BAML expressions and compare the results to expected outputs.
4+
//! Test files are in the `interpreter_tests/` directory and use the format:
5+
//!
6+
//! ```baml
7+
//! function Foo() -> int {
8+
//! 1 + 2
9+
//! }
10+
//!
11+
//! //> Foo()
12+
//! //
13+
//! // 3
14+
//! ```
15+
//!
16+
//! The first comment starting with `>` contains the expression to evaluate,
17+
//! and subsequent comments contain the expected pretty-printed result.
18+
19+
use std::path::PathBuf;
20+
21+
use anyhow::{Context, Result};
22+
// Use the CoreRuntime pattern: select implementation based on feature flag
23+
#[cfg(feature = "interpreter")]
24+
use baml_runtime::async_interpreter_runtime::BamlAsyncInterpreterRuntime as CoreRuntime;
25+
#[cfg(not(feature = "interpreter"))]
26+
use baml_runtime::async_vm_runtime::BamlAsyncVmRuntime as CoreRuntime;
27+
use baml_types::BamlValue;
28+
29+
/// Test case parsed from a .baml file
30+
#[derive(Debug)]
31+
struct InterpreterTest {
32+
/// The BAML source code
33+
source: String,
34+
/// Expression to evaluate (from comment starting with `>`)
35+
expr: String,
36+
/// Expected output (from subsequent comments)
37+
expected: String,
38+
/// File path for error reporting
39+
file_path: PathBuf,
40+
}
41+
42+
/// Test result including value and watch notifications
43+
#[derive(Debug)]
44+
struct TestResult {
45+
value: BamlValue,
46+
watch_notifications: Vec<String>,
47+
}
48+
49+
/// Parse a test file into test cases
50+
fn parse_test_file(path: &PathBuf) -> Result<Vec<InterpreterTest>> {
51+
let source = std::fs::read_to_string(path)
52+
.with_context(|| format!("Failed to read test file: {}", path.display()))?;
53+
54+
let mut tests = Vec::new();
55+
let mut current_expr: Option<String> = None;
56+
let mut current_expected = Vec::new();
57+
let mut baml_source = String::new();
58+
let mut in_comment_block = false;
59+
60+
for line in source.lines() {
61+
let trimmed = line.trim();
62+
63+
if trimmed.starts_with("//>") {
64+
// Start of a new test expression
65+
if let Some(expr) = current_expr.take() {
66+
// Save previous test
67+
tests.push(InterpreterTest {
68+
source: baml_source.clone(),
69+
expr,
70+
expected: current_expected.join("\n"),
71+
file_path: path.clone(),
72+
});
73+
current_expected.clear();
74+
}
75+
76+
current_expr = Some(trimmed.trim_start_matches("//>").trim().to_string());
77+
in_comment_block = true;
78+
} else if in_comment_block && trimmed.starts_with("//") {
79+
// Continuation of expected output
80+
// Remove "//" prefix, keeping all whitespace after it
81+
let content = trimmed.strip_prefix("//").unwrap_or(trimmed);
82+
// If there's a leading space after //, remove just one space
83+
let content = content.strip_prefix(" ").unwrap_or(content);
84+
current_expected.push(content.to_string());
85+
} else if in_comment_block && trimmed.is_empty() {
86+
// Empty line might be part of expected output
87+
current_expected.push(String::new());
88+
} else if !trimmed.starts_with("//") {
89+
// Not a comment, back to source code
90+
in_comment_block = false;
91+
baml_source.push_str(line);
92+
baml_source.push('\n');
93+
}
94+
}
95+
96+
// Don't forget the last test
97+
if let Some(expr) = current_expr {
98+
tests.push(InterpreterTest {
99+
source: baml_source.clone(),
100+
expr,
101+
expected: current_expected.join("\n"),
102+
file_path: path.clone(),
103+
});
104+
}
105+
106+
Ok(tests)
107+
}
108+
109+
/// Evaluate an expression using the selected runtime
110+
async fn eval_expr(source: &str, expr_to_eval: &str) -> Result<TestResult> {
111+
use std::{
112+
collections::HashMap,
113+
sync::{Arc, Mutex},
114+
};
115+
116+
use baml_runtime::BamlSrcReader;
117+
use baml_types::BamlValue;
118+
119+
// Collect watch notifications
120+
let notifications = Arc::new(Mutex::new(Vec::new()));
121+
let notifications_clone = notifications.clone();
122+
123+
// Create watch handler using the helper function
124+
let watch_handler = baml_compiler::watch::shared_handler(
125+
move |notification: baml_compiler::watch::WatchNotification| {
126+
let mut notifs = notifications_clone.lock().unwrap();
127+
128+
// Only handle Value notifications (not Block, StreamStart, etc.)
129+
if let baml_compiler::watch::WatchBamlValue::Value(value_with_meta) = notification.value
130+
{
131+
if let Some(var_name) = notification.variable_name {
132+
// Convert BamlValueWithMeta to BamlValue and serialize as JSON
133+
let baml_value = value_with_meta.value();
134+
let value_str = serde_json::to_string(&baml_value)
135+
.unwrap_or_else(|_| format!("{:?}", baml_value));
136+
let formatted = format!("[watch] {} = {}", var_name, value_str);
137+
notifs.push(formatted);
138+
}
139+
}
140+
},
141+
);
142+
143+
// The expression should be a function call like "Add()" or "WithWatch()"
144+
// Extract the function name from the expression (everything before the opening paren)
145+
let function_name = expr_to_eval
146+
.trim()
147+
.split('(')
148+
.next()
149+
.ok_or_else(|| anyhow::anyhow!("Invalid expression: {}", expr_to_eval))?
150+
.trim()
151+
.to_string();
152+
153+
// Create runtime with source - need to pass as HashMap
154+
let mut files = HashMap::new();
155+
files.insert("test.baml", source);
156+
157+
let env_vars: HashMap<String, String> = std::env::vars().collect();
158+
159+
let core_runtime = CoreRuntime::from_file_content(".", &files, env_vars.clone())?;
160+
161+
// Create context manager - BamlSrcReader is Option<Box<dyn Fn...>>, so pass None
162+
let ctx = baml_runtime::RuntimeContextManager::new(None);
163+
164+
// Call the function directly
165+
let (result, _call_id) = core_runtime
166+
.call_function(
167+
function_name,
168+
&baml_types::BamlMap::new(),
169+
&ctx,
170+
None, // TypeBuilder
171+
None, // ClientRegistry
172+
None, // collectors
173+
env_vars,
174+
None, // tags
175+
baml_runtime::TripWire::new(None),
176+
Some(watch_handler),
177+
)
178+
.await;
179+
180+
let function_result = result?;
181+
182+
// Extract the BamlValue from FunctionResult
183+
// result_with_constraints() returns &Option<Result<ResponseBamlValue>>
184+
let response_value = function_result
185+
.result_with_constraints()
186+
.as_ref()
187+
.ok_or_else(|| anyhow::anyhow!("No result returned"))?
188+
.as_ref()
189+
.map_err(|e| anyhow::anyhow!("Failed to parse result: {}", e))?;
190+
191+
// ResponseBamlValue is a wrapper around BamlValueWithMeta, access the inner value with .0
192+
// Convert BamlValueWithMeta to BamlValue by stripping metadata
193+
let value: BamlValue = (&response_value.0).into();
194+
195+
// Extract watch notifications
196+
let watch_notifications = notifications.lock().unwrap().clone();
197+
198+
Ok(TestResult {
199+
value,
200+
watch_notifications,
201+
})
202+
}
203+
204+
/// Run a single interpreter test
205+
async fn run_test(test: &InterpreterTest) -> Result<()> {
206+
let result = eval_expr(&test.source, &test.expr).await?;
207+
208+
// Build actual output: value + watch notifications
209+
let mut actual_lines = Vec::new();
210+
211+
// Add watch notifications first
212+
for notification in &result.watch_notifications {
213+
actual_lines.push(notification.clone());
214+
}
215+
216+
// Add separator if there are watch notifications
217+
if !result.watch_notifications.is_empty() {
218+
actual_lines.push(String::new());
219+
}
220+
221+
// Add the result value - format as JSON-like output to match expected format
222+
// Use serde_json to serialize the BamlValue
223+
let value_str = serde_json::to_string_pretty(&result.value)
224+
.unwrap_or_else(|_| format!("{:#?}", result.value));
225+
actual_lines.push(value_str);
226+
227+
let actual = actual_lines.join("\n");
228+
let expected = test.expected.trim();
229+
230+
if actual != expected {
231+
// Check if UPDATE_EXPECT environment variable is set to a truthy value
232+
let should_update = std::env::var("UPDATE_EXPECT")
233+
.ok()
234+
.map(|v| {
235+
let v = v.to_lowercase();
236+
// Consider truthy: "1", "true", "yes"
237+
// Consider falsy: "0", "false", "no", or empty string
238+
v == "1" || v == "true" || v == "yes"
239+
})
240+
.unwrap_or(false);
241+
242+
if should_update {
243+
update_test_expectation(test, &actual)?;
244+
println!("Updated expectation for test: {}", test.file_path.display());
245+
Ok(())
246+
} else {
247+
anyhow::bail!(
248+
"Test failed: {}\nExpression: {}\nExpected:\n{}\n\nActual:\n{}\n\nRun with UPDATE_EXPECT=1 to update the expectation.",
249+
test.file_path.display(),
250+
test.expr,
251+
expected,
252+
actual
253+
);
254+
}
255+
} else {
256+
Ok(())
257+
}
258+
}
259+
260+
/// Update the test file with new expected output
261+
fn update_test_expectation(test: &InterpreterTest, new_output: &str) -> Result<()> {
262+
// Read the original file
263+
let original_content = std::fs::read_to_string(&test.file_path)
264+
.with_context(|| format!("Failed to read test file: {}", test.file_path.display()))?;
265+
266+
// Build the new content by replacing the expected output section
267+
let mut new_content = String::new();
268+
let mut lines = original_content.lines();
269+
let mut in_test_output = false;
270+
let mut found_test = false;
271+
272+
while let Some(line) = lines.next() {
273+
let trimmed = line.trim();
274+
275+
// Check if this is the start of our test expression
276+
if trimmed.starts_with("//>") {
277+
let expr = trimmed.trim_start_matches("//>").trim();
278+
if expr == test.expr {
279+
found_test = true;
280+
new_content.push_str(line);
281+
new_content.push('\n');
282+
283+
// Skip the old expected output lines
284+
in_test_output = true;
285+
continue;
286+
}
287+
}
288+
289+
if in_test_output {
290+
// Skip old expected output (lines starting with "//")
291+
if trimmed.starts_with("//") || trimmed.is_empty() {
292+
continue;
293+
} else {
294+
// We've reached the end of the expected output section
295+
in_test_output = false;
296+
297+
// Insert the new expected output
298+
new_content.push_str("//\n");
299+
for output_line in new_output.lines() {
300+
new_content.push_str("// ");
301+
new_content.push_str(output_line);
302+
new_content.push('\n');
303+
}
304+
305+
// Add the current line (which is not part of the expected output)
306+
new_content.push_str(line);
307+
new_content.push('\n');
308+
}
309+
} else {
310+
new_content.push_str(line);
311+
new_content.push('\n');
312+
}
313+
}
314+
315+
// If we're still in test output at the end of file, insert the new output
316+
if in_test_output {
317+
new_content.push_str("//\n");
318+
for output_line in new_output.lines() {
319+
new_content.push_str("// ");
320+
new_content.push_str(output_line);
321+
new_content.push('\n');
322+
}
323+
}
324+
325+
if !found_test {
326+
anyhow::bail!("Could not find test expression '{}' in file", test.expr);
327+
}
328+
329+
// Write the updated content back to the file
330+
std::fs::write(&test.file_path, new_content).with_context(|| {
331+
format!(
332+
"Failed to write updated test file: {}",
333+
test.file_path.display()
334+
)
335+
})?;
336+
337+
Ok(())
338+
}
339+
340+
/// Main test function that discovers and runs all interpreter tests
341+
#[tokio::test]
342+
async fn interpreter_tests() -> Result<()> {
343+
let test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/interpreter_tests");
344+
345+
if !test_dir.exists() {
346+
// No tests yet, skip
347+
return Ok(());
348+
}
349+
350+
let mut all_tests = Vec::new();
351+
352+
// Discover all .baml test files
353+
for entry in std::fs::read_dir(&test_dir)? {
354+
let entry = entry?;
355+
let path = entry.path();
356+
357+
if path.extension().and_then(|s| s.to_str()) == Some("baml") {
358+
let tests = parse_test_file(&path)?;
359+
all_tests.extend(tests);
360+
}
361+
}
362+
363+
println!("Running {} interpreter tests", all_tests.len());
364+
365+
// Run all tests
366+
for test in &all_tests {
367+
run_test(test).await.with_context(|| {
368+
format!(
369+
"Test failed in {} for expression: {}",
370+
test.file_path.display(),
371+
test.expr
372+
)
373+
})?;
374+
}
375+
376+
Ok(())
377+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Basic arithmetic test
2+
3+
function Add() -> int {
4+
1 + 2
5+
}
6+
7+
//> Add()
8+
//
9+
// 3

0 commit comments

Comments
 (0)