Merge branch 'master' into remove_bind_by_move

This commit is contained in:
Jonathan Turner 2019-08-29 15:08:23 +12:00 committed by GitHub
commit a42cf7bf6e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 1263 additions and 1043 deletions

View File

@ -272,11 +272,7 @@ pub async fn cli() -> Result<(), Box<dyn Error>> {
if ctrlcbreak { if ctrlcbreak {
std::process::exit(0); std::process::exit(0);
} else { } else {
context context.with_host(|host| host.stdout("CTRL-C pressed (again to quit)"));
.host
.lock()
.unwrap()
.stdout("CTRL-C pressed (again to quit)");
ctrlcbreak = true; ctrlcbreak = true;
continue; continue;
} }
@ -285,7 +281,7 @@ pub async fn cli() -> Result<(), Box<dyn Error>> {
LineResult::Error(mut line, err) => { LineResult::Error(mut line, err) => {
rl.add_history_entry(line.clone()); rl.add_history_entry(line.clone());
let diag = err.to_diagnostic(); let diag = err.to_diagnostic();
let host = context.host.lock().unwrap(); context.with_host(|host| {
let writer = host.err_termcolor(); let writer = host.err_termcolor();
line.push_str(" "); line.push_str(" ");
let files = crate::parser::Files::new(line); let files = crate::parser::Files::new(line);
@ -297,6 +293,7 @@ pub async fn cli() -> Result<(), Box<dyn Error>> {
&language_reporting::DefaultConfig, &language_reporting::DefaultConfig,
); );
}); });
})
} }
LineResult::Break => { LineResult::Break => {
@ -304,11 +301,9 @@ pub async fn cli() -> Result<(), Box<dyn Error>> {
} }
LineResult::FatalError(_, err) => { LineResult::FatalError(_, err) => {
context context.with_host(|host| {
.host host.stdout(&format!("A surprising fatal error occurred.\n{:?}", err))
.lock() });
.unwrap()
.stdout(&format!("A surprising fatal error occurred.\n{:?}", err));
} }
} }
ctrlcbreak = false; ctrlcbreak = false;
@ -330,31 +325,6 @@ enum LineResult {
FatalError(String, ShellError), FatalError(String, ShellError),
} }
impl std::ops::Try for LineResult {
type Ok = Option<String>;
type Error = (String, ShellError);
fn into_result(self) -> Result<Option<String>, (String, ShellError)> {
match self {
LineResult::Success(s) => Ok(Some(s)),
LineResult::Error(string, err) => Err((string, err)),
LineResult::Break => Ok(None),
LineResult::CtrlC => Ok(None),
LineResult::FatalError(string, err) => Err((string, err)),
}
}
fn from_error(v: (String, ShellError)) -> Self {
LineResult::Error(v.0, v.1)
}
fn from_ok(v: Option<String>) -> Self {
match v {
None => LineResult::Break,
Some(v) => LineResult::Success(v),
}
}
}
async fn process_line(readline: Result<String, ReadlineError>, ctx: &mut Context) -> LineResult { async fn process_line(readline: Result<String, ReadlineError>, ctx: &mut Context) -> LineResult {
match &readline { match &readline {
Ok(line) if line.trim() == "" => LineResult::Success(line.clone()), Ok(line) if line.trim() == "" => LineResult::Success(line.clone()),
@ -371,8 +341,10 @@ async fn process_line(readline: Result<String, ReadlineError>, ctx: &mut Context
debug!("=== Parsed ==="); debug!("=== Parsed ===");
debug!("{:#?}", result); debug!("{:#?}", result);
let mut pipeline = classify_pipeline(&result, ctx, &Text::from(line)) let mut pipeline = match classify_pipeline(&result, ctx, &Text::from(line)) {
.map_err(|err| (line.clone(), err))?; Ok(pipeline) => pipeline,
Err(err) => return LineResult::Error(line.clone(), err),
};
match pipeline.commands.last() { match pipeline.commands.last() {
Some(ClassifiedCommand::External(_)) => {} Some(ClassifiedCommand::External(_)) => {}

View File

@ -315,7 +315,8 @@ impl ExternalCommand {
if arg_string.contains("$it") { if arg_string.contains("$it") {
let mut first = true; let mut first = true;
for i in &inputs { for i in &inputs {
if i.as_string().is_err() { let i = match i.as_string() {
Err(_err) => {
let mut span = name_span; let mut span = name_span;
for arg in &self.args { for arg in &self.args {
if arg.item.contains("$it") { if arg.item.contains("$it") {
@ -328,6 +329,9 @@ impl ExternalCommand {
span, span,
)); ));
} }
Ok(val) => val,
};
if !first { if !first {
new_arg_string.push_str("&&"); new_arg_string.push_str("&&");
new_arg_string.push_str(&self.name); new_arg_string.push_str(&self.name);
@ -341,7 +345,7 @@ impl ExternalCommand {
} }
new_arg_string.push_str(" "); new_arg_string.push_str(" ");
new_arg_string.push_str(&arg.replace("$it", &i.as_string().unwrap())); new_arg_string.push_str(&arg.replace("$it", &i));
} }
} }
} else { } else {
@ -366,7 +370,7 @@ impl ExternalCommand {
process = process.stdin(stdin); process = process.stdin(stdin);
} }
let mut popen = process.popen().unwrap(); let mut popen = process.popen()?;
match stream_next { match stream_next {
StreamNext::Last => { StreamNext::Last => {

View File

@ -596,14 +596,10 @@ impl Command {
.unwrap(); .unwrap();
// We don't have an $it or block, so just execute what we have // We don't have an $it or block, so just execute what we have
command match command.run(&call_info, &registry, &raw_args.shell_manager, nothing) {
.run(&call_info, &registry, &raw_args.shell_manager, nothing)? Ok(o) => o,
.into() Err(e) => OutputStream::one(Err(e)),
// let out = match command.run(&call_info, &registry, &raw_args.shell_manager, nothing) { }
// Ok(o) => o,
// Err(e) => VecDeque::from(vec![ReturnValue::Err(e)]),
// };
// Ok(out.to_output_stream())
} }
} }
} }

View File

@ -74,7 +74,7 @@ impl CommandRegistry {
pub struct Context { pub struct Context {
registry: CommandRegistry, registry: CommandRegistry,
crate source_map: SourceMap, crate source_map: SourceMap,
crate host: Arc<Mutex<dyn Host + Send>>, host: Arc<Mutex<dyn Host + Send>>,
crate shell_manager: ShellManager, crate shell_manager: ShellManager,
} }
@ -93,6 +93,12 @@ impl Context {
}) })
} }
crate fn with_host(&mut self, block: impl FnOnce(&mut dyn Host)) {
let mut host = self.host.lock().unwrap();
block(&mut *host)
}
pub fn add_commands(&mut self, commands: Vec<Arc<Command>>) { pub fn add_commands(&mut self, commands: Vec<Arc<Command>>) {
for command in commands { for command in commands {
self.registry.insert(command.name().to_string(), command); self.registry.insert(command.name().to_string(), command);
@ -103,10 +109,6 @@ impl Context {
self.source_map.insert(uuid, span_source); self.source_map.insert(uuid, span_source);
} }
// pub fn clone_commands(&self) -> CommandRegistry {
// self.registry.clone()
// }
crate fn has_command(&self, name: &str) -> bool { crate fn has_command(&self, name: &str) -> bool {
self.registry.has(name) self.registry.has(name)
} }

View File

@ -1,7 +1,6 @@
#![feature(crate_visibility_modifier)] #![feature(crate_visibility_modifier)]
#![feature(in_band_lifetimes)] #![feature(in_band_lifetimes)]
#![feature(generators)] #![feature(generators)]
#![feature(try_trait)]
#![feature(specialization)] #![feature(specialization)]
#![feature(proc_macro_hygiene)] #![feature(proc_macro_hygiene)]
@ -30,7 +29,7 @@ pub use crate::env::host::BasicHost;
pub use crate::object::base::OF64; pub use crate::object::base::OF64;
pub use crate::parser::hir::SyntaxType; pub use crate::parser::hir::SyntaxType;
pub use crate::plugin::{serve_plugin, Plugin}; pub use crate::plugin::{serve_plugin, Plugin};
pub use crate::utils::{AbsolutePath, RelativePath}; pub use crate::utils::{AbsoluteFile, AbsolutePath, RelativePath};
pub use cli::cli; pub use cli::cli;
pub use errors::ShellError; pub use errors::ShellError;
pub use object::base::{Primitive, Value}; pub use object::base::{Primitive, Value};

View File

@ -16,10 +16,6 @@ macro_rules! trace_stream {
(target: $target:tt, $desc:tt = $expr:expr) => {{ (target: $target:tt, $desc:tt = $expr:expr) => {{
if log::log_enabled!(target: $target, log::Level::Trace) { if log::log_enabled!(target: $target, log::Level::Trace) {
use futures::stream::StreamExt; use futures::stream::StreamExt;
// Blocking is generally quite bad, but this is for debugging
// let mut local = futures::executor::LocalPool::new();
// let objects = local.run_until($expr.into_vec());
// let objects: Vec<_> = futures::executor::block_on($expr.into_vec());
let objects = $expr.values.inspect(|o| { let objects = $expr.values.inspect(|o| {
trace!(target: $target, "{} = {:#?}", $desc, o.debug()); trace!(target: $target, "{} = {:#?}", $desc, o.debug());

View File

@ -84,22 +84,6 @@ impl OutputStream {
} }
} }
impl std::ops::Try for OutputStream {
type Ok = OutputStream;
type Error = ShellError;
fn into_result(self) -> Result<Self::Ok, Self::Error> {
Ok(self)
}
fn from_error(v: Self::Error) -> Self {
OutputStream::one(Err(v))
}
fn from_ok(v: Self::Ok) -> Self {
v
}
}
impl Stream for OutputStream { impl Stream for OutputStream {
type Item = ReturnValue; type Item = ReturnValue;

View File

@ -1,7 +1,52 @@
use crate::errors::ShellError; use crate::errors::ShellError;
use std::fmt;
use std::ops::Div; use std::ops::Div;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
pub struct AbsoluteFile {
inner: PathBuf,
}
impl AbsoluteFile {
pub fn new(path: impl AsRef<Path>) -> AbsoluteFile {
let path = path.as_ref();
if !path.is_absolute() {
panic!(
"AbsoluteFile::new must take an absolute path :: {}",
path.display()
)
} else if path.is_dir() {
// At the moment, this is not an invariant, but rather a way to catch bugs
// in tests.
panic!(
"AbsoluteFile::new must not take a directory :: {}",
path.display()
)
} else {
AbsoluteFile {
inner: path.to_path_buf(),
}
}
}
pub fn dir(&self) -> AbsolutePath {
AbsolutePath::new(self.inner.parent().unwrap())
}
}
impl From<AbsoluteFile> for PathBuf {
fn from(file: AbsoluteFile) -> Self {
file.inner
}
}
impl fmt::Display for AbsoluteFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.inner.display())
}
}
pub struct AbsolutePath { pub struct AbsolutePath {
inner: PathBuf, inner: PathBuf,
} }
@ -20,6 +65,12 @@ impl AbsolutePath {
} }
} }
impl fmt::Display for AbsolutePath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.inner.display())
}
}
impl Div<&str> for &AbsolutePath { impl Div<&str> for &AbsolutePath {
type Output = AbsolutePath; type Output = AbsolutePath;
@ -72,6 +123,12 @@ impl<T: AsRef<str>> Div<T> for &RelativePath {
} }
} }
impl fmt::Display for RelativePath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.inner.display())
}
}
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Res { pub struct Res {
pub loc: PathBuf, pub loc: PathBuf,

View File

@ -4,8 +4,8 @@ use helpers::in_directory as cwd;
#[test] #[test]
fn cd_directory_not_found() { fn cd_directory_not_found() {
nu_error!(output, cwd("tests/fixtures"), "cd dir_that_does_not_exist"); let actual = nu_error!(cwd("tests/fixtures"), "cd dir_that_does_not_exist");
assert!(output.contains("dir_that_does_not_exist")); assert!(actual.contains("dir_that_does_not_exist"));
assert!(output.contains("directory not found")); assert!(actual.contains("directory not found"));
} }

View File

@ -1,75 +1,65 @@
mod helpers; mod helpers;
use h::{in_directory as cwd, Playground, Stub::*}; use helpers::{in_directory as cwd, dir_exists_at, file_exists_at, files_exist_at, Playground, Stub::*};
use helpers as h; use nu::AbsoluteFile;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
#[test] #[test]
fn copies_a_file() { fn copies_a_file() {
let sandbox = Playground::setup_for("cp_test_1").test_dir_name(); Playground::setup("cp_test_1", |dirs, _| {
let full_path = format!("{}/{}", Playground::root(), sandbox);
let expected_file = format!("{}/{}", full_path, "sample.ini");
nu!( nu!(
_output, cwd(dirs.root()),
cwd(&Playground::root()), "cp {} cp_test_1/sample.ini",
"cp ../formats/sample.ini cp_test_1/sample.ini" dirs.formats().join("sample.ini")
); );
assert!(h::file_exists_at(PathBuf::from(expected_file))); assert!(file_exists_at(dirs.test().join("sample.ini")));
});
} }
#[test] #[test]
fn copies_the_file_inside_directory_if_path_to_copy_is_directory() { fn copies_the_file_inside_directory_if_path_to_copy_is_directory() {
let sandbox = Playground::setup_for("cp_test_2").test_dir_name(); Playground::setup("cp_test_2", |dirs, _| {
let expected_file = AbsoluteFile::new(dirs.test().join("sample.ini"));
let full_path = format!("{}/{}", Playground::root(), sandbox);
let expected_file = format!("{}/{}", full_path, "sample.ini");
nu!( nu!(
_output, cwd(dirs.formats()),
cwd(&Playground::root()), "cp ../formats/sample.ini {}",
"cp ../formats/sample.ini cp_test_2" expected_file.dir()
); );
assert!(h::file_exists_at(PathBuf::from(expected_file))); assert!(file_exists_at(dirs.test().join("sample.ini")));
})
} }
#[test] #[test]
fn error_if_attempting_to_copy_a_directory_to_another_directory() { fn error_if_attempting_to_copy_a_directory_to_another_directory() {
Playground::setup_for("cp_test_3"); Playground::setup("cp_test_3", |dirs, _| {
let actual = nu_error!(dirs.formats(), "cp ../formats {}", dirs.test());
nu_error!(output, cwd(&Playground::root()), "cp ../formats cp_test_3"); assert!(actual.contains("../formats"));
assert!(actual.contains("is a directory (not copied)"));
assert!(output.contains("../formats")); });
assert!(output.contains("is a directory (not copied)"));
} }
#[test] #[test]
fn copies_the_directory_inside_directory_if_path_to_copy_is_directory_and_with_recursive_flag() { fn copies_the_directory_inside_directory_if_path_to_copy_is_directory_and_with_recursive_flag() {
let sandbox = Playground::setup_for("cp_test_4") Playground::setup("cp_test_4", |dirs, sandbox| {
sandbox
.within("originals") .within("originals")
.with_files(vec![ .with_files(vec![
EmptyFile("yehuda.txt"), EmptyFile("yehuda.txt"),
EmptyFile("jonathan.txt"), EmptyFile("jonathan.txt"),
EmptyFile("andres.txt"), EmptyFile("andres.txt"),
]) ])
.mkdir("expected") .mkdir("expected");
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let expected_dir = dirs.test().join("expected").join("originals");
let expected_dir = format!("{}/{}", full_path, "expected/originals");
nu!( nu!(cwd(dirs.test()), "cp originals expected --recursive");
_output,
cwd(&full_path),
"cp originals expected --recursive"
);
assert!(h::dir_exists_at(PathBuf::from(&expected_dir))); assert!(dir_exists_at(PathBuf::from(&expected_dir)));
assert!(h::files_exist_at( assert!(files_exist_at(
vec![ vec![
Path::new("yehuda.txt"), Path::new("yehuda.txt"),
Path::new("jonathan.txt"), Path::new("jonathan.txt"),
@ -77,6 +67,7 @@ fn copies_the_directory_inside_directory_if_path_to_copy_is_directory_and_with_r
], ],
PathBuf::from(&expected_dir) PathBuf::from(&expected_dir)
)); ));
})
} }
#[test] #[test]
@ -99,7 +90,8 @@ fn deep_copies_with_recursive_flag() {
originals/contributors/yehuda/defer-evaluation.txt originals/contributors/yehuda/defer-evaluation.txt
"#; "#;
let sandbox = Playground::setup_for("cp_test_5") Playground::setup("cp_test_5", |dirs, sandbox| {
sandbox
.within("originals") .within("originals")
.with_files(vec![EmptyFile("manifest.txt")]) .with_files(vec![EmptyFile("manifest.txt")])
.within("originals/contributors") .within("originals/contributors")
@ -114,49 +106,38 @@ fn deep_copies_with_recursive_flag() {
.with_files(vec![EmptyFile("coverage.txt"), EmptyFile("commands.txt")]) .with_files(vec![EmptyFile("coverage.txt"), EmptyFile("commands.txt")])
.within("originals/contributors/yehuda") .within("originals/contributors/yehuda")
.with_files(vec![EmptyFile("defer-evaluation.txt")]) .with_files(vec![EmptyFile("defer-evaluation.txt")])
.mkdir("expected") .mkdir("expected");
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let expected_dir = dirs.test().join("expected").join("originals");
let expected_dir = format!("{}/{}", full_path, "expected/originals");
let jonathans_expected_copied_dir = format!("{}/contributors/jonathan", expected_dir); let jonathans_expected_copied_dir = expected_dir.join("contributors").join("jonathan");
let andres_expected_copied_dir = format!("{}/contributors/andres", expected_dir); let andres_expected_copied_dir = expected_dir.join("contributors").join("andres");
let yehudas_expected_copied_dir = format!("{}/contributors/yehuda", expected_dir); let yehudas_expected_copied_dir = expected_dir.join("contributors").join("yehuda");
nu!( nu!(cwd(dirs.test()), "cp originals expected --recursive");
_output,
cwd(&full_path),
"cp originals expected --recursive"
);
assert!(h::dir_exists_at(PathBuf::from(&expected_dir))); assert!(dir_exists_at(PathBuf::from(&expected_dir)));
assert!(h::files_exist_at( assert!(files_exist_at(
vec![Path::new("errors.txt"), Path::new("multishells.txt")], vec![Path::new("errors.txt"), Path::new("multishells.txt")],
PathBuf::from(&jonathans_expected_copied_dir) PathBuf::from(&jonathans_expected_copied_dir)
)); ));
assert!(h::files_exist_at( assert!(files_exist_at(
vec![Path::new("coverage.txt"), Path::new("commands.txt")], vec![Path::new("coverage.txt"), Path::new("commands.txt")],
PathBuf::from(&andres_expected_copied_dir) PathBuf::from(&andres_expected_copied_dir)
)); ));
assert!(h::files_exist_at( assert!(files_exist_at(
vec![Path::new("defer-evaluation.txt")], vec![Path::new("defer-evaluation.txt")],
PathBuf::from(&yehudas_expected_copied_dir) PathBuf::from(&yehudas_expected_copied_dir)
)); ));
})
} }
#[test] #[test]
fn copies_using_path_with_wildcard() { fn copies_using_path_with_wildcard() {
let sandbox = Playground::setup_for("cp_test_6").test_dir_name(); Playground::setup("cp_test_6", |dirs, _| {
let expected_copies_path = format!("{}/{}", Playground::root(), sandbox); nu!(cwd(dirs.formats()), "cp ../formats/* {}", dirs.test());
nu!( assert!(files_exist_at(
_output,
cwd(&Playground::root()),
"cp ../formats/* cp_test_6"
);
assert!(h::files_exist_at(
vec![ vec![
Path::new("caco3_plastics.csv"), Path::new("caco3_plastics.csv"),
Path::new("cargo_sample.toml"), Path::new("cargo_sample.toml"),
@ -165,22 +146,17 @@ fn copies_using_path_with_wildcard() {
Path::new("sgml_description.json"), Path::new("sgml_description.json"),
Path::new("utf16.ini"), Path::new("utf16.ini"),
], ],
PathBuf::from(&expected_copies_path) dirs.test()
)); ));
})
} }
#[test] #[test]
fn copies_using_a_glob() { fn copies_using_a_glob() {
let sandbox = Playground::setup_for("cp_test_7").test_dir_name(); Playground::setup("cp_test_7", |dirs, _| {
let expected_copies_path = format!("{}/{}", Playground::root(), sandbox); nu!(cwd(dirs.formats()), "cp * {}", dirs.test());
nu!( assert!(files_exist_at(
_output,
cwd("tests/fixtures/formats"),
"cp * ../nuplayground/cp_test_7"
);
assert!(h::files_exist_at(
vec![ vec![
Path::new("caco3_plastics.csv"), Path::new("caco3_plastics.csv"),
Path::new("cargo_sample.toml"), Path::new("cargo_sample.toml"),
@ -189,6 +165,7 @@ fn copies_using_a_glob() {
Path::new("sgml_description.json"), Path::new("sgml_description.json"),
Path::new("utf16.ini"), Path::new("utf16.ini"),
], ],
PathBuf::from(&expected_copies_path) dirs.test()
)); ));
});
} }

View File

@ -6,7 +6,8 @@ use std::path::{Path, PathBuf};
#[test] #[test]
fn knows_the_filesystems_entered() { fn knows_the_filesystems_entered() {
let sandbox = Playground::setup_for("enter_filesystem_sessions_test") Playground::setup("enter_test_1", |dirs, sandbox| {
sandbox
.within("red_pill") .within("red_pill")
.with_files(vec![ .with_files(vec![
EmptyFile("andres.nu"), EmptyFile("andres.nu"),
@ -19,19 +20,15 @@ fn knows_the_filesystems_entered() {
EmptyFile("korn.nxt"), EmptyFile("korn.nxt"),
EmptyFile("powedsh.nxt"), EmptyFile("powedsh.nxt"),
]) ])
.mkdir("expected") .mkdir("expected");
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let red_pill_dir = dirs.test().join("red_pill");
let blue_pill_dir = dirs.test().join("blue_pill");
let red_pill_dir = format!("{}/{}", full_path, "red_pill"); let expected = dirs.test().join("expected");
let blue_pill_dir = format!("{}/{}", full_path, "blue_pill"); let expected_recycled = expected.join("recycled");
let expected = format!("{}/{}", full_path, "expected");
let expected_recycled = format!("{}/{}", expected, "recycled");
nu!( nu!(
_output, cwd(dirs.test()),
cwd(&full_path),
r#" r#"
enter expected enter expected
mkdir recycled mkdir recycled
@ -73,4 +70,5 @@ fn knows_the_filesystems_entered() {
], ],
PathBuf::from(&expected_recycled) PathBuf::from(&expected_recycled)
)); ));
})
} }

View File

@ -5,65 +5,86 @@ use helpers as h;
#[test] #[test]
fn ls_lists_regular_files() { fn ls_lists_regular_files() {
let sandbox = Playground::setup_for("ls_lists_files_test") Playground::setup("ls_test_1", |dirs, sandbox| {
sandbox
.with_files(vec![ .with_files(vec![
EmptyFile("yehuda.10.txt"), EmptyFile("yehuda.10.txt"),
EmptyFile("jonathan.10.txt"), EmptyFile("jonathan.10.txt"),
EmptyFile("andres.10.txt"), EmptyFile("andres.10.txt"),
]) ]);
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let actual = nu!(
cwd(dirs.test()), h::pipeline(
r#"
ls
| get name
| lines
| split-column "."
| get Column2
| str --to-int
| sum
| echo $it
"#
));
nu!( assert_eq!(actual, "30");
output, })
cwd(&full_path),
r#"ls | get name | lines | split-column "." | get Column2 | str --to-int | sum | echo $it"#
);
assert_eq!(output, "30");
} }
#[test] #[test]
fn ls_lists_regular_files_using_asterisk_wildcard() { fn ls_lists_regular_files_using_asterisk_wildcard() {
let sandbox = Playground::setup_for("ls_asterisk_wildcard_test") Playground::setup("ls_test_2", |dirs, sandbox| {
sandbox
.with_files(vec![ .with_files(vec![
EmptyFile("los.1.txt"), EmptyFile("los.1.txt"),
EmptyFile("tres.1.txt"), EmptyFile("tres.1.txt"),
EmptyFile("amigos.1.txt"), EmptyFile("amigos.1.txt"),
EmptyFile("arepas.1.clu"), EmptyFile("arepas.1.clu"),
]) ]);
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let actual = nu!(
cwd(dirs.test()), h::pipeline(
r#"
ls *.txt
| get name
| lines
| split-column "."
| get Column2
| str --to-int
| sum
| echo $it
"#
));
nu!( assert_eq!(actual, "3");
output, })
cwd(&full_path),
r#"ls *.txt | get name | lines| split-column "." | get Column2 | str --to-int | sum | echo $it"#
);
assert_eq!(output, "3");
} }
#[test] #[test]
fn ls_lists_regular_files_using_question_mark_wildcard() { fn ls_lists_regular_files_using_question_mark_wildcard() {
let sandbox = Playground::setup_for("ls_question_mark_wildcard_test") Playground::setup("ls_test_3", |dirs, sandbox| {
sandbox
.with_files(vec![ .with_files(vec![
EmptyFile("yehuda.10.txt"), EmptyFile("yehuda.10.txt"),
EmptyFile("jonathan.10.txt"), EmptyFile("jonathan.10.txt"),
EmptyFile("andres.10.txt"), EmptyFile("andres.10.txt"),
EmptyFile("chicken_not_to_be_picked_up.100.txt"), EmptyFile("chicken_not_to_be_picked_up.100.txt"),
]) ]);
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let actual = nu!(
cwd(dirs.test()), h::pipeline(
r#"
ls *.??.txt
| get name
| lines
| split-column "."
| get Column2
| str --to-int
| sum
| echo $it
"#
));
nu!( assert_eq!(actual, "30");
output, })
cwd(&full_path),
r#"ls *.??.txt | get name | lines| split-column "." | get Column2 | str --to-int | sum | echo $it"#
);
assert_eq!(output, "30");
} }

View File

@ -6,46 +6,35 @@ use std::path::{Path, PathBuf};
#[test] #[test]
fn creates_directory() { fn creates_directory() {
let sandbox = Playground::setup_for("mkdir_test_1").test_dir_name(); Playground::setup("mkdir_test_1", |dirs, _| {
nu!(cwd(dirs.test()), "mkdir my_new_directory");
let full_path = format!("{}/{}", Playground::root(), sandbox); let expected = dirs.test().join("my_new_directory");
nu!(_output, cwd(&full_path), "mkdir my_new_directory");
let mut expected = PathBuf::from(full_path);
expected.push("my_new_directory");
assert!(h::dir_exists_at(expected)); assert!(h::dir_exists_at(expected));
})
} }
#[test] #[test]
fn accepts_and_creates_directories() { fn accepts_and_creates_directories() {
let sandbox = Playground::setup_for("mkdir_test_2").test_dir_name(); Playground::setup("mkdir_test_2", |dirs, _| {
nu!(cwd(dirs.test()), "mkdir dir_1 dir_2 dir_3");
let full_path = format!("{}/{}", Playground::root(), sandbox);
nu!(_output, cwd(&full_path), "mkdir dir_1 dir_2 dir_3");
assert!(h::files_exist_at( assert!(h::files_exist_at(
vec![Path::new("dir_1"), Path::new("dir_2"), Path::new("dir_3")], vec![Path::new("dir_1"), Path::new("dir_2"), Path::new("dir_3")],
PathBuf::from(&full_path) dirs.test()
)); ));
})
} }
#[test] #[test]
fn creates_intermediary_directories() { fn creates_intermediary_directories() {
let sandbox = Playground::setup_for("mkdir_test_3").test_dir_name(); Playground::setup("mkdir_test_3", |dirs, _| {
nu!(cwd(dirs.test()), "mkdir some_folder/another/deeper_one");
let full_path = format!("{}/{}", Playground::root(), sandbox); let mut expected = PathBuf::from(dirs.test());
nu!(
_output,
cwd(&full_path),
"mkdir some_folder/another/deeper_one"
);
let mut expected = PathBuf::from(full_path);
expected.push("some_folder/another/deeper_one"); expected.push("some_folder/another/deeper_one");
assert!(h::dir_exists_at(expected)); assert!(h::dir_exists_at(expected));
})
} }

View File

@ -3,125 +3,120 @@ mod helpers;
use h::{in_directory as cwd, Playground, Stub::*}; use h::{in_directory as cwd, Playground, Stub::*};
use helpers as h; use helpers as h;
use std::path::{Path, PathBuf};
#[test] #[test]
fn moves_a_file() { fn moves_a_file() {
let sandbox = Playground::setup_for("mv_test_1") Playground::setup("mv_test_1", |dirs, sandbox| {
sandbox
.with_files(vec![EmptyFile("andres.txt")]) .with_files(vec![EmptyFile("andres.txt")])
.mkdir("expected") .mkdir("expected");
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let original = dirs.test().join("andres.txt");
let original = format!("{}/{}", full_path, "andres.txt"); let expected = dirs.test().join("expected/yehuda.txt");
let expected = format!("{}/{}", full_path, "expected/yehuda.txt");
nu!( nu!(cwd(dirs.test()), "mv andres.txt expected/yehuda.txt");
_output,
cwd(&full_path),
"mv andres.txt expected/yehuda.txt"
);
assert!(!h::file_exists_at(PathBuf::from(original))); assert!(!h::file_exists_at(original));
assert!(h::file_exists_at(PathBuf::from(expected))); assert!(h::file_exists_at(expected));
})
} }
#[test] #[test]
fn overwrites_if_moving_to_existing_file() { fn overwrites_if_moving_to_existing_file() {
let sandbox = Playground::setup_for("mv_test_2") Playground::setup("mv_test_2", |dirs, sandbox| {
.with_files(vec![EmptyFile("andres.txt"), EmptyFile("jonathan.txt")]) sandbox
.test_dir_name(); .with_files(vec![
EmptyFile("andres.txt"),
EmptyFile("jonathan.txt")
]);
let full_path = format!("{}/{}", Playground::root(), sandbox); let original = dirs.test().join("andres.txt");
let original = format!("{}/{}", full_path, "andres.txt"); let expected = dirs.test().join("jonathan.txt");
let expected = format!("{}/{}", full_path, "jonathan.txt");
nu!(_output, cwd(&full_path), "mv andres.txt jonathan.txt"); nu!(cwd(dirs.test()), "mv andres.txt jonathan.txt");
assert!(!h::file_exists_at(PathBuf::from(original))); assert!(!h::file_exists_at(original));
assert!(h::file_exists_at(PathBuf::from(expected))); assert!(h::file_exists_at(expected));
})
} }
#[test] #[test]
fn moves_a_directory() { fn moves_a_directory() {
let sandbox = Playground::setup_for("mv_test_3") Playground::setup("mv_test_3", |dirs, sandbox| {
.mkdir("empty_dir") sandbox.mkdir("empty_dir");
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let original_dir = dirs.test().join("empty_dir");
let original_dir = format!("{}/{}", full_path, "empty_dir"); let expected = dirs.test().join("renamed_dir");
let expected = format!("{}/{}", full_path, "renamed_dir");
nu!(_output, cwd(&full_path), "mv empty_dir renamed_dir"); nu!(cwd(dirs.test()), "mv empty_dir renamed_dir");
assert!(!h::dir_exists_at(PathBuf::from(original_dir))); assert!(!h::dir_exists_at(original_dir));
assert!(h::dir_exists_at(PathBuf::from(expected))); assert!(h::dir_exists_at(expected));
})
} }
#[test] #[test]
fn moves_the_file_inside_directory_if_path_to_move_is_existing_directory() { fn moves_the_file_inside_directory_if_path_to_move_is_existing_directory() {
let sandbox = Playground::setup_for("mv_test_4") Playground::setup("mv_test_4", |dirs, sandbox| {
sandbox
.with_files(vec![EmptyFile("jonathan.txt")]) .with_files(vec![EmptyFile("jonathan.txt")])
.mkdir("expected") .mkdir("expected");
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let original_dir = dirs.test().join("jonathan.txt");
let original_dir = format!("{}/{}", full_path, "jonathan.txt"); let expected = dirs.test().join("expected/jonathan.txt");
let expected = format!("{}/{}", full_path, "expected/jonathan.txt");
nu!(_output, cwd(&full_path), "mv jonathan.txt expected"); nu!(dirs.test(), "mv jonathan.txt expected");
assert!(!h::file_exists_at(PathBuf::from(original_dir))); assert!(!h::file_exists_at(original_dir));
assert!(h::file_exists_at(PathBuf::from(expected))); assert!(h::file_exists_at(expected));
})
} }
#[test] #[test]
fn moves_the_directory_inside_directory_if_path_to_move_is_existing_directory() { fn moves_the_directory_inside_directory_if_path_to_move_is_existing_directory() {
let sandbox = Playground::setup_for("mv_test_5") Playground::setup("mv_test_5", |dirs, sandbox| {
sandbox
.within("contributors") .within("contributors")
.with_files(vec![EmptyFile("jonathan.txt")]) .with_files(vec![EmptyFile("jonathan.txt")])
.mkdir("expected") .mkdir("expected");
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let original_dir = dirs.test().join("contributors");
let original_dir = format!("{}/{}", full_path, "contributors"); let expected = dirs.test().join("expected/contributors");
let expected = format!("{}/{}", full_path, "expected/contributors");
nu!(_output, cwd(&full_path), "mv contributors expected"); nu!(dirs.test(), "mv contributors expected");
assert!(!h::dir_exists_at(PathBuf::from(original_dir))); assert!(!h::dir_exists_at(original_dir));
assert!(h::file_exists_at(PathBuf::from(expected))); assert!(h::file_exists_at(expected));
})
} }
#[test] #[test]
fn moves_the_directory_inside_directory_if_path_to_move_is_nonexistent_directory() { fn moves_the_directory_inside_directory_if_path_to_move_is_nonexistent_directory() {
let sandbox = Playground::setup_for("mv_test_6") Playground::setup("mv_test_6", |dirs, sandbox| {
sandbox
.within("contributors") .within("contributors")
.with_files(vec![EmptyFile("jonathan.txt")]) .with_files(vec![EmptyFile("jonathan.txt")])
.mkdir("expected") .mkdir("expected");
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let original_dir = dirs.test().join("contributors");
let original_dir = format!("{}/{}", full_path, "contributors");
nu!( nu!(
_output, cwd(dirs.test()),
cwd(&full_path),
"mv contributors expected/this_dir_exists_now/los_tres_amigos" "mv contributors expected/this_dir_exists_now/los_tres_amigos"
); );
let expected = format!( let expected = dirs
"{}/{}", .test()
full_path, "expected/this_dir_exists_now/los_tres_amigos" .join("expected/this_dir_exists_now/los_tres_amigos");
);
assert!(!h::dir_exists_at(PathBuf::from(original_dir))); assert!(!h::dir_exists_at(original_dir));
assert!(h::file_exists_at(PathBuf::from(expected))); assert!(h::file_exists_at(expected));
})
} }
#[test] #[test]
fn moves_using_path_with_wildcard() { fn moves_using_path_with_wildcard() {
let sandbox = Playground::setup_for("mv_test_7") Playground::setup("mv_test_7", |dirs, sandbox| {
sandbox
.within("originals") .within("originals")
.with_files(vec![ .with_files(vec![
EmptyFile("andres.ini"), EmptyFile("andres.ini"),
@ -132,56 +127,46 @@ fn moves_using_path_with_wildcard() {
EmptyFile("sgml_description.json"), EmptyFile("sgml_description.json"),
EmptyFile("sample.ini"), EmptyFile("sample.ini"),
EmptyFile("utf16.ini"), EmptyFile("utf16.ini"),
EmptyFile("yehuda.ini"), EmptyFile("yehuda.ini")
]) ])
.mkdir("work_dir") .mkdir("work_dir")
.mkdir("expected") .mkdir("expected");
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let work_dir = dirs.test().join("work_dir");
let work_dir = format!("{}/{}", full_path, "work_dir"); let expected = dirs.test().join("expected");
let expected_copies_path = format!("{}/{}", full_path, "expected");
nu!(_output, cwd(&work_dir), "mv ../originals/*.ini ../expected"); nu!(cwd(work_dir), "mv ../originals/*.ini ../expected");
assert!(h::files_exist_at( assert!(h::files_exist_at(
vec![ vec!["yehuda.ini", "jonathan.ini", "sample.ini", "andres.ini",],
Path::new("yehuda.ini"), expected
Path::new("jonathan.ini"),
Path::new("sample.ini"),
Path::new("andres.ini"),
],
PathBuf::from(&expected_copies_path)
)); ));
})
} }
#[test] #[test]
fn moves_using_a_glob() { fn moves_using_a_glob() {
let sandbox = Playground::setup_for("mv_test_8") Playground::setup("mv_test_8", |dirs, sandbox| {
sandbox
.within("meals") .within("meals")
.with_files(vec![ .with_files(vec![
EmptyFile("arepa.txt"), EmptyFile("arepa.txt"),
EmptyFile("empanada.txt"), EmptyFile("empanada.txt"),
EmptyFile("taquiza.txt"), EmptyFile("taquiza.txt")
]) ])
.mkdir("work_dir") .mkdir("work_dir")
.mkdir("expected") .mkdir("expected");
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let meal_dir = dirs.test().join("meals");
let meal_dir = format!("{}/{}", full_path, "meals"); let work_dir = dirs.test().join("work_dir");
let work_dir = format!("{}/{}", full_path, "work_dir"); let expected = dirs.test().join("expected");
let expected_copies_path = format!("{}/{}", full_path, "expected");
nu!(_output, cwd(&work_dir), "mv ../meals/* ../expected"); nu!(cwd(work_dir), "mv ../meals/* ../expected");
assert!(h::dir_exists_at(PathBuf::from(meal_dir))); assert!(h::dir_exists_at(meal_dir));
assert!(h::files_exist_at( assert!(h::files_exist_at(
vec![ vec!["arepa.txt", "empanada.txt", "taquiza.txt",],
Path::new("arepa.txt"), expected
Path::new("empanada.txt"),
Path::new("taquiza.txt"),
],
PathBuf::from(&expected_copies_path)
)); ));
})
} }

View File

@ -1,114 +1,126 @@
mod helpers; mod helpers;
use helpers::{in_directory as cwd, Playground, Stub::*}; use helpers::{in_directory as cwd, Playground, Stub::*};
use helpers as h;
#[test] #[test]
fn recognizes_csv() { fn recognizes_csv() {
Playground::setup_for("open_recognizes_csv_test").with_files(vec![FileWithContentToBeTrimmed( Playground::setup("open_test_1", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContentToBeTrimmed(
"nu.zion.csv", "nu.zion.csv",
r#" r#"
author,lang,source author,lang,source
Jonathan Turner,Rust,New Zealand Jonathan Turner,Rust,New Zealand
Andres N. Robalino,Rust,Ecuador Andres N. Robalino,Rust,Ecuador
Yehuda Katz,Rust,Estados Unidos Yehuda Katz,Rust,Estados Unidos
"#, "#
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()), h::pipeline(
cwd("tests/fixtures/nuplayground/open_recognizes_csv_test"), r#"
r#"open nu.zion.csv | where author == "Andres N. Robalino" | get source | echo $it"# open nu.zion.csv
); | where author == "Andres N. Robalino"
| get source
| echo $it
"#
));
assert_eq!(output, "Ecuador"); assert_eq!(actual, "Ecuador");
})
} }
#[test] #[test]
fn open_can_parse_bson_1() { fn open_can_parse_bson_1() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open sample.bson | get root | nth 0 | get b | echo $it" "open sample.bson | get root | nth 0 | get b | echo $it"
); );
assert_eq!(output, "hello"); assert_eq!(actual, "hello");
} }
#[test] #[test]
fn open_can_parse_bson_2() { fn open_can_parse_bson_2() {
nu!( let actual = nu!(
output, cwd("tests/fixtures/formats"), h::pipeline(
cwd("tests/fixtures/formats"), r#"
"open sample.bson | get root | nth 6 | get b | get '$binary_subtype' | echo $it " open sample.bson
); | get root
| nth 6
| get b
| get '$binary_subtype'
| echo $it
"#
));
assert_eq!(output, "function"); assert_eq!(actual, "function");
} }
#[test] #[test]
fn open_can_parse_toml() { fn open_can_parse_toml() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open cargo_sample.toml | get package.edition | echo $it" "open cargo_sample.toml | get package.edition | echo $it"
); );
assert_eq!(output, "2018"); assert_eq!(actual, "2018");
} }
#[test] #[test]
fn open_can_parse_json() { fn open_can_parse_json() {
nu!(output, let actual = nu!(
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"), h::pipeline(
"open sgml_description.json | get glossary.GlossDiv.GlossList.GlossEntry.GlossSee | echo $it" r#"
); open sgml_description.json
| get glossary.GlossDiv.GlossList.GlossEntry.GlossSee
| echo $it
"#
));
assert_eq!(output, "markup") assert_eq!(actual, "markup")
} }
#[test] #[test]
fn open_can_parse_xml() { fn open_can_parse_xml() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open jonathan.xml | get rss.channel.item.link | echo $it" "open jonathan.xml | get rss.channel.item.link | echo $it"
); );
assert_eq!( assert_eq!(
output, actual,
"http://www.jonathanturner.org/2015/10/off-to-new-adventures.html" "http://www.jonathanturner.org/2015/10/off-to-new-adventures.html"
) )
} }
#[test] #[test]
fn open_can_parse_ini() { fn open_can_parse_ini() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open sample.ini | get SectionOne.integer | echo $it" "open sample.ini | get SectionOne.integer | echo $it"
); );
assert_eq!(output, "1234") assert_eq!(actual, "1234")
} }
#[test] #[test]
fn open_can_parse_utf16_ini() { fn open_can_parse_utf16_ini() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open utf16.ini | get .ShellClassInfo | get IconIndex | echo $it" "open utf16.ini | get .ShellClassInfo | get IconIndex | echo $it"
); );
assert_eq!(output, "-236") assert_eq!(actual, "-236")
} }
#[test] #[test]
fn errors_if_file_not_found() { fn errors_if_file_not_found() {
nu_error!( let actual = nu_error!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open i_dont_exist.txt | echo $it" "open i_dont_exist.txt | echo $it"
); );
assert!(output.contains("File could not be opened")); assert!(actual.contains("File could not be opened"));
} }

View File

@ -2,38 +2,31 @@ mod helpers;
use h::{in_directory as cwd, Playground, Stub::*}; use h::{in_directory as cwd, Playground, Stub::*};
use helpers as h; use helpers as h;
use std::path::{Path, PathBuf};
#[test] #[test]
fn rm_removes_a_file() { fn rm_removes_a_file() {
let sandbox = Playground::setup_for("rm_regular_file_test") Playground::setup("rm_test_1", |dirs, sandbox| {
.with_files(vec![EmptyFile("i_will_be_deleted.txt")]) sandbox
.test_dir_name(); .with_files(vec![EmptyFile("i_will_be_deleted.txt")
]);
nu!( nu!(cwd(dirs.root()), "rm rm_test_1/i_will_be_deleted.txt");
_output,
cwd(&Playground::root()),
"rm rm_regular_file_test/i_will_be_deleted.txt"
);
let path = &format!( let path = dirs.test().join("i_will_be_deleted.txt");
"{}/{}/{}",
Playground::root(),
sandbox,
"i_will_be_deleted.txt"
);
assert!(!h::file_exists_at(PathBuf::from(path))); assert!(!h::file_exists_at(path));
})
} }
#[test] #[test]
fn rm_removes_files_with_wildcard() { fn rm_removes_files_with_wildcard() {
let sandbox = Playground::setup_for("rm_wildcard_test_1") Playground::setup("rm_test_2", |dirs, sandbox| {
sandbox
.within("src") .within("src")
.with_files(vec![ .with_files(vec![
EmptyFile("cli.rs"), EmptyFile("cli.rs"),
EmptyFile("lib.rs"), EmptyFile("lib.rs"),
EmptyFile("prelude.rs"), EmptyFile("prelude.rs")
]) ])
.within("src/parser") .within("src/parser")
.with_files(vec![EmptyFile("parse.rs"), EmptyFile("parser.rs")]) .with_files(vec![EmptyFile("parse.rs"), EmptyFile("parser.rs")])
@ -42,41 +35,36 @@ fn rm_removes_files_with_wildcard() {
.within("src/parser/hir") .within("src/parser/hir")
.with_files(vec![ .with_files(vec![
EmptyFile("baseline_parse.rs"), EmptyFile("baseline_parse.rs"),
EmptyFile("baseline_parse_tokens.rs"), EmptyFile("baseline_parse_tokens.rs")
]) ]);
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); nu!(cwd(dirs.test()), r#"rm "src/*/*/*.rs""#);
nu!(
_output,
cwd("tests/fixtures/nuplayground/rm_wildcard_test_1"),
r#"rm "src/*/*/*.rs""#
);
assert!(!h::files_exist_at( assert!(!h::files_exist_at(
vec![ vec![
Path::new("src/parser/parse/token_tree.rs"), "src/parser/parse/token_tree.rs",
Path::new("src/parser/hir/baseline_parse.rs"), "src/parser/hir/baseline_parse.rs",
Path::new("src/parser/hir/baseline_parse_tokens.rs") "src/parser/hir/baseline_parse_tokens.rs"
], ],
PathBuf::from(&full_path) dirs.test()
)); ));
assert_eq!( assert_eq!(
Playground::glob_vec(&format!("{}/src/*/*/*.rs", &full_path)), Playground::glob_vec(&format!("{}/src/*/*/*.rs", dirs.test().display())),
Vec::<PathBuf>::new() Vec::<std::path::PathBuf>::new()
); );
})
} }
#[test] #[test]
fn rm_removes_deeply_nested_directories_with_wildcard_and_recursive_flag() { fn rm_removes_deeply_nested_directories_with_wildcard_and_recursive_flag() {
let sandbox = Playground::setup_for("rm_wildcard_test_2") Playground::setup("rm_test_3", |dirs, sandbox| {
sandbox
.within("src") .within("src")
.with_files(vec![ .with_files(vec![
EmptyFile("cli.rs"), EmptyFile("cli.rs"),
EmptyFile("lib.rs"), EmptyFile("lib.rs"),
EmptyFile("prelude.rs"), EmptyFile("prelude.rs")
]) ])
.within("src/parser") .within("src/parser")
.with_files(vec![EmptyFile("parse.rs"), EmptyFile("parser.rs")]) .with_files(vec![EmptyFile("parse.rs"), EmptyFile("parser.rs")])
@ -85,88 +73,74 @@ fn rm_removes_deeply_nested_directories_with_wildcard_and_recursive_flag() {
.within("src/parser/hir") .within("src/parser/hir")
.with_files(vec![ .with_files(vec![
EmptyFile("baseline_parse.rs"), EmptyFile("baseline_parse.rs"),
EmptyFile("baseline_parse_tokens.rs"), EmptyFile("baseline_parse_tokens.rs")
]) ]);
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); nu!(cwd(dirs.test()), "rm src/* --recursive");
nu!(
_output,
cwd("tests/fixtures/nuplayground/rm_wildcard_test_2"),
"rm src/* --recursive"
);
assert!(!h::files_exist_at( assert!(!h::files_exist_at(
vec![Path::new("src/parser/parse"), Path::new("src/parser/hir"),], vec!["src/parser/parse", "src/parser/hir"],
PathBuf::from(&full_path) dirs.test()
)); ));
})
} }
#[test] #[test]
fn rm_removes_directory_contents_without_recursive_flag_if_empty() { fn rm_removes_directory_contents_without_recursive_flag_if_empty() {
let sandbox = Playground::setup_for("rm_directory_removal_recursively_test_1").test_dir_name(); Playground::setup("rm_test_4", |dirs, _| {
nu!(cwd(dirs.root()), "rm rm_test_4");
nu!( assert!(!h::file_exists_at(dirs.test()));
_output, })
cwd("tests/fixtures/nuplayground"),
"rm rm_directory_removal_recursively_test_1"
);
let expected = format!("{}/{}", Playground::root(), sandbox);
assert!(!h::file_exists_at(PathBuf::from(expected)));
} }
#[test] #[test]
fn rm_removes_directory_contents_with_recursive_flag() { fn rm_removes_directory_contents_with_recursive_flag() {
let sandbox = Playground::setup_for("rm_directory_removal_recursively_test_2") Playground::setup("rm_test_5", |dirs, sandbox| {
sandbox
.with_files(vec![ .with_files(vec![
EmptyFile("yehuda.txt"), EmptyFile("yehuda.txt"),
EmptyFile("jonathan.txt"), EmptyFile("jonathan.txt"),
EmptyFile("andres.txt"), EmptyFile("andres.txt")
]) ]);
.test_dir_name();
nu!( nu!(cwd(dirs.root()), "rm rm_test_5 --recursive");
_output,
cwd("tests/fixtures/nuplayground"),
"rm rm_directory_removal_recursively_test_2 --recursive"
);
let expected = format!("{}/{}", Playground::root(), sandbox); assert!(!h::file_exists_at(dirs.test()));
})
assert!(!h::file_exists_at(PathBuf::from(expected)));
} }
#[test] #[test]
fn rm_errors_if_attempting_to_delete_a_directory_with_content_without_recursive_flag() { fn rm_errors_if_attempting_to_delete_a_directory_with_content_without_recursive_flag() {
let sandbox = Playground::setup_for("rm_prevent_directory_removal_without_flag_test") Playground::setup("rm_test_6", |dirs, sandbox| {
.with_files(vec![EmptyFile("some_empty_file.txt")]) sandbox
.test_dir_name(); .with_files(vec![EmptyFile("some_empty_file.txt")
]);
let full_path = format!("{}/{}", Playground::root(), sandbox); let actual = nu_error!(
cwd(dirs.root()),
nu_error!( "rm rm_test_6"
output,
cwd(&Playground::root()),
"rm rm_prevent_directory_removal_without_flag_test"
); );
assert!(h::file_exists_at(PathBuf::from(full_path))); assert!(h::file_exists_at(dirs.test()));
assert!(output.contains("is a directory")); assert!(actual.contains("is a directory"));
})
} }
#[test] #[test]
fn rm_errors_if_attempting_to_delete_single_dot_as_argument() { fn rm_errors_if_attempting_to_delete_single_dot_as_argument() {
nu_error!(output, cwd(&Playground::root()), "rm ."); Playground::setup("rm_test_7", |dirs, _| {
let actual = nu_error!(cwd(dirs.root()), "rm .");
assert!(output.contains("may not be removed")); assert!(actual.contains("may not be removed"));
})
} }
#[test] #[test]
fn rm_errors_if_attempting_to_delete_two_dot_as_argument() { fn rm_errors_if_attempting_to_delete_two_dot_as_argument() {
nu_error!(output, cwd(&Playground::root()), "rm .."); Playground::setup("rm_test_8", |dirs, _| {
let actual = nu_error!(cwd(dirs.root()), "rm ..");
assert!(output.contains("may not be removed")); assert!(actual.contains("may not be removed"));
})
} }

View File

@ -5,18 +5,18 @@ use helpers as h;
#[test] #[test]
fn lines() { fn lines() {
nu!(output, let actual = nu!(
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
r#"open cargo_sample.toml --raw | lines | skip-while $it != "[dependencies]" | skip 1 | first 1 | split-column "=" | get Column1 | trim | echo $it"# r#"open cargo_sample.toml --raw | lines | skip-while $it != "[dependencies]" | skip 1 | first 1 | split-column "=" | get Column1 | trim | echo $it"#
); );
assert_eq!(output, "rustyline"); assert_eq!(actual, "rustyline");
} }
#[test] #[test]
fn save_figures_out_intelligently_where_to_write_out_with_metadata() { fn save_figures_out_intelligently_where_to_write_out_with_metadata() {
let sandbox = Playground::setup_for("save_smart_test") Playground::setup("save_test_1", |dirs, sandbox| {
.with_files(vec![FileWithContent( sandbox.with_files(vec![FileWithContent(
"cargo_sample.toml", "cargo_sample.toml",
r#" r#"
[package] [package]
@ -26,36 +26,33 @@ fn save_figures_out_intelligently_where_to_write_out_with_metadata() {
description = "A shell for the GitHub era" description = "A shell for the GitHub era"
license = "ISC" license = "ISC"
edition = "2018" edition = "2018"
"#, "#)
)]) ]);
.test_dir_name();
let full_path = format!("{}/{}", Playground::root(), sandbox); let subject_file = dirs.test().join("cargo_sample.toml");
let subject_file = format!("{}/{}", full_path, "cargo_sample.toml");
nu!( nu!(
_output, cwd(dirs.root()),
cwd(&Playground::root()), "open save_test_1/cargo_sample.toml | inc package.version --minor | save"
"open save_smart_test/cargo_sample.toml | inc package.version --minor | save"
); );
let actual = h::file_contents(&subject_file); let actual = h::file_contents(&subject_file);
assert!(actual.contains("0.2.0")); assert!(actual.contains("0.2.0"));
})
} }
#[test] #[test]
fn save_can_write_out_csv() { fn save_can_write_out_csv() {
let sandbox = Playground::setup_for("save_writes_out_csv_test").test_dir_name(); Playground::setup("save_test_2", |dirs, _| {
let expected_file = dirs.test().join("cargo_sample.csv");
let full_path = format!("{}/{}", Playground::root(), sandbox);
let expected_file = format!("{}/{}", full_path, "cargo_sample.csv");
nu!( nu!(
_output, dirs.root(),
cwd(&Playground::root()), "open {}/cargo_sample.toml | inc package.version --minor | get package | save save_test_2/cargo_sample.csv",
"open ../formats/cargo_sample.toml | inc package.version --minor | get package | save save_writes_out_csv_test/cargo_sample.csv" dirs.formats()
); );
let actual = h::file_contents(&expected_file); let actual = h::file_contents(expected_file);
assert!(actual.contains("[list list],A shell for the GitHub era,2018,ISC,nu,0.2.0")); assert!(actual.contains("[list list],A shell for the GitHub era,2018,ISC,nu,0.2.0"));
})
} }

View File

@ -4,7 +4,7 @@ use helpers::in_directory as cwd;
#[test] #[test]
fn external_command() { fn external_command() {
nu!(output, cwd("tests/fixtures"), "echo 1"); let actual = nu!(cwd("tests/fixtures"), "echo 1");
assert!(output.contains("1")); assert!(actual.contains("1"));
} }

View File

@ -5,131 +5,136 @@ use helpers as h;
#[test] #[test]
fn can_only_apply_one() { fn can_only_apply_one() {
nu_error!( let actual = nu_error!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open cargo_sample.toml | first 1 | inc package.version --major --minor" "open cargo_sample.toml | first 1 | inc package.version --major --minor"
); );
assert!(output.contains("Usage: inc field [--major|--minor|--patch]")); assert!(actual.contains("Usage: inc field [--major|--minor|--patch]"));
} }
#[test] #[test]
fn by_one_with_field_passed() { fn by_one_with_field_passed() {
Playground::setup_for("plugin_inc_by_one_with_field_passed_test").with_files(vec![ Playground::setup("plugin_inc_test_1", |dirs, sandbox| {
FileWithContent( sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[package] [package]
edition = "2018" edition = "2018"
"#, "#
), )]);
]);
nu!( let actual = nu!(
output, cwd(dirs.test()),
cwd("tests/fixtures/nuplayground/plugin_inc_by_one_with_field_passed_test"),
"open sample.toml | inc package.edition | get package.edition | echo $it" "open sample.toml | inc package.edition | get package.edition | echo $it"
); );
assert_eq!(output, "2019"); assert_eq!(actual, "2019");
})
} }
#[test] #[test]
fn by_one_with_no_field_passed() { fn by_one_with_no_field_passed() {
Playground::setup_for("plugin_inc_by_one_with_no_field_passed_test").with_files(vec![ Playground::setup("plugin_inc_test_2", |dirs, sandbox| {
FileWithContent( sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[package] [package]
contributors = "2" contributors = "2"
"#, "#
), )]);
]);
nu!( let actual = nu!(
output, cwd(dirs.test()),
cwd("tests/fixtures/nuplayground/plugin_inc_by_one_with_no_field_passed_test"),
"open sample.toml | get package.contributors | inc | echo $it" "open sample.toml | get package.contributors | inc | echo $it"
); );
assert_eq!(output, "3"); assert_eq!(actual, "3");
})
} }
#[test] #[test]
fn semversion_major_inc() { fn semversion_major_inc() {
Playground::setup_for("plugin_inc_major_semversion_test").with_files(vec![FileWithContent( Playground::setup("plugin_inc_test_3", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[package] [package]
version = "0.1.3" version = "0.1.3"
"#, "#
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()),
cwd("tests/fixtures/nuplayground/plugin_inc_major_semversion_test"),
"open sample.toml | inc package.version --major | get package.version | echo $it" "open sample.toml | inc package.version --major | get package.version | echo $it"
); );
assert_eq!(output, "1.0.0"); assert_eq!(actual, "1.0.0");
})
} }
#[test] #[test]
fn semversion_minor_inc() { fn semversion_minor_inc() {
Playground::setup_for("plugin_inc_minor_semversion_test").with_files(vec![FileWithContent( Playground::setup("plugin_inc_test_4", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[package] [package]
version = "0.1.3" version = "0.1.3"
"#, "#
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()),
cwd("tests/fixtures/nuplayground/plugin_inc_minor_semversion_test"),
"open sample.toml | inc package.version --minor | get package.version | echo $it" "open sample.toml | inc package.version --minor | get package.version | echo $it"
); );
assert_eq!(output, "0.2.0"); assert_eq!(actual, "0.2.0");
})
} }
#[test] #[test]
fn semversion_patch_inc() { fn semversion_patch_inc() {
Playground::setup_for("plugin_inc_patch_semversion_test").with_files(vec![FileWithContent( Playground::setup("plugin_inc_test_5", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[package] [package]
version = "0.1.3" version = "0.1.3"
"#, "#
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()),
cwd("tests/fixtures/nuplayground/plugin_inc_patch_semversion_test"),
"open sample.toml | inc package.version --patch | get package.version | echo $it" "open sample.toml | inc package.version --patch | get package.version | echo $it"
); );
assert_eq!(output, "0.1.4"); assert_eq!(actual, "0.1.4");
})
} }
#[test] #[test]
fn semversion_without_passing_field() { fn semversion_without_passing_field() {
Playground::setup_for("plugin_inc_semversion_without_passing_field_test").with_files(vec![ Playground::setup("plugin_inc_test_6", |dirs, sandbox| {
FileWithContent( sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[package] [package]
version = "0.1.3" version = "0.1.3"
"#, "#
), )]);
]);
nu!( let actual = nu!(
output, cwd(dirs.test()),
cwd("tests/fixtures/nuplayground/plugin_inc_semversion_without_passing_field_test"),
"open sample.toml | get package.version | inc --patch | echo $it" "open sample.toml | get package.version | inc --patch | echo $it"
); );
assert_eq!(output, "0.1.4"); assert_eq!(actual, "0.1.4");
})
} }

View File

@ -5,42 +5,42 @@ use helpers as h;
#[test] #[test]
fn can_only_apply_one() { fn can_only_apply_one() {
nu_error!( let actual = nu_error!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open caco3_plastics.csv | first 1 | str origin --downcase --upcase" "open caco3_plastics.csv | first 1 | str origin --downcase --upcase"
); );
assert!( assert!(
output.contains("Usage: str field [--downcase|--upcase|--to-int|--replace|--find-replace]") actual.contains("Usage: str field [--downcase|--upcase|--to-int|--replace|--find-replace]")
); );
} }
#[test] #[test]
fn acts_without_passing_field() { fn acts_without_passing_field() {
Playground::setup_for("plugin_str_acts_without_passing_field_test").with_files(vec![ Playground::setup("plugin_str_test_1", |dirs, sandbox| {
FileWithContent( sandbox.with_files(vec![FileWithContent(
"sample.yml", "sample.yml",
r#" r#"
environment: environment:
global: global:
PROJECT_NAME: nushell PROJECT_NAME: nushell
"#, "#,
), )]);
]);
nu!( let actual = nu!(
output, cwd(dirs.test()),
cwd("tests/fixtures/nuplayground/plugin_str_acts_without_passing_field_test"),
"open sample.yml | get environment.global.PROJECT_NAME | str --upcase | echo $it" "open sample.yml | get environment.global.PROJECT_NAME | str --upcase | echo $it"
); );
assert_eq!(output, "NUSHELL"); assert_eq!(actual, "NUSHELL");
})
} }
#[test] #[test]
fn downcases() { fn downcases() {
Playground::setup_for("plugin_str_downcases_test").with_files(vec![FileWithContent( Playground::setup("plugin_str_test_2", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[dependency] [dependency]
@ -48,18 +48,20 @@ fn downcases() {
"#, "#,
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()),
cwd("tests/fixtures/nuplayground/plugin_str_downcases_test"),
"open sample.toml | str dependency.name --downcase | get dependency.name | echo $it" "open sample.toml | str dependency.name --downcase | get dependency.name | echo $it"
); );
assert_eq!(output, "light"); assert_eq!(actual, "light");
})
} }
#[test] #[test]
fn upcases() { fn upcases() {
Playground::setup_for("plugin_str_upcases_test").with_files(vec![FileWithContent( Playground::setup("plugin_str_test_3", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[package] [package]
@ -67,29 +69,37 @@ fn upcases() {
"#, "#,
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()),
cwd("tests/fixtures/nuplayground/plugin_str_upcases_test"),
"open sample.toml | str package.name --upcase | get package.name | echo $it" "open sample.toml | str package.name --upcase | get package.name | echo $it"
); );
assert_eq!(output, "NUSHELL"); assert_eq!(actual, "NUSHELL");
})
} }
#[test] #[test]
fn converts_to_int() { fn converts_to_int() {
nu!( let actual = nu!(
output, cwd("tests/fixtures/formats"), h::pipeline(
cwd("tests/fixtures/formats"), r#"
"open caco3_plastics.csv | first 1 | str tariff_item --to-int | where tariff_item == 2509000000 | get tariff_item | echo $it" open caco3_plastics.csv
); | first 1
| str tariff_item --to-int
| where tariff_item == 2509000000
| get tariff_item
| echo $it
"#
));
assert_eq!(output, "2509000000"); assert_eq!(actual, "2509000000");
} }
#[test] #[test]
fn replaces() { fn replaces() {
Playground::setup_for("plugin_str_replaces_test").with_files(vec![FileWithContent( Playground::setup("plugin_str_test_4", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[package] [package]
@ -97,18 +107,25 @@ fn replaces() {
"#, "#,
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()), h::pipeline(
cwd("tests/fixtures/nuplayground/plugin_str_replaces_test"), r#"
"open sample.toml | str package.name --replace wykittenshell | get package.name | echo $it" open sample.toml
); | str package.name --replace wykittenshell
| get package.name
| echo $it
"#
));
assert_eq!(output, "wykittenshell"); assert_eq!(actual, "wykittenshell");
})
} }
#[test] #[test]
fn find_and_replaces() { fn find_and_replaces() {
Playground::setup_for("plugin_str_find_and_replaces_test").with_files(vec![FileWithContent( Playground::setup("plugin_str_test_5", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[fortune.teller] [fortune.teller]
@ -116,32 +133,42 @@ fn find_and_replaces() {
"#, "#,
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()), h::pipeline(
cwd("tests/fixtures/nuplayground/plugin_str_find_and_replaces_test"), r#"
r#"open sample.toml | str fortune.teller.phone --find-replace KATZ "5289" | get fortune.teller.phone | echo $it"# open sample.toml
); | str fortune.teller.phone --find-replace KATZ "5289"
| get fortune.teller.phone
| echo $it
"#
));
assert_eq!(output, "1-800-5289"); assert_eq!(actual, "1-800-5289");
})
} }
#[test] #[test]
fn find_and_replaces_without_passing_field() { fn find_and_replaces_without_passing_field() {
Playground::setup_for("plugin_str_find_and_replaces_without_passing_field_test").with_files( Playground::setup("plugin_str_test_6", |dirs, sandbox| {
vec![FileWithContent( sandbox
.with_files(vec![FileWithContent(
"sample.toml", "sample.toml",
r#" r#"
[fortune.teller] [fortune.teller]
phone = "1-800-KATZ" phone = "1-800-KATZ"
"#, "#,
)], )]);
);
nu!( let actual = nu!(
output, cwd(dirs.test()), h::pipeline(
cwd("tests/fixtures/nuplayground/plugin_str_find_and_replaces_without_passing_field_test"), r#"
r#"open sample.toml | get fortune.teller.phone | str --find-replace KATZ "5289" | echo $it"# open sample.toml
); | get fortune.teller.phone
| str --find-replace KATZ "5289"
| echo $it
"#
));
assert_eq!(output, "1-800-5289"); assert_eq!(actual, "1-800-5289");
})
} }

View File

@ -1,61 +1,83 @@
mod helpers; mod helpers;
use helpers::{in_directory as cwd, Playground, Stub::*}; use helpers::{in_directory as cwd, Playground, Stub::*};
use helpers as h;
#[test] #[test]
fn can_convert_table_to_csv_text_and_from_csv_text_back_into_table() { fn can_convert_table_to_csv_text_and_from_csv_text_back_into_table() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open caco3_plastics.csv | to-csv | from-csv | first 1 | get origin | echo $it" "open caco3_plastics.csv | to-csv | from-csv | first 1 | get origin | echo $it"
); );
assert_eq!(output, "SPAIN"); assert_eq!(actual, "SPAIN");
} }
#[test] #[test]
fn converts_structured_table_to_csv_text() { fn converts_structured_table_to_csv_text() {
Playground::setup_for("filter_to_csv_test_1").with_files(vec![FileWithContentToBeTrimmed( Playground::setup("filter_to_csv_test_1", |dirs, sandbox| {
"sample.txt", sandbox
.with_files(vec![FileWithContentToBeTrimmed(
"csv_text_sample.txt",
r#" r#"
importer,shipper,tariff_item,name,origin importer,shipper,tariff_item,name,origin
Plasticos Rival,Reverte,2509000000,Calcium carbonate,Spain Plasticos Rival,Reverte,2509000000,Calcium carbonate,Spain
Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia
"#, "#
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()), h::pipeline(
cwd("tests/fixtures/nuplayground/filter_to_csv_test_1"), r#"
r#"open sample.txt | lines | split-column "," a b c d origin | last 1 | to-csv | lines | nth 1 | echo "$it""# open csv_text_sample.txt
); | lines
| split-column "," a b c d origin
| last 1
| to-csv
| lines
| nth 1
| echo "$it"
"#
));
assert!(output.contains("Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia")); assert!(actual.contains("Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia"));
})
} }
#[test] #[test]
fn converts_structured_table_to_csv_text_skipping_headers_after_conversion() { fn converts_structured_table_to_csv_text_skipping_headers_after_conversion() {
Playground::setup_for("filter_to_csv_test_2").with_files(vec![FileWithContentToBeTrimmed( Playground::setup("filter_to_csv_test_2", |dirs, sandbox| {
"sample.txt", sandbox
.with_files(vec![FileWithContentToBeTrimmed(
"csv_text_sample.txt",
r#" r#"
importer,shipper,tariff_item,name,origin importer,shipper,tariff_item,name,origin
Plasticos Rival,Reverte,2509000000,Calcium carbonate,Spain Plasticos Rival,Reverte,2509000000,Calcium carbonate,Spain
Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia
"#, "#
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()), h::pipeline(
cwd("tests/fixtures/nuplayground/filter_to_csv_test_2"), r#"
r#"open sample.txt | lines | split-column "," a b c d origin | last 1 | to-csv --headerless | echo "$it""# open csv_text_sample.txt
); | lines
| split-column "," a b c d origin
| last 1
| to-csv --headerless
| echo "$it"
"#
));
assert!(output.contains("Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia")); assert!(actual.contains("Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia"));
})
} }
#[test] #[test]
fn converts_from_csv_text_to_structured_table() { fn converts_from_csv_text_to_structured_table() {
Playground::setup_for("filter_from_csv_test_1").with_files(vec![FileWithContentToBeTrimmed( Playground::setup("filter_from_csv_test_1", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContentToBeTrimmed(
"los_tres_amigos.txt", "los_tres_amigos.txt",
r#" r#"
first_name,last_name,rusty_luck first_name,last_name,rusty_luck
@ -65,18 +87,27 @@ fn converts_from_csv_text_to_structured_table() {
"#, "#,
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()), h::pipeline(
cwd("tests/fixtures/nuplayground/filter_from_csv_test_1"), r#"
"open los_tres_amigos.txt | from-csv | get rusty_luck | str --to-int | sum | echo $it" open los_tres_amigos.txt
); | from-csv
| get rusty_luck
| str --to-int
| sum
| echo $it
"#
));
assert_eq!(output, "3"); assert_eq!(actual, "3");
})
} }
#[test] #[test]
fn converts_from_csv_text_skipping_headers_to_structured_table() { fn converts_from_csv_text_skipping_headers_to_structured_table() {
Playground::setup_for("filter_from_csv_test_2").with_files(vec![FileWithContentToBeTrimmed( Playground::setup("filter_from_csv_test_2", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContentToBeTrimmed(
"los_tres_amigos.txt", "los_tres_amigos.txt",
r#" r#"
first_name,last_name,rusty_luck first_name,last_name,rusty_luck
@ -86,29 +117,43 @@ fn converts_from_csv_text_skipping_headers_to_structured_table() {
"#, "#,
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()), h::pipeline(
cwd("tests/fixtures/nuplayground/filter_from_csv_test_2"), r#"
"open los_tres_amigos.txt | from-csv --headerless | get Column3 | str --to-int | sum | echo $it" open los_tres_amigos.txt
); | from-csv --headerless
| get Column3
| str --to-int
| sum
| echo $it
"#
));
assert_eq!(output, "3"); assert_eq!(actual, "3");
})
} }
#[test] #[test]
fn can_convert_table_to_json_text_and_from_json_text_back_into_table() { fn can_convert_table_to_json_text_and_from_json_text_back_into_table() {
nu!( let actual = nu!(
output, cwd("tests/fixtures/formats"), h::pipeline(
cwd("tests/fixtures/formats"), r#"
"open sgml_description.json | to-json | from-json | get glossary.GlossDiv.GlossList.GlossEntry.GlossSee | echo $it" open sgml_description.json
); | to-json
| from-json
| get glossary.GlossDiv.GlossList.GlossEntry.GlossSee
| echo $it
"#
));
assert_eq!(output, "markup"); assert_eq!(actual, "markup");
} }
#[test] #[test]
fn converts_from_json_text_to_structured_table() { fn converts_from_json_text_to_structured_table() {
Playground::setup_for("filter_from_json_test_1").with_files(vec![FileWithContentToBeTrimmed( Playground::setup("filter_from_json_test_1", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContentToBeTrimmed(
"katz.txt", "katz.txt",
r#" r#"
{ {
@ -122,18 +167,21 @@ fn converts_from_json_text_to_structured_table() {
"#, "#,
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()),
cwd("tests/fixtures/nuplayground/filter_from_json_test_1"),
"open katz.txt | from-json | get katz | get rusty_luck | sum | echo $it" "open katz.txt | from-json | get katz | get rusty_luck | sum | echo $it"
); );
assert_eq!(output, "4"); assert_eq!(actual, "4");
})
} }
#[test] #[test]
fn converts_from_json_text_recognizing_objects_independendtly_to_structured_table() { fn converts_from_json_text_recognizing_objects_independendtly_to_structured_table() {
Playground::setup_for("filter_from_json_test_2").with_files(vec![FileWithContentToBeTrimmed( Playground::setup("filter_from_json_test_2", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContentToBeTrimmed(
"katz.txt", "katz.txt",
r#" r#"
{"name": "Yehuda", "rusty_luck": 1} {"name": "Yehuda", "rusty_luck": 1}
@ -143,18 +191,26 @@ fn converts_from_json_text_recognizing_objects_independendtly_to_structured_tabl
"#, "#,
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()), h::pipeline(
cwd("tests/fixtures/nuplayground/filter_from_json_test_2"), r#"
r#"open katz.txt | from-json --objects | where name == "GorbyPuff" | get rusty_luck | echo $it"# open katz.txt
); | from-json --objects
| where name == "GorbyPuff"
| get rusty_luck
| echo $it
"#
));
assert_eq!(output, "3"); assert_eq!(actual, "3");
})
} }
#[test] #[test]
fn converts_structured_table_to_json_text() { fn converts_structured_table_to_json_text() {
Playground::setup_for("filter_to_json_test_1").with_files(vec![FileWithContentToBeTrimmed( Playground::setup("filter_to_json_test", |dirs, sandbox| {
sandbox
.with_files(vec![FileWithContentToBeTrimmed(
"sample.txt", "sample.txt",
r#" r#"
JonAndrehudaTZ,3 JonAndrehudaTZ,3
@ -162,110 +218,143 @@ fn converts_structured_table_to_json_text() {
"#, "#,
)]); )]);
nu!( let actual = nu!(
output, cwd(dirs.test()), h::pipeline(
cwd("tests/fixtures/nuplayground/filter_to_json_test_1"), r#"
r#"open sample.txt | lines | split-column "," name luck | pick name | to-json | nth 0 | from-json | get name | echo $it"# open sample.txt
); | lines
| split-column "," name luck
| pick name
| to-json
| nth 0
| from-json
| get name
| echo $it
"#
));
assert_eq!(output, "JonAndrehudaTZ"); assert_eq!(actual, "JonAndrehudaTZ");
})
} }
#[test] #[test]
fn can_convert_json_text_to_bson_and_back_into_table() { fn can_convert_json_text_to_bson_and_back_into_table() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open sample.bson | to-bson | from-bson | get root | nth 1 | get b | echo $it" "open sample.bson | to-bson | from-bson | get root | nth 1 | get b | echo $it"
); );
assert_eq!(output, "whel"); assert_eq!(actual, "whel");
} }
#[test] #[test]
fn can_convert_table_to_toml_text_and_from_toml_text_back_into_table() { fn can_convert_table_to_toml_text_and_from_toml_text_back_into_table() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open cargo_sample.toml | to-toml | from-toml | get package.name | echo $it" "open cargo_sample.toml | to-toml | from-toml | get package.name | echo $it"
); );
assert_eq!(output, "nu"); assert_eq!(actual, "nu");
} }
#[test] #[test]
fn can_convert_table_to_yaml_text_and_from_yaml_text_back_into_table() { fn can_convert_table_to_yaml_text_and_from_yaml_text_back_into_table() {
nu!( let actual = nu!(
output, cwd("tests/fixtures/formats"), h::pipeline(
cwd("tests/fixtures/formats"), r#"
"open appveyor.yml | to-yaml | from-yaml | get environment.global.PROJECT_NAME | echo $it" open appveyor.yml
); | to-yaml
| from-yaml
| get environment.global.PROJECT_NAME
| echo $it
"#
));
assert_eq!(output, "nushell"); assert_eq!(actual, "nushell");
} }
#[test] #[test]
fn can_sort_by_column() { fn can_sort_by_column() {
nu!( let actual = nu!(
output, cwd("tests/fixtures/formats"), h::pipeline(
cwd("tests/fixtures/formats"), r#"
r#"open cargo_sample.toml --raw | lines | skip 1 | first 4 | split-column "=" | sort-by Column1 | skip 1 | first 1 | get Column1 | trim | echo $it"# open cargo_sample.toml --raw
); | lines
| skip 1
| first 4
| split-column "="
| sort-by Column1
| skip 1
| first 1
| get Column1
| trim
| echo $it
"#
));
assert_eq!(output, "description"); assert_eq!(actual, "description");
} }
#[test] #[test]
fn can_split_by_column() { fn can_split_by_column() {
nu!( let actual = nu!(
output, cwd("tests/fixtures/formats"), h::pipeline(
cwd("tests/fixtures/formats"), r#"
r#"open cargo_sample.toml --raw | lines | skip 1 | first 1 | split-column "=" | get Column1 | trim | echo $it"# open cargo_sample.toml --raw
); | lines
| skip 1
| first 1
| split-column "="
| get Column1
| trim
| echo $it
"#
));
assert_eq!(output, "name"); assert_eq!(actual, "name");
} }
#[test] #[test]
fn can_sum() { fn can_sum() {
nu!( let actual = nu!(
output, cwd("tests/fixtures/formats"), h::pipeline(
cwd("tests/fixtures/formats"), r#"
"open sgml_description.json | get glossary.GlossDiv.GlossList.GlossEntry.Sections | sum | echo $it" open sgml_description.json
); | get glossary.GlossDiv.GlossList.GlossEntry.Sections
| sum
| echo $it
"#
));
assert_eq!(output, "203") assert_eq!(actual, "203")
} }
#[test] #[test]
fn can_filter_by_unit_size_comparison() { fn can_filter_by_unit_size_comparison() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"ls | where size > 1kb | sort-by size | get name | skip 1 | trim | echo $it" "ls | where size > 1kb | sort-by size | get name | skip 1 | trim | echo $it"
); );
assert_eq!(output, "caco3_plastics.csv"); assert_eq!(actual, "caco3_plastics.csv");
} }
#[test] #[test]
fn can_get_last() { fn can_get_last() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"ls | sort-by name | last 1 | get name | trim | echo $it" "ls | sort-by name | last 1 | get name | trim | echo $it"
); );
assert_eq!(output, "utf16.ini"); assert_eq!(actual, "utf16.ini");
} }
#[test] #[test]
fn can_get_reverse_first() { fn can_get_reverse_first() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"ls | sort-by name | reverse | first 1 | get name | trim | echo $it" "ls | sort-by name | reverse | first 1 | get name | trim | echo $it"
); );
assert_eq!(output, "utf16.ini"); assert_eq!(actual, "utf16.ini");
} }

View File

@ -4,11 +4,63 @@ use glob::glob;
pub use std::path::Path; pub use std::path::Path;
pub use std::path::PathBuf; pub use std::path::PathBuf;
use getset::Getters;
use std::io::Read; use std::io::Read;
use tempfile::{tempdir, TempDir};
pub trait DisplayPath {
fn display_path(&self) -> String;
}
impl DisplayPath for PathBuf {
fn display_path(&self) -> String {
self.display().to_string()
}
}
impl DisplayPath for str {
fn display_path(&self) -> String {
self.to_string()
}
}
impl DisplayPath for &str {
fn display_path(&self) -> String {
self.to_string()
}
}
impl DisplayPath for String {
fn display_path(&self) -> String {
self.clone()
}
}
impl DisplayPath for &String {
fn display_path(&self) -> String {
self.to_string()
}
}
impl DisplayPath for nu::AbsolutePath {
fn display_path(&self) -> String {
self.to_string()
}
}
#[macro_export] #[macro_export]
macro_rules! nu { macro_rules! nu {
($out:ident, $cwd:expr, $commands:expr) => { ($cwd:expr, $path:expr, $($part:expr),*) => {{
use $crate::helpers::DisplayPath;
let path = format!($path, $(
$part.display_path()
),*);
nu!($cwd, &path)
}};
($cwd:expr, $path:expr) => {{
pub use std::error::Error; pub use std::error::Error;
pub use std::io::prelude::*; pub use std::io::prelude::*;
pub use std::process::{Command, Stdio}; pub use std::process::{Command, Stdio};
@ -18,7 +70,8 @@ macro_rules! nu {
cd {} cd {}
{} {}
exit", exit",
$cwd, $commands $crate::helpers::in_directory($cwd),
$crate::helpers::DisplayPath::display_path(&$path)
); );
let mut process = match Command::new(helpers::executable_path()) let mut process = match Command::new(helpers::executable_path())
@ -39,15 +92,27 @@ macro_rules! nu {
.wait_with_output() .wait_with_output()
.expect("couldn't read from stdout"); .expect("couldn't read from stdout");
let $out = String::from_utf8_lossy(&output.stdout); let out = String::from_utf8_lossy(&output.stdout);
let $out = $out.replace("\r\n", ""); let out = out.replace("\r\n", "");
let $out = $out.replace("\n", ""); let out = out.replace("\n", "");
}; out
}};
} }
#[macro_export] #[macro_export]
macro_rules! nu_error { macro_rules! nu_error {
($out:ident, $cwd:expr, $commands:expr) => { ($cwd:expr, $path:expr, $($part:expr),*) => {{
use $crate::helpers::DisplayPath;
let path = format!($path, $(
$part.display_path()
),*);
nu_error!($cwd, &path)
}};
($cwd:expr, $commands:expr) => {{
use std::io::prelude::*; use std::io::prelude::*;
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
@ -56,7 +121,7 @@ macro_rules! nu_error {
cd {} cd {}
{} {}
exit", exit",
$cwd, $commands $crate::helpers::in_directory($cwd), $commands
); );
let mut process = Command::new(helpers::executable_path()) let mut process = Command::new(helpers::executable_path())
@ -73,8 +138,11 @@ macro_rules! nu_error {
let output = process let output = process
.wait_with_output() .wait_with_output()
.expect("couldn't read from stderr"); .expect("couldn't read from stderr");
let $out = String::from_utf8_lossy(&output.stderr);
}; let out = String::from_utf8_lossy(&output.stderr);
out.into_owned()
}};
} }
pub enum Stub<'a> { pub enum Stub<'a> {
@ -84,26 +152,38 @@ pub enum Stub<'a> {
} }
pub struct Playground { pub struct Playground {
root: TempDir,
tests: String, tests: String,
cwd: PathBuf, cwd: PathBuf,
} }
impl Playground { #[derive(Getters)]
pub fn root() -> String { #[get = "pub"]
String::from("tests/fixtures/nuplayground") pub struct Dirs {
} pub root: PathBuf,
pub test: PathBuf,
pub fixtures: PathBuf,
}
pub fn test_dir_name(&self) -> String { impl Dirs {
self.tests.clone() pub fn formats(&self) -> PathBuf {
PathBuf::from(self.fixtures.join("formats"))
}
}
impl Playground {
pub fn root(&self) -> &Path {
self.root.path()
} }
pub fn back_to_playground(&mut self) -> &mut Self { pub fn back_to_playground(&mut self) -> &mut Self {
self.cwd = PathBuf::from([Playground::root(), self.tests.clone()].join("/")); self.cwd = PathBuf::from(self.root()).join(self.tests.clone());
self self
} }
pub fn setup_for(topic: &str) -> Playground { pub fn setup(topic: &str, block: impl FnOnce(Dirs, &mut Playground)) {
let nuplay_dir = format!("{}/{}", Playground::root(), topic); let root = tempdir().expect("Couldn't create a tempdir");
let nuplay_dir = root.path().join(topic);
if PathBuf::from(&nuplay_dir).exists() { if PathBuf::from(&nuplay_dir).exists() {
std::fs::remove_dir_all(PathBuf::from(&nuplay_dir)).expect("can not remove directory"); std::fs::remove_dir_all(PathBuf::from(&nuplay_dir)).expect("can not remove directory");
@ -111,10 +191,41 @@ impl Playground {
std::fs::create_dir(PathBuf::from(&nuplay_dir)).expect("can not create directory"); std::fs::create_dir(PathBuf::from(&nuplay_dir)).expect("can not create directory");
Playground { let mut playground = Playground {
root: root,
tests: topic.to_string(), tests: topic.to_string(),
cwd: PathBuf::from([Playground::root(), topic.to_string()].join("/")), cwd: nuplay_dir,
} };
let project_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let playground_root = playground.root.path();
let fixtures = project_root.join(file!());
let fixtures = fixtures
.parent()
.expect("Couldn't find the fixtures directory")
.parent()
.expect("Couldn't find the fixtures directory")
.join("fixtures");
let fixtures = dunce::canonicalize(fixtures.clone()).expect(&format!(
"Couldn't canonicalize fixtures path {}",
fixtures.display()
));
let test =
dunce::canonicalize(PathBuf::from(playground_root.join(topic))).expect(&format!(
"Couldn't canonicalize test path {}",
playground_root.join(topic).display()
));
let dirs = Dirs {
root: PathBuf::from(playground_root),
test,
fixtures,
};
block(dirs, &mut playground);
} }
pub fn mkdir(&mut self, directory: &str) -> &mut Self { pub fn mkdir(&mut self, directory: &str) -> &mut Self {
@ -180,8 +291,8 @@ impl Playground {
} }
} }
pub fn file_contents(full_path: &str) -> String { pub fn file_contents(full_path: impl AsRef<Path>) -> String {
let mut file = std::fs::File::open(full_path).expect("can not open file"); let mut file = std::fs::File::open(full_path.as_ref()).expect("can not open file");
let mut contents = String::new(); let mut contents = String::new();
file.read_to_string(&mut contents) file.read_to_string(&mut contents)
.expect("can not read file"); .expect("can not read file");
@ -226,20 +337,20 @@ pub fn copy_file_to(source: &str, destination: &str) {
std::fs::copy(source, destination).expect("can not copy file"); std::fs::copy(source, destination).expect("can not copy file");
} }
pub fn files_exist_at(files: Vec<&Path>, path: PathBuf) -> bool { pub fn files_exist_at(files: Vec<impl AsRef<Path>>, path: impl AsRef<Path>) -> bool {
files.iter().all(|f| { files.iter().all(|f| {
let mut loc = path.clone(); let mut loc = PathBuf::from(path.as_ref());
loc.push(f); loc.push(f);
loc.exists() loc.exists()
}) })
} }
pub fn file_exists_at(path: PathBuf) -> bool { pub fn file_exists_at(path: impl AsRef<Path>) -> bool {
path.exists() path.as_ref().exists()
} }
pub fn dir_exists_at(path: PathBuf) -> bool { pub fn dir_exists_at(path: impl AsRef<Path>) -> bool {
path.exists() path.as_ref().exists()
} }
pub fn delete_directory_at(full_path: &str) { pub fn delete_directory_at(full_path: &str) {
@ -254,6 +365,17 @@ pub fn executable_path() -> PathBuf {
buf buf
} }
pub fn in_directory(str: &str) -> &str { pub fn in_directory(str: impl AsRef<Path>) -> String {
str str.as_ref().display().to_string()
}
pub fn pipeline(commands: &str) -> String {
commands.lines()
.skip(1)
.map(|line| line.trim())
.collect::<Vec<&str>>()
.join(" ")
.trim_end()
.to_string()
} }

View File

@ -1,44 +1,58 @@
mod helpers; mod helpers;
use helpers::in_directory as cwd; use helpers::{in_directory as cwd};
use helpers::normalize_string; use helpers as h;
#[test]
fn pipeline_helper() {
let actual = h::pipeline(
r#"
open los_tres_amigos.txt
| from-csv
| get rusty_luck
| str --to-int
| sum
| echo "$it"
"#);
assert_eq!(actual, r#"open los_tres_amigos.txt | from-csv | get rusty_luck | str --to-int | sum | echo "$it""#);
}
#[test] #[test]
fn external_num() { fn external_num() {
nu!( let actual = nu!(
output,
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
"open sgml_description.json | get glossary.GlossDiv.GlossList.GlossEntry.Height | echo $it" "open sgml_description.json | get glossary.GlossDiv.GlossList.GlossEntry.Height | echo $it"
); );
assert_eq!(output, "10"); assert_eq!(actual, "10");
} }
#[test] #[test]
fn external_has_correct_quotes() { fn external_has_correct_quotes() {
nu!(output, cwd("."), r#"echo "hello world""#); let actual = nu!(cwd("."), r#"echo "hello world""#);
let output = normalize_string(&output); let actual = h::normalize_string(&actual);
assert_eq!(output, r#""hello world""#); assert_eq!(actual, r#""hello world""#);
} }
#[test] #[test]
fn add_plugin() { fn add_plugin() {
nu!(output, let actual = nu!(
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
r#"open cargo_sample.toml | add dev-dependencies.newdep "1" | get dev-dependencies.newdep | echo $it"# r#"open cargo_sample.toml | add dev-dependencies.newdep "1" | get dev-dependencies.newdep | echo $it"#
); );
assert_eq!(output, "1"); assert_eq!(actual, "1");
} }
#[test] #[test]
fn edit_plugin() { fn edit_plugin() {
nu!(output, let actual = nu!(
cwd("tests/fixtures/formats"), cwd("tests/fixtures/formats"),
r#"open cargo_sample.toml | edit dev-dependencies.pretty_assertions "7" | get dev-dependencies.pretty_assertions | echo $it"# r#"open cargo_sample.toml | edit dev-dependencies.pretty_assertions "7" | get dev-dependencies.pretty_assertions | echo $it"#
); );
assert_eq!(output, "7"); assert_eq!(actual, "7");
} }