example unit test

This commit is contained in:
Fernando Herrera 2021-10-09 14:10:10 +01:00
parent 5021d61800
commit e3e4ae0591
10 changed files with 285 additions and 25 deletions

1
Cargo.lock generated
View file

@ -520,6 +520,7 @@ dependencies = [
"glob",
"nu-engine",
"nu-json",
"nu-parser",
"nu-path",
"nu-protocol",
"nu-table",

View file

@ -11,6 +11,7 @@ nu-json = { path = "../nu-json" }
nu-path = { path = "../nu-path" }
nu-protocol = { path = "../nu-protocol" }
nu-table = { path = "../nu-table" }
nu-parser = { path = "../nu-parser" }
# Potential dependencies for extras
glob = "0.3.0"

View file

@ -0,0 +1,74 @@
use std::{cell::RefCell, rc::Rc};
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
engine::{Command, EngineState, EvaluationContext, StateWorkingSet},
Value,
};
use super::From;
pub fn test_examples(cmd: impl Command + 'static) {
let examples = cmd.examples();
let engine_state = Rc::new(RefCell::new(EngineState::new()));
let delta = {
// Base functions that are needed for testing
// Try to keep this working set as small to keep tests running as fast as possible
let engine_state = engine_state.borrow();
let mut working_set = StateWorkingSet::new(&*engine_state);
working_set.add_decl(Box::new(From));
// Adding the command that is being tested to the working set
working_set.add_decl(Box::new(cmd));
working_set.render()
};
EngineState::merge_delta(&mut *engine_state.borrow_mut(), delta);
for example in examples {
let start = std::time::Instant::now();
let (block, delta) = {
let engine_state = engine_state.borrow();
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 {
panic!("test parse error: {:?}", err)
}
(output, working_set.render())
};
EngineState::merge_delta(&mut *engine_state.borrow_mut(), delta);
let state = EvaluationContext {
engine_state: engine_state.clone(),
stack: nu_protocol::engine::Stack::new(),
};
match eval_block(&state, &block, Value::nothing()) {
Err(err) => panic!("test eval error: {:?}", err),
Ok(result) => {
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
)
}
}
}
}
}
}

View file

@ -1,7 +1,7 @@
use nu_engine::eval_block;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EvaluationContext};
use nu_protocol::{IntoValueStream, Signature, SyntaxShape, Value};
use nu_protocol::{Example, IntoValueStream, Signature, Span, SyntaxShape, Value};
pub struct Each;
@ -24,6 +24,32 @@ impl Command for Each {
.switch("numbered", "iterate with an index", Some('n'))
}
fn examples(&self) -> Vec<Example> {
let stream_test_1 = vec![
Value::Int {
val: 2,
span: Span::unknown(),
},
Value::Int {
val: 4,
span: Span::unknown(),
},
Value::Int {
val: 6,
span: Span::unknown(),
},
];
vec![Example {
example: "[1 2 3] | each { 2 * $it }",
description: "Multiplies elements in list",
result: Some(Value::Stream {
stream: stream_test_1.into_iter().into_value_stream(),
span: Span::unknown(),
}),
}]
}
fn run(
&self,
context: &EvaluationContext,
@ -225,3 +251,15 @@ impl Command for Each {
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Each {})
}
}

View file

@ -98,34 +98,43 @@ impl Command for For {
Example {
description: "Echo the square of each integer",
example: "for x in [1 2 3] { $x * $x }",
result: Some(vec![
Value::Int { val: 1, span },
Value::Int { val: 4, span },
Value::Int { val: 9, span },
]),
result: Some(Value::List {
vals: vec![
Value::Int { val: 1, span },
Value::Int { val: 4, span },
Value::Int { val: 9, span },
],
span: Span::unknown(),
}),
},
Example {
description: "Work with elements of a range",
example: "for $x in 1..3 { $x }",
result: Some(vec![
Value::Int { val: 1, span },
Value::Int { val: 2, span },
Value::Int { val: 3, span },
]),
result: Some(Value::List {
vals: vec![
Value::Int { val: 1, span },
Value::Int { val: 2, span },
Value::Int { val: 3, span },
],
span: Span::unknown(),
}),
},
Example {
description: "Number each item and echo a message",
example: "for $it in ['bob' 'fred'] --numbered { $\"($it.index) is ($it.item)\" }",
result: Some(vec![
Value::String {
val: "0 is bob".into(),
span,
},
Value::String {
val: "0 is fred".into(),
span,
},
]),
result: Some(Value::List {
vals: vec![
Value::String {
val: "0 is bob".into(),
span,
},
Value::String {
val: "0 is fred".into(),
span,
},
],
span: Span::unknown(),
}),
},
]
}

View file

@ -1,6 +1,6 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EvaluationContext};
use nu_protocol::{IntoValueStream, ShellError, Signature, Span, Value};
use nu_protocol::{Example, IntoValueStream, ShellError, Signature, Span, Value};
pub struct FromJson;
@ -21,6 +21,50 @@ impl Command for FromJson {
)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
example: "'{ a:1 }' | from json",
description: "Converts json formatted string to table",
result: Some(Value::Record {
cols: vec!["a".to_string()],
vals: vec![Value::Int {
val: 1,
span: Span::unknown(),
}],
span: Span::unknown(),
}),
},
Example {
example: "'{ a:1, b: [1, 2] }' | from json",
description: "Converts json formatted string to table",
result: Some(Value::Record {
cols: vec!["a".to_string(), "b".to_string()],
vals: vec![
Value::Int {
val: 1,
span: Span::unknown(),
},
Value::List {
vals: vec![
Value::Int {
val: 1,
span: Span::unknown(),
},
Value::Int {
val: 2,
span: Span::unknown(),
},
],
span: Span::unknown(),
},
],
span: Span::unknown(),
}),
},
]
}
fn run(
&self,
_context: &EvaluationContext,
@ -109,3 +153,15 @@ fn convert_string_to_value(string_input: String, span: Span) -> Result<Value, Sh
)),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(FromJson {})
}
}

View file

@ -1,6 +1,7 @@
mod core_commands;
mod default_context;
mod env;
mod example_test;
mod experimental;
mod filesystem;
mod filters;
@ -9,9 +10,10 @@ mod strings;
mod system;
mod viewers;
pub use core_commands::*;
pub(crate) use core_commands::*;
pub use default_context::*;
pub use env::*;
pub use example_test::test_examples;
pub use experimental::*;
pub use filesystem::*;
pub use filters::*;

View file

@ -1,7 +1,7 @@
use nu_engine::eval_expression;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EvaluationContext};
use nu_protocol::{ShellError, Signature, SyntaxShape, Value};
use nu_protocol::{Example, ShellError, Signature, Span, SyntaxShape, Value};
pub struct BuildString;
@ -18,6 +18,27 @@ impl Command for BuildString {
Signature::build("build-string").rest("rest", SyntaxShape::String, "list of string")
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
example: "build-string a b c",
description: "Builds a string from letters a b c",
result: Some(Value::String {
val: "abc".to_string(),
span: Span::unknown(),
}),
},
Example {
example: "build-string (1 + 2) = one ' ' plus ' ' two",
description: "Builds a string from letters a b c",
result: Some(Value::String {
val: "3=one plus two".to_string(),
span: Span::unknown(),
}),
},
]
}
fn run(
&self,
context: &EvaluationContext,
@ -36,3 +57,15 @@ impl Command for BuildString {
})
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(BuildString {})
}
}

View file

@ -3,5 +3,5 @@ use crate::Value;
pub struct Example {
pub example: &'static str,
pub description: &'static str,
pub result: Option<Vec<Value>>,
pub result: Option<Value>,
}

View file

@ -374,6 +374,52 @@ impl PartialEq for Value {
(Value::Float { val: lhs, .. }, Value::Float { val: rhs, .. }) => lhs == rhs,
(Value::String { val: lhs, .. }, Value::String { val: rhs, .. }) => lhs == rhs,
(Value::Block { val: b1, .. }, Value::Block { val: b2, .. }) => b1 == b2,
(Value::List { vals: vals_lhs, .. }, Value::List { vals: vals_rhs, .. }) => {
for (lhs, rhs) in vals_lhs.iter().zip(vals_rhs) {
if lhs != rhs {
return false;
}
}
true
}
(
Value::Record {
cols: cols_lhs,
vals: vals_lhs,
..
},
Value::Record {
cols: cols_rhs,
vals: vals_rhs,
..
},
) => {
if cols_lhs != cols_rhs {
return false;
}
for (lhs, rhs) in vals_lhs.iter().zip(vals_rhs) {
if lhs != rhs {
return false;
}
}
true
}
(
Value::Stream {
stream: stream_lhs, ..
},
Value::Stream {
stream: stream_rhs, ..
},
) => {
let vals_lhs = stream_lhs.clone().collect_string();
let vals_rhs = stream_rhs.clone().collect_string();
vals_lhs == vals_rhs
}
_ => false,
}
}