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

150 lines
4.7 KiB
Rust
Raw Normal View History

2021-12-19 08:46:13 +01:00
#[cfg(test)]
2021-10-09 15:10:10 +02:00
use nu_engine::eval_block;
2021-12-19 08:46:13 +01:00
#[cfg(test)]
2021-10-09 15:10:10 +02:00
use nu_parser::parse;
2021-12-19 08:46:13 +01:00
#[cfg(test)]
2021-10-09 15:10:10 +02:00
use nu_protocol::{
2021-10-25 18:58:58 +02:00
engine::{Command, EngineState, Stack, StateWorkingSet},
PipelineData, Span, Value,
2021-10-09 15:10:10 +02:00
};
2021-12-19 08:46:13 +01:00
#[cfg(test)]
2021-10-29 08:26:29 +02:00
use crate::To;
2021-12-19 08:46:13 +01:00
#[cfg(test)]
use super::{
Ansi, Date, From, If, Into, LetEnv, Math, Path, Random, Split, SplitColumn, SplitRow, Str,
StrJoin, StrLength, StrReplace, Url, Wrap,
};
2021-10-09 15:10:10 +02:00
2021-12-19 08:46:13 +01:00
#[cfg(test)]
2021-10-09 15:10:10 +02:00
pub fn test_examples(cmd: impl Command + 'static) {
use crate::BuildString;
2021-10-09 15:10:10 +02:00
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(Str));
working_set.add_decl(Box::new(StrJoin));
working_set.add_decl(Box::new(StrLength));
working_set.add_decl(Box::new(StrReplace));
working_set.add_decl(Box::new(BuildString));
2021-10-09 15:10:10 +02:00
working_set.add_decl(Box::new(From));
working_set.add_decl(Box::new(If));
2021-10-29 08:26:29 +02:00
working_set.add_decl(Box::new(To));
2021-10-11 03:56:19 +02:00
working_set.add_decl(Box::new(Into));
working_set.add_decl(Box::new(Random));
2021-10-09 15:28:09 +02:00
working_set.add_decl(Box::new(Split));
working_set.add_decl(Box::new(SplitColumn));
working_set.add_decl(Box::new(SplitRow));
working_set.add_decl(Box::new(Math));
working_set.add_decl(Box::new(Path));
2021-10-31 07:54:51 +01:00
working_set.add_decl(Box::new(Date));
working_set.add_decl(Box::new(Url));
working_set.add_decl(Box::new(Ansi));
working_set.add_decl(Box::new(Wrap));
working_set.add_decl(Box::new(LetEnv));
2021-10-09 15:10:10 +02:00
use super::Echo;
working_set.add_decl(Box::new(Echo));
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()
};
Use only $nu.env.PWD for getting the current directory (#587) * Use only $nu.env.PWD for getting current directory Because setting and reading to/from std::env changes the global state shich is problematic if we call `cd` from multiple threads (e.g., in a `par-each` block). With this change, when engine-q starts, it will either inherit existing PWD env var, or create a new one from `std::env::current_dir()`. Otherwise, everything that needs the current directory will get it from `$nu.env.PWD`. Each spawned external command will get its current directory per-process which should be thread-safe. One thing left to do is to patch nu-path for this as well since it uses `std::env::current_dir()` in its expansions. * Rename nu-path functions *_with is not *_relative which should be more descriptive and frees "with" for use in a followup commit. * Clone stack every each iter; Fix some commands Cloning the stack each iteration of `each` makes sure we're not reusing PWD between iterations. Some fixes in commands to make them use the new PWD. * Post-rebase cleanup, fmt, clippy * Change back _relative to _with in nu-path funcs Didn't use the idea I had for the new "_with". * Remove leftover current_dir from rebase * Add cwd sync at merge_delta() This makes sure the parser and completer always have up-to-date cwd. * Always pass absolute path to glob in ls * Do not allow PWD a relative path; Allow recovery Makes it possible to recover PWD by proceeding with the REPL cycle. * Clone stack in each also for byte/string stream * (WIP) Start moving env variables to engine state * (WIP) Move env vars to engine state (ugly) Quick and dirty code. * (WIP) Remove unused mut and args; Fmt * (WIP) Fix dataframe tests * (WIP) Fix missing args after rebase * (WIP) Clone only env vars, not the whole stack * (WIP) Add env var clone to `for` loop as well * Minor edits * Refactor merge_delta() to include stack merging. Less error-prone than doing it manually. * Clone env for each `update` command iteration * Mark env var hidden only when found in eng. state * Fix clippt warnings * Add TODO about env var reading * Do not clone empty environment in loops * Remove extra cwd collection * Split current_dir() into str and path; Fix autocd * Make completions respect PWD env var
2022-01-04 23:30:34 +01:00
let cwd = std::env::current_dir().expect("Could not get current working directory.");
engine_state
.merge_delta(delta)
.expect("Error merging 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 mut stack = Stack::new();
// Set up PWD
stack.add_env_var(
"PWD".to_string(),
Value::String {
val: cwd.to_string_lossy().to_string(),
span: Span::test_data(),
},
);
engine_state
.merge_env(&mut stack, &cwd)
.expect("Error merging environment");
2021-10-09 15:10:10 +02:00
let (block, delta) = {
let mut working_set = StateWorkingSet::new(&*engine_state);
let (output, err) = parse(
&mut working_set,
None,
example.example.as_bytes(),
false,
&[],
);
2021-10-09 15:10:10 +02:00
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())
};
engine_state
.merge_delta(delta)
.expect("Error merging 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
Use only $nu.env.PWD for getting the current directory (#587) * Use only $nu.env.PWD for getting current directory Because setting and reading to/from std::env changes the global state shich is problematic if we call `cd` from multiple threads (e.g., in a `par-each` block). With this change, when engine-q starts, it will either inherit existing PWD env var, or create a new one from `std::env::current_dir()`. Otherwise, everything that needs the current directory will get it from `$nu.env.PWD`. Each spawned external command will get its current directory per-process which should be thread-safe. One thing left to do is to patch nu-path for this as well since it uses `std::env::current_dir()` in its expansions. * Rename nu-path functions *_with is not *_relative which should be more descriptive and frees "with" for use in a followup commit. * Clone stack every each iter; Fix some commands Cloning the stack each iteration of `each` makes sure we're not reusing PWD between iterations. Some fixes in commands to make them use the new PWD. * Post-rebase cleanup, fmt, clippy * Change back _relative to _with in nu-path funcs Didn't use the idea I had for the new "_with". * Remove leftover current_dir from rebase * Add cwd sync at merge_delta() This makes sure the parser and completer always have up-to-date cwd. * Always pass absolute path to glob in ls * Do not allow PWD a relative path; Allow recovery Makes it possible to recover PWD by proceeding with the REPL cycle. * Clone stack in each also for byte/string stream * (WIP) Start moving env variables to engine state * (WIP) Move env vars to engine state (ugly) Quick and dirty code. * (WIP) Remove unused mut and args; Fmt * (WIP) Fix dataframe tests * (WIP) Fix missing args after rebase * (WIP) Clone only env vars, not the whole stack * (WIP) Add env var clone to `for` loop as well * Minor edits * Refactor merge_delta() to include stack merging. Less error-prone than doing it manually. * Clone env for each `update` command iteration * Mark env var hidden only when found in eng. state * Fix clippt warnings * Add TODO about env var reading * Do not clone empty environment in loops * Remove extra cwd collection * Split current_dir() into str and path; Fix autocd * Make completions respect PWD env var
2022-01-04 23:30:34 +01:00
// Set up PWD
stack.add_env_var(
"PWD".to_string(),
Value::String {
val: cwd.to_string_lossy().to_string(),
span: Span::test_data(),
},
);
match eval_block(
&engine_state,
&mut stack,
&block,
2021-12-19 08:46:13 +01:00
PipelineData::new(Span::test_data()),
true,
true,
) {
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-12-19 08:46:13 +01:00
let result = result.into_value(Span::test_data());
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
)
}
}
}
}
}
}