Skip to main content

reifydb_testing/testscript/
runner.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4// This file includes and modifies code from the toydb project (https://github.com/erikgrinaker/toydb),
5// originally licensed under the Apache License, Version 2.0.
6// Original copyright:
7//   Copyright (c) 2024 Erik Grinaker
8//
9// The original Apache License can be found at:
10//   http://www.apache.org/licenses/LICENSE-2.0
11
12use std::{env::temp_dir, error::Error, fs, io, io::Write as _, panic, path, process, time};
13
14use fs::read_to_string;
15use io::ErrorKind;
16use panic::AssertUnwindSafe;
17use path::Path;
18use time::SystemTime;
19
20use crate::{
21	goldenfile::Mint,
22	testscript::{command::Command, parser::parse},
23};
24
25/// Runs testscript commands, returning their output.
26pub trait Runner {
27	/// Runs a testscript command, returning its output, or an error if the
28	/// command fails.
29	///
30	/// Arguments can be accessed directly via [`Command::args`], or by
31	/// using the [`Command::consume_args`] helper for more convenient
32	/// processing.
33	///
34	/// Error cases are typically tested by running the command with a `!`
35	/// prefix (expecting a failure), but the runner can also handle these
36	/// itself and return an `Ok` result with appropriate output.
37	fn run(&mut self, command: &Command) -> Result<String, Box<dyn Error>>;
38
39	/// Called at the start of a testscript. Used e.g. for initial setup.
40	/// Can't return output, since it's not called in the context of a
41	/// block.
42	fn start_script(&mut self) -> Result<(), Box<dyn Error>> {
43		Ok(())
44	}
45
46	/// Called at the end of a testscript. Used e.g. for state assertions.
47	/// Can't return output, since it's not called in the context of a
48	/// block.
49	fn end_script(&mut self) -> Result<(), Box<dyn Error>> {
50		Ok(())
51	}
52
53	/// Called at the start of a block. Used e.g. to output initial state.
54	/// Any output is prepended to the block's output.
55	fn start_block(&mut self) -> Result<String, Box<dyn Error>> {
56		Ok(String::new())
57	}
58
59	/// Called at the end of a block. Used e.g. to output final state.
60	/// Any output is appended to the block's output.
61	fn end_block(&mut self) -> Result<String, Box<dyn Error>> {
62		Ok(String::new())
63	}
64
65	/// Called at the start of a command. Used e.g. for setup. Any output is
66	/// prepended to the command's output, and is affected e.g. by the
67	/// prefix and silencing of the command.
68	#[allow(unused_variables)]
69	fn start_command(&mut self, command: &Command) -> Result<String, Box<dyn Error>> {
70		Ok(String::new())
71	}
72
73	/// Called at the end of a command. Used e.g. for cleanup. Any output is
74	/// appended to the command's output, and is affected e.g. by the prefix
75	/// and silencing of the command.
76	#[allow(unused_variables)]
77	fn end_command(&mut self, command: &Command) -> Result<String, Box<dyn Error>> {
78		Ok(String::new())
79	}
80}
81
82/// Runs a testscript at the given path.
83///
84/// Panics if the script output differs from the current input file. Errors on
85/// IO, parser, or runner failure. If the environment variable
86/// `UPDATE_TESTFILES=1` is set, the new output file will replace the input
87/// file.
88pub fn run_path<R: Runner, P: AsRef<Path>>(runner: &mut R, path: P) -> io::Result<()> {
89	let path = path.as_ref();
90	let Some(dir) = path.parent() else {
91		return Err(io::Error::new(ErrorKind::InvalidInput, format!("invalid path '{path:?}'")));
92	};
93	let Some(filename) = path.file_name() else {
94		return Err(io::Error::new(ErrorKind::InvalidInput, format!("invalid path '{path:?}'")));
95	};
96
97	if filename.to_str().unwrap().ends_with(".skip") {
98		return Ok(());
99	}
100
101	let input = read_to_string(dir.join(filename))?;
102	let output = generate(runner, &input)?;
103
104	Mint::new(dir).new_goldenfile(filename)?.write_all(output.as_bytes())
105}
106
107pub fn run<R: Runner, S: Into<String>>(runner: R, test: S) {
108	try_run(runner, test).unwrap();
109}
110
111pub fn try_run<R: Runner, S: Into<String>>(mut runner: R, test: S) -> io::Result<()> {
112	let input = test.into();
113
114	let dir = temp_dir();
115	#[allow(clippy::disallowed_methods)]
116	let file_name = format!(
117		"test-{}-{}.txt",
118		process::id(),
119		SystemTime::now().duration_since(time::UNIX_EPOCH).unwrap().as_nanos()
120	);
121	let file_path = dir.join(&file_name);
122
123	let mut file = fs::File::create(&file_path)?;
124	file.write_all(input.as_bytes())?;
125
126	let output = generate(&mut runner, &input)?;
127	Mint::new(dir).new_goldenfile(&file_name)?.write_all(output.as_bytes())
128}
129
130/// Generates output for a testscript input, without comparing them.
131pub fn generate<R: Runner>(runner: &mut R, input: &str) -> io::Result<String> {
132	let mut output = String::with_capacity(input.len()); // common case: output == input
133
134	// Detect end-of-line format.
135	let eol = match input.find("\r\n") {
136		Some(_) => "\r\n",
137		None => "\n",
138	};
139
140	// Parse the script.
141	let blocks = parse(input).map_err(|e| {
142		io::Error::new(
143			ErrorKind::InvalidInput,
144			format!(
145				"parse error at line {} column {} for {:?}:\n{}\n{}^",
146				e.input.location_line(),
147				e.input.get_column(),
148				e.code,
149				String::from_utf8_lossy(e.input.get_line_beginning()),
150				' '.to_string().repeat(e.input.get_utf8_column() - 1)
151			),
152		)
153	})?;
154
155	// Call the start_script() hook.
156	runner.start_script().map_err(|e| io::Error::other(format!("start_script failed: {e}")))?;
157
158	for (i, block) in blocks.iter().enumerate() {
159		// There may be a trailing block with no commands if the script
160		// has bare comments at the end. If so, just retain its
161		// literal contents.
162		if block.commands.is_empty() {
163			output.push_str(&block.literal);
164			continue;
165		}
166
167		// Process each block of commands and accumulate their output.
168		let mut block_output = String::new();
169
170		// Call the start_block() hook.
171		block_output.push_str(&ensure_eol(
172			runner.start_block().map_err(|e| {
173				io::Error::other(format!("start_block failed at line {}: {e}", block.line_number))
174			})?,
175			eol,
176		));
177
178		for command in &block.commands {
179			let mut command_output = String::new();
180
181			// Call the start_command() hook.
182			command_output.push_str(&ensure_eol(
183				runner.start_command(command).map_err(|e| {
184					io::Error::other(format!(
185						"start_command failed at line {}: {e}",
186						command.line_number
187					))
188				})?,
189				eol,
190			));
191
192			// Execute the command. Handle panics and errors if
193			// requested. We assume the command is unwind-safe
194			// when handling panics, it is up to callers to
195			// manage this appropriately.
196			let run = AssertUnwindSafe(|| runner.run(command));
197			command_output.push_str(&match panic::catch_unwind(run) {
198				// Unexpected success, error out.
199				Ok(Ok(output)) if command.fail => {
200					return Err(io::Error::other(format!(
201						"expected command '{}' to fail at line {}, succeeded with: {output}",
202						command.name, command.line_number
203					)));
204				}
205
206				// Expected success, output the result.
207				Ok(Ok(output)) => output,
208
209				// Expected error, output it.
210				Ok(Err(e)) if command.fail => {
211					format!("{e}")
212				}
213
214				// Unexpected error, return it.
215				Ok(Err(e)) => {
216					return Err(io::Error::other(format!(
217						"command '{}' failed at line {}: {e}",
218						command.name, command.line_number
219					)));
220				}
221
222				// Expected panic, output it.
223				Err(panic) if command.fail => {
224					let message = panic
225						.downcast_ref::<&str>()
226						.map(|s| s.to_string())
227						.or_else(|| panic.downcast_ref::<String>().cloned())
228						.unwrap_or_else(|| panic::resume_unwind(panic));
229					format!("Panic: {message}")
230				}
231
232				// Unexpected panic, throw it.
233				Err(panic) => panic::resume_unwind(panic),
234			});
235
236			// Make sure the command output has a trailing newline,
237			// unless empty.
238			command_output = ensure_eol(command_output, eol);
239
240			// Call the end_command() hook.
241			command_output.push_str(&ensure_eol(
242				runner.end_command(command).map_err(|e| {
243					io::Error::other(format!(
244						"end_command failed at line {}: {e}",
245						command.line_number
246					))
247				})?,
248				eol,
249			));
250
251			// Silence the output if requested.
252			if command.silent {
253				command_output = "".to_string();
254			}
255
256			// Prefix output lines if requested.
257			if let Some(prefix) = &command.prefix
258				&& !command_output.is_empty()
259			{
260				command_output = format!(
261					"{prefix}: {}{eol}",
262					command_output
263						.strip_suffix(eol)
264						.unwrap_or(command_output.as_str())
265						.replace('\n', &format!("\n{prefix}: "))
266				);
267			}
268
269			block_output.push_str(&command_output);
270		}
271
272		// Call the end_block() hook.
273		block_output.push_str(&ensure_eol(
274			runner.end_block().map_err(|e| {
275				io::Error::other(format!("end_block failed at line {}: {e}", block.line_number))
276			})?,
277			eol,
278		));
279
280		// If the block doesn't have any output, default to "ok".
281		if block_output.is_empty() {
282			block_output.push_str("ok\n")
283		}
284
285		// If the block output contains blank lines, use a > prefix for
286		// it.
287		//
288		// We'd be better off using regular expressions here, but don't
289		// want to add a dependency just for this.
290		if block_output.starts_with('\n')
291			|| block_output.starts_with("\r\n")
292			|| block_output.contains("\n\n")
293			|| block_output.contains("\n\r\n")
294		{
295			block_output = format!("> {}", block_output.replace('\n', "\n> "));
296			// Remove trailing space from blank lines ("> \n" -> ">\n")
297			block_output = block_output.replace("> \n", ">\n");
298			// We guarantee above that block output ends with a
299			// newline, so we remove the "> " at the end of the
300			// output.
301			block_output.pop();
302			block_output.pop();
303		}
304
305		// Add the resulting block to the output. If this is not the
306		// last block, also add a newline separator.
307		output.push_str(&format!("{}---{eol}{}", block.literal, block_output));
308		if i < blocks.len() - 1 {
309			output.push_str(eol);
310		}
311	}
312
313	// Call the end_script() hook.
314	runner.end_script().map_err(|e| io::Error::other(format!("end_script failed: {e}")))?;
315
316	Ok(output)
317}
318
319/// Appends a newline if the string is not empty and doesn't already have one.
320fn ensure_eol(mut s: String, eol: &str) -> String {
321	if let Some(c) = s.chars().next_back()
322		&& c != '\n'
323	{
324		s.push_str(eol)
325	}
326	s
327}
328
329// NB: most tests are done as testscripts under tests/.
330#[cfg(test)]
331pub mod tests {
332	use super::*;
333
334	/// A runner which simply counts the number of times its hooks are
335	/// called.
336	#[derive(Default)]
337	struct HookRunner {
338		start_script_count: usize,
339		end_script_count: usize,
340		start_block_count: usize,
341		end_block_count: usize,
342		start_command_count: usize,
343		end_command_count: usize,
344	}
345
346	impl Runner for HookRunner {
347		fn run(&mut self, _: &Command) -> Result<String, Box<dyn Error>> {
348			Ok(String::new())
349		}
350
351		fn start_script(&mut self) -> Result<(), Box<dyn Error>> {
352			self.start_script_count += 1;
353			Ok(())
354		}
355
356		fn end_script(&mut self) -> Result<(), Box<dyn Error>> {
357			self.end_script_count += 1;
358			Ok(())
359		}
360
361		fn start_block(&mut self) -> Result<String, Box<dyn Error>> {
362			self.start_block_count += 1;
363			Ok(String::new())
364		}
365
366		fn end_block(&mut self) -> Result<String, Box<dyn Error>> {
367			self.end_block_count += 1;
368			Ok(String::new())
369		}
370
371		fn start_command(&mut self, _: &Command) -> Result<String, Box<dyn Error>> {
372			self.start_command_count += 1;
373			Ok(String::new())
374		}
375
376		fn end_command(&mut self, _: &Command) -> Result<String, Box<dyn Error>> {
377			self.end_command_count += 1;
378			Ok(String::new())
379		}
380	}
381
382	/// Tests that runner hooks are called as expected.
383	#[test]
384	fn hooks() {
385		let mut runner = HookRunner::default();
386		generate(
387			&mut runner,
388			r#"
389command
390---
391
392command
393command
394---
395"#,
396		)
397		.unwrap();
398
399		assert_eq!(runner.start_script_count, 1);
400		assert_eq!(runner.end_script_count, 1);
401		assert_eq!(runner.start_block_count, 2);
402		assert_eq!(runner.end_block_count, 2);
403		assert_eq!(runner.start_command_count, 3);
404		assert_eq!(runner.end_command_count, 3);
405	}
406}