nushell/crates/nu-command/src/example_test.rs

77 lines
2.6 KiB
Rust
Raw Normal View History

2021-10-09 15:10:10 +02:00
use std::{cell::RefCell, rc::Rc};
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
2021-10-25 08:31:39 +02:00
engine::{Command, EngineState, EvaluationContext, Stack, StateWorkingSet},
2021-10-25 06:01:02 +02:00
PipelineData, Value,
2021-10-09 15:10:10 +02:00
};
2021-10-11 03:56:19 +02:00
use super::{From, Into, Split};
2021-10-09 15:10:10 +02:00
pub fn test_examples(cmd: impl Command + 'static) {
let examples = cmd.examples();
2021-10-25 06:01:02 +02:00
let mut engine_state = Box::new(EngineState::new());
2021-10-09 15:10:10 +02:00
let delta = {
// Base functions that are needed for testing
2021-10-09 15:28:09 +02:00
// Try to keep this working set small to keep tests running as fast as possible
2021-10-09 15:10:10 +02:00
let mut working_set = StateWorkingSet::new(&*engine_state);
working_set.add_decl(Box::new(From));
2021-10-11 03:56:19 +02:00
working_set.add_decl(Box::new(Into));
2021-10-09 15:28:09 +02:00
working_set.add_decl(Box::new(Split));
2021-10-09 15:10:10 +02:00
// Adding the command that is being tested to the working set
working_set.add_decl(Box::new(cmd));
working_set.render()
};
2021-10-25 06:01:02 +02:00
EngineState::merge_delta(&mut *engine_state, delta);
2021-10-09 15:10:10 +02:00
for example in examples {
2021-10-11 03:56:19 +02:00
// Skip tests that don't have results to compare to
if example.result.is_none() {
continue;
}
2021-10-09 15:10:10 +02:00
let start = std::time::Instant::now();
let (block, delta) = {
let mut working_set = StateWorkingSet::new(&*engine_state);
let (output, err) = parse(&mut working_set, None, example.example.as_bytes(), false);
if let Some(err) = err {
2021-10-11 03:56:19 +02:00
panic!("test parse error in `{}`: {:?}", example.example, err)
2021-10-09 15:10:10 +02:00
}
(output, working_set.render())
};
2021-10-25 08:31:39 +02:00
EngineState::merge_delta(&mut engine_state, delta);
2021-10-09 15:10:10 +02:00
2021-10-25 08:31:39 +02:00
let mut stack = Stack::new();
2021-10-09 15:10:10 +02:00
2021-10-25 08:31:39 +02:00
match eval_block(&engine_state, &mut stack, &block, PipelineData::new()) {
2021-10-11 03:56:19 +02:00
Err(err) => panic!("test eval error in `{}`: {:?}", example.example, err),
2021-10-09 15:10:10 +02:00
Ok(result) => {
2021-10-25 06:01:02 +02:00
let result = result.into_value();
2021-10-09 15:10:10 +02:00
println!("input: {}", example.example);
println!("result: {:?}", result);
println!("done: {:?}", start.elapsed());
// Note. Value implements PartialEq for Bool, Int, Float, String and Block
// If the command you are testing requires to compare another case, then
// you need to define its equality in the Value struct
if let Some(expected) = example.result {
if result != expected {
panic!(
"the example result is different to expected value: {:?} != {:?}",
result, expected
)
}
}
}
}
}
}