repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/debug/view_source.rs | crates/nu-command/src/debug/view_source.rs | use nu_engine::command_prelude::*;
use nu_protocol::{Config, PipelineMetadata};
use std::fmt::Write;
#[derive(Clone)]
pub struct ViewSource;
impl Command for ViewSource {
fn name(&self) -> &str {
"view source"
}
fn description(&self) -> &str {
"View a block, module, or a definition."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("view source")
.input_output_types(vec![(Type::Nothing, Type::String)])
.required("item", SyntaxShape::Any, "Name or block to view.")
.category(Category::Debug)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let arg: Value = call.req(engine_state, stack, 0)?;
let arg_span = arg.span();
let source = match arg {
Value::Int { val, .. } => {
if let Some(block) =
engine_state.try_get_block(nu_protocol::BlockId::new(val as usize))
{
if let Some(span) = block.span {
let contents = engine_state.get_span_contents(span);
Ok(Value::string(String::from_utf8_lossy(contents), call.head)
.into_pipeline_data())
} else {
Err(ShellError::GenericError {
error: "Cannot view int value".to_string(),
msg: "the block does not have a viewable span".to_string(),
span: Some(arg_span),
help: None,
inner: vec![],
})
}
} else {
Err(ShellError::GenericError {
error: format!("Block Id {} does not exist", arg.coerce_into_string()?),
msg: "this number does not correspond to a block".to_string(),
span: Some(arg_span),
help: None,
inner: vec![],
})
}
}
Value::String { val, .. } => {
if let Some(decl_id) = engine_state.find_decl(val.as_bytes(), &[]) {
// arg is a command
let decl = engine_state.get_decl(decl_id);
let sig = decl.signature();
let vec_of_required = &sig.required_positional;
let vec_of_optional = &sig.optional_positional;
let rest = &sig.rest_positional;
let vec_of_flags = &sig.named;
let type_signatures = &sig.input_output_types;
if decl.is_alias() {
if let Some(alias) = &decl.as_alias() {
let contents = String::from_utf8_lossy(
engine_state.get_span_contents(alias.wrapped_call.span),
);
Ok(Value::string(contents, call.head).into_pipeline_data())
} else {
Ok(Value::string("no alias found", call.head).into_pipeline_data())
}
}
// gets vector of positionals.
else if let Some(block_id) = decl.block_id() {
let block = engine_state.get_block(block_id);
if let Some(block_span) = block.span {
let contents = engine_state.get_span_contents(block_span);
// name of function
let mut final_contents = String::new();
if val.contains(' ') {
let _ = write!(&mut final_contents, "def \"{val}\" [");
} else {
let _ = write!(&mut final_contents, "def {val} [");
};
if !vec_of_required.is_empty()
|| !vec_of_optional.is_empty()
|| vec_of_flags.len() != 1
|| rest.is_some()
{
final_contents.push(' ');
}
for n in vec_of_required {
let _ = write!(&mut final_contents, "{}: {} ", n.name, n.shape);
// positional arguments
}
for n in vec_of_optional {
if let Some(s) = n.default_value.clone() {
let _ = write!(
&mut final_contents,
"{}: {} = {} ",
n.name,
n.shape,
s.to_expanded_string(" ", &Config::default())
);
} else {
let _ =
write!(&mut final_contents, "{}?: {} ", n.name, n.shape);
}
}
for n in vec_of_flags {
// skip adding the help flag
if n.long == "help" {
continue;
}
let _ = write!(&mut final_contents, "--{}", n.long);
if let Some(short) = n.short {
let _ = write!(&mut final_contents, "(-{short})");
}
if let Some(arg) = &n.arg {
let _ = write!(&mut final_contents, ": {arg}");
}
final_contents.push(' ');
}
if let Some(rest_arg) = rest {
let _ = write!(
&mut final_contents,
"...{}:{}",
rest_arg.name, rest_arg.shape
);
}
let len = type_signatures.len();
if len != 0 {
final_contents.push_str("]: [");
let mut c = 0;
for (insig, outsig) in type_signatures {
c += 1;
let s = format!("{insig} -> {outsig}");
final_contents.push_str(&s);
if c != len {
final_contents.push_str(", ")
}
}
}
final_contents.push_str("] ");
final_contents.push_str(&String::from_utf8_lossy(contents));
Ok(Value::string(final_contents, call.head).into_pipeline_data())
} else {
Err(ShellError::GenericError {
error: "Cannot view string value".to_string(),
msg: "the command does not have a viewable block span".to_string(),
span: Some(arg_span),
help: None,
inner: vec![],
})
}
} else {
Err(ShellError::GenericError {
error: "Cannot view string decl value".to_string(),
msg: "the command does not have a viewable block".to_string(),
span: Some(arg_span),
help: None,
inner: vec![],
})
}
} else if let Some(module_id) = engine_state.find_module(val.as_bytes(), &[]) {
// arg is a module
let module = engine_state.get_module(module_id);
if let Some(module_span) = module.span {
let contents = engine_state.get_span_contents(module_span);
Ok(Value::string(String::from_utf8_lossy(contents), call.head)
.into_pipeline_data())
} else {
Err(ShellError::GenericError {
error: "Cannot view string module value".to_string(),
msg: "the module does not have a viewable block".to_string(),
span: Some(arg_span),
help: None,
inner: vec![],
})
}
} else {
Err(ShellError::GenericError {
error: "Cannot view string value".to_string(),
msg: "this name does not correspond to a viewable value".to_string(),
span: Some(arg_span),
help: None,
inner: vec![],
})
}
}
value => {
if let Ok(closure) = value.as_closure() {
let block = engine_state.get_block(closure.block_id);
if let Some(span) = block.span {
let contents = engine_state.get_span_contents(span);
Ok(Value::string(String::from_utf8_lossy(contents), call.head)
.into_pipeline_data())
} else {
Ok(Value::string("<internal command>", call.head).into_pipeline_data())
}
} else {
Err(ShellError::GenericError {
error: "Cannot view value".to_string(),
msg: "this value cannot be viewed".to_string(),
span: Some(arg_span),
help: None,
inner: vec![],
})
}
}
};
source.map(|x| {
x.set_metadata(Some(PipelineMetadata {
content_type: Some("application/x-nuscript".into()),
..Default::default()
}))
})
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "View the source of a code block",
example: r#"let abc = {|| echo 'hi' }; view source $abc"#,
result: Some(Value::test_string("{|| echo 'hi' }")),
},
Example {
description: "View the source of a custom command",
example: r#"def hi [] { echo 'Hi!' }; view source hi"#,
result: Some(Value::test_string("def hi [] { echo 'Hi!' }")),
},
Example {
description: "View the source of a custom command, which participates in the caller environment",
example: r#"def --env foo [] { $env.BAR = 'BAZ' }; view source foo"#,
result: Some(Value::test_string("def foo [] { $env.BAR = 'BAZ' }")),
},
Example {
description: "View the source of a custom command with flags and arguments",
example: r#"def test [a?:any --b:int ...rest:string] { echo 'test' }; view source test"#,
result: Some(Value::test_string(
"def test [ a?: any --b: int ...rest: string] { echo 'test' }",
)),
},
Example {
description: "View the source of a module",
example: r#"module mod-foo { export-env { $env.FOO_ENV = 'BAZ' } }; view source mod-foo"#,
result: Some(Value::test_string(" export-env { $env.FOO_ENV = 'BAZ' }")),
},
Example {
description: "View the source of an alias",
example: r#"alias hello = echo hi; view source hello"#,
result: Some(Value::test_string("echo hi")),
},
]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/debug/mod.rs | crates/nu-command/src/debug/mod.rs | mod ast;
mod debug_;
mod env;
mod experimental_options;
mod explain;
mod info;
mod inspect;
mod inspect_table;
mod metadata;
mod metadata_access;
mod metadata_set;
mod profile;
mod timeit;
mod util;
mod view;
mod view_blocks;
mod view_files;
mod view_ir;
mod view_source;
mod view_span;
pub use ast::Ast;
pub use debug_::Debug;
pub use env::DebugEnv;
pub use experimental_options::DebugExperimentalOptions;
pub use explain::Explain;
pub use info::DebugInfo;
pub use inspect::Inspect;
pub use inspect_table::build_table;
pub use metadata::Metadata;
pub use metadata_access::MetadataAccess;
pub use metadata_set::MetadataSet;
pub use profile::DebugProfile;
pub use timeit::TimeIt;
pub use view::View;
pub use view_blocks::ViewBlocks;
pub use view_files::ViewFiles;
pub use view_ir::ViewIr;
pub use view_source::ViewSource;
pub use view_span::ViewSpan;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/debug/metadata_access.rs | crates/nu-command/src/debug/metadata_access.rs | use nu_engine::{command_prelude::*, get_eval_block_with_early_return};
use nu_protocol::{
PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
engine::{Call, Closure, Command, EngineState, Stack},
};
use super::util::build_metadata_record;
#[derive(Clone)]
pub struct MetadataAccess;
impl Command for MetadataAccess {
fn name(&self) -> &str {
"metadata access"
}
fn description(&self) -> &str {
"Access the metadata for the input stream within a closure."
}
fn signature(&self) -> Signature {
Signature::build("metadata access")
.required(
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Record(vec![])])),
"The closure to run with metadata access.",
)
.input_output_types(vec![(Type::Any, Type::Any)])
.category(Category::Debug)
}
fn run(
&self,
engine_state: &EngineState,
caller_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let closure: Closure = call.req(engine_state, caller_stack, 0)?;
let block = engine_state.get_block(closure.block_id);
// `ClosureEvalOnce` is not used as it uses `Stack::captures_to_stack` rather than
// `Stack::captures_to_stack_preserve_out_dest`. This command shouldn't collect streams
let mut callee_stack = caller_stack.captures_to_stack_preserve_out_dest(closure.captures);
let metadata_record = Value::record(build_metadata_record(&input, call.head), call.head);
if let Some(var_id) = block.signature.get_positional(0).and_then(|var| var.var_id) {
callee_stack.add_var(var_id, metadata_record)
}
let eval = get_eval_block_with_early_return(engine_state);
eval(engine_state, &mut callee_stack, block, input).map(|p| p.body)
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Access metadata and data from a stream together",
example: r#"{foo: bar} | to json --raw | metadata access {|meta| {in: $in, content: $meta.content_type}}"#,
result: Some(Value::test_record(record! {
"in" => Value::test_string(r#"{"foo":"bar"}"#),
"content" => Value::test_string(r#"application/json"#)
})),
}]
}
}
#[cfg(test)]
mod test {
use crate::ToJson;
use super::*;
#[test]
fn test_examples() {
use crate::test_examples_with_commands;
test_examples_with_commands(MetadataAccess {}, &[&ToJson])
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/debug/metadata_set.rs | crates/nu-command/src/debug/metadata_set.rs | use super::util::{extend_record_with_metadata, parse_metadata_from_record};
use nu_engine::{ClosureEvalOnce, command_prelude::*};
use nu_protocol::{DataSource, engine::Closure};
#[derive(Clone)]
pub struct MetadataSet;
impl Command for MetadataSet {
fn name(&self) -> &str {
"metadata set"
}
fn description(&self) -> &str {
"Set the metadata for items in the stream."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("metadata set")
.input_output_types(vec![(Type::Any, Type::Any)])
.optional(
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Record(vec![])])),
"A closure that receives the current metadata and returns a new metadata record. Cannot be used with other flags.",
)
.switch(
"datasource-ls",
"Assign the DataSource::Ls metadata to the input",
Some('l'),
)
.named(
"datasource-filepath",
SyntaxShape::Filepath,
"Assign the DataSource::FilePath metadata to the input",
Some('f'),
)
.named(
"content-type",
SyntaxShape::String,
"Assign content type metadata to the input",
Some('c'),
)
.named(
"merge",
SyntaxShape::Record(vec![]),
"Merge arbitrary metadata fields",
Some('m'),
)
.allow_variants_without_examples(true)
.category(Category::Debug)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
mut input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let closure: Option<Closure> = call.opt(engine_state, stack, 0)?;
let ds_fp: Option<String> = call.get_flag(engine_state, stack, "datasource-filepath")?;
let ds_ls = call.has_flag(engine_state, stack, "datasource-ls")?;
let content_type: Option<String> = call.get_flag(engine_state, stack, "content-type")?;
let merge: Option<Value> = call.get_flag(engine_state, stack, "merge")?;
let mut metadata = match &mut input {
PipelineData::Value(_, metadata)
| PipelineData::ListStream(_, metadata)
| PipelineData::ByteStream(_, metadata) => metadata.take().unwrap_or_default(),
PipelineData::Empty => return Err(ShellError::PipelineEmpty { dst_span: head }),
};
// Handle closure parameter - mutually exclusive with flags
if let Some(closure) = closure {
if ds_fp.is_some() || ds_ls || content_type.is_some() || merge.is_some() {
return Err(ShellError::GenericError {
error: "Incompatible parameters".into(),
msg: "cannot use closure with other flags".into(),
span: Some(head),
help: Some("Use either the closure parameter or flags, not both".into()),
inner: vec![],
});
}
let record = extend_record_with_metadata(Record::new(), Some(&metadata), head);
let metadata_value = record.into_value(head);
let result = ClosureEvalOnce::new(engine_state, stack, closure)
.run_with_value(metadata_value)?
.into_value(head)?;
let result_record = result.as_record().map_err(|err| ShellError::GenericError {
error: "Closure must return a record".into(),
msg: format!("got {}", result.get_type()),
span: Some(head),
help: Some("The closure should return a record with metadata fields".into()),
inner: vec![err],
})?;
metadata = parse_metadata_from_record(result_record);
return Ok(input.set_metadata(Some(metadata)));
}
// Flag-based metadata modification
if let Some(content_type) = content_type {
metadata.content_type = Some(content_type);
}
if let Some(merge) = merge {
let custom_record = merge.as_record()?;
for (key, value) in custom_record {
metadata.custom.insert(key.clone(), value.clone());
}
}
match (ds_fp, ds_ls) {
(Some(path), false) => metadata.data_source = DataSource::FilePath(path.into()),
(None, true) => metadata.data_source = DataSource::Ls,
(Some(_), true) => {
return Err(ShellError::IncompatibleParameters {
left_message: "cannot use `--datasource-filepath`".into(),
left_span: call
.get_flag_span(stack, "datasource-filepath")
.expect("has flag"),
right_message: "with `--datasource-ls`".into(),
right_span: call
.get_flag_span(stack, "datasource-ls")
.expect("has flag"),
});
}
(None, false) => (),
}
Ok(input.set_metadata(Some(metadata)))
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Set the metadata of a table literal",
example: "[[name color]; [Cargo.lock '#ff0000'] [Cargo.toml '#00ff00'] [README.md '#0000ff']] | metadata set --datasource-ls",
result: None,
},
Example {
description: "Set the metadata of a file path",
example: "'crates' | metadata set --datasource-filepath $'(pwd)/crates'",
result: None,
},
Example {
description: "Set the content type metadata",
example: "'crates' | metadata set --content-type text/plain | metadata | get content_type",
result: Some(Value::test_string("text/plain")),
},
Example {
description: "Set custom metadata",
example: r#""data" | metadata set --merge {custom_key: "value"} | metadata | get custom_key"#,
result: Some(Value::test_string("value")),
},
Example {
description: "Set metadata using a closure",
example: r#""data" | metadata set --content-type "text/csv" | metadata set {|m| $m | update content_type {$in + "-processed"}} | metadata | get content_type"#,
result: Some(Value::test_string("text/csv-processed")),
},
]
}
}
#[cfg(test)]
mod test {
use crate::{Metadata, test_examples_with_commands};
use super::*;
#[test]
fn test_examples() {
test_examples_with_commands(MetadataSet {}, &[&Metadata {}])
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/debug/metadata.rs | crates/nu-command/src/debug/metadata.rs | use super::util::{build_metadata_record, extend_record_with_metadata};
use nu_engine::command_prelude::*;
use nu_protocol::{
PipelineMetadata,
ast::{Expr, Expression},
};
#[derive(Clone)]
pub struct Metadata;
impl Command for Metadata {
fn name(&self) -> &str {
"metadata"
}
fn description(&self) -> &str {
"Get the metadata for items in the stream."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("metadata")
.input_output_types(vec![(Type::Any, Type::record())])
.allow_variants_without_examples(true)
.optional(
"expression",
SyntaxShape::Any,
"The expression you want metadata for.",
)
.category(Category::Debug)
}
fn requires_ast_for_arguments(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let arg = call.positional_nth(stack, 0);
let head = call.head;
if !matches!(input, PipelineData::Empty)
&& let Some(arg_expr) = arg
{
return Err(ShellError::IncompatibleParameters {
left_message: "pipeline input was provided".into(),
left_span: head,
right_message: "but a positional metadata expression was also given".into(),
right_span: arg_expr.span,
});
}
match arg {
Some(Expression {
expr: Expr::FullCellPath(full_cell_path),
span,
..
}) => {
if full_cell_path.tail.is_empty() {
match &full_cell_path.head {
Expression {
expr: Expr::Var(var_id),
..
} => {
let origin = stack.get_var_with_origin(*var_id, *span)?;
Ok(build_metadata_record_value(
&origin,
input.metadata().as_ref(),
head,
)
.into_pipeline_data())
}
_ => {
let val: Value = call.req(engine_state, stack, 0)?;
Ok(
build_metadata_record_value(&val, input.metadata().as_ref(), head)
.into_pipeline_data(),
)
}
}
} else {
let val: Value = call.req(engine_state, stack, 0)?;
Ok(
build_metadata_record_value(&val, input.metadata().as_ref(), head)
.into_pipeline_data(),
)
}
}
Some(_) => {
let val: Value = call.req(engine_state, stack, 0)?;
Ok(
build_metadata_record_value(&val, input.metadata().as_ref(), head)
.into_pipeline_data(),
)
}
None => {
Ok(Value::record(build_metadata_record(&input, head), head).into_pipeline_data())
}
}
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Get the metadata of a variable",
example: "let a = 42; metadata $a",
result: None,
},
Example {
description: "Get the metadata of the input",
example: "ls | metadata",
result: None,
},
]
}
}
fn build_metadata_record_value(
arg: &Value,
metadata: Option<&PipelineMetadata>,
head: Span,
) -> Value {
let mut record = Record::new();
record.push("span", arg.span().into_value(head));
Value::record(extend_record_with_metadata(record, metadata, head), head)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Metadata {})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/debug/experimental_options.rs | crates/nu-command/src/debug/experimental_options.rs | use nu_engine::command_prelude::*;
use nu_experimental::Status;
#[derive(Clone)]
pub struct DebugExperimentalOptions;
impl Command for DebugExperimentalOptions {
fn name(&self) -> &str {
"debug experimental-options"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_type(
Type::Nothing,
Type::Table(Box::from([
(String::from("identifier"), Type::String),
(String::from("enabled"), Type::Bool),
(String::from("status"), Type::String),
(String::from("description"), Type::String),
(String::from("since"), Type::String),
(String::from("issue"), Type::String),
])),
)
.category(Category::Debug)
}
fn description(&self) -> &str {
"Show all experimental options."
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(PipelineData::value(
Value::list(
nu_experimental::ALL
.iter()
.map(|option| {
Value::record(
nu_protocol::record! {
"identifier" => Value::string(option.identifier(), call.head),
"enabled" => Value::bool(option.get(), call.head),
"status" => Value::string(match option.status() {
Status::OptIn => "opt-in",
Status::OptOut => "opt-out",
Status::DeprecatedDiscard => "deprecated-discard",
Status::DeprecatedDefault => "deprecated-default"
}, call.head),
"description" => Value::string(option.description(), call.head),
"since" => Value::string({
let (major, minor, patch) = option.since();
format!("{major}.{minor}.{patch}")
}, call.head),
"issue" => Value::string(option.issue_url(), call.head)
},
call.head,
)
})
.collect(),
call.head,
),
None,
))
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/debug/view_blocks.rs | crates/nu-command/src/debug/view_blocks.rs | use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct ViewBlocks;
impl Command for ViewBlocks {
fn name(&self) -> &str {
"view blocks"
}
fn description(&self) -> &str {
"View the blocks registered in nushell's EngineState memory."
}
fn extra_description(&self) -> &str {
"These are blocks parsed and loaded at runtime as well as any blocks that accumulate in the repl."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("view blocks")
.input_output_types(vec![(
Type::Nothing,
Type::Table(
[
("block_id".into(), Type::Int),
("content".into(), Type::String),
("start".into(), Type::Int),
("end".into(), Type::Int),
]
.into(),
),
)])
.category(Category::Debug)
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let mut records = vec![];
for block_id in 0..engine_state.num_blocks() {
let block = engine_state.get_block(nu_protocol::BlockId::new(block_id));
if let Some(span) = block.span {
let contents_bytes = engine_state.get_span_contents(span);
let contents_string = String::from_utf8_lossy(contents_bytes);
let cur_rec = record! {
"block_id" => Value::int(block_id as i64, span),
"content" => Value::string(contents_string.trim().to_string(), span),
"start" => Value::int(span.start as i64, span),
"end" => Value::int(span.end as i64, span),
};
records.push(Value::record(cur_rec, span));
}
}
Ok(Value::list(records, call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "View the blocks registered in Nushell's EngineState memory",
example: r#"view blocks"#,
result: None,
}]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/debug/inspect.rs | crates/nu-command/src/debug/inspect.rs | use super::inspect_table;
use nu_engine::command_prelude::*;
use nu_utils::terminal_size;
#[derive(Clone)]
pub struct Inspect;
impl Command for Inspect {
fn name(&self) -> &str {
"inspect"
}
fn description(&self) -> &str {
"Inspect pipeline results while running a pipeline."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("inspect")
.input_output_types(vec![(Type::Any, Type::Any)])
.allow_variants_without_examples(true)
.category(Category::Debug)
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let input_metadata = input.metadata();
let input_val = input.into_value(call.head)?;
if input_val.is_nothing() {
return Err(ShellError::PipelineEmpty {
dst_span: call.head,
});
}
let original_input = input_val.clone();
let description = input_val.get_type().to_string();
let (cols, _rows) = terminal_size().unwrap_or((0, 0));
let table = inspect_table::build_table(engine_state, input_val, description, cols as usize);
// Note that this is printed to stderr. The reason for this is so it doesn't disrupt the regular nushell
// tabular output. If we printed to stdout, nushell would get confused with two outputs.
eprintln!("{table}\n");
Ok(original_input.into_pipeline_data_with_metadata(input_metadata))
}
fn examples(&self) -> Vec<Example<'_>> {
vec![Example {
description: "Inspect pipeline results",
example: "ls | inspect | get name | inspect",
result: None,
}]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/debug/profile.rs | crates/nu-command/src/debug/profile.rs | use nu_engine::{ClosureEvalOnce, command_prelude::*};
use nu_protocol::{
debugger::{DurationMode, Profiler, ProfilerOptions},
engine::Closure,
};
#[derive(Clone)]
pub struct DebugProfile;
impl Command for DebugProfile {
fn name(&self) -> &str {
"debug profile"
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("debug profile")
.required(
"closure",
SyntaxShape::Closure(None),
"The closure to profile.",
)
.switch("spans", "Collect spans of profiled elements", Some('s'))
.switch(
"expand-source",
"Collect full source fragments of profiled elements",
Some('e'),
)
.switch(
"values",
"Collect pipeline element output values",
Some('v'),
)
.switch("lines", "Collect line numbers", Some('l'))
.switch(
"duration-values",
"Report instruction duration as duration values rather than milliseconds",
Some('d'),
)
.named(
"max-depth",
SyntaxShape::Int,
"How many blocks/closures deep to step into (default 2)",
Some('m'),
)
.input_output_types(vec![(Type::Any, Type::table())])
.category(Category::Debug)
}
fn description(&self) -> &str {
"Profile pipeline elements in a closure."
}
fn extra_description(&self) -> &str {
r#"The profiler profiles every evaluated instruction inside a closure, stepping into all
commands calls and other blocks/closures.
The output can be heavily customized. By default, the following columns are included:
- depth : Depth of the instruction. Each entered block adds one level of depth. How many
blocks deep to step into is controlled with the --max-depth option.
- id : ID of the instruction
- parent_id : ID of the instruction that created the parent scope
- source : Source code that generated the instruction. If the source code has multiple lines,
only the first line is used and `...` is appended to the end. Full source code can
be shown with the --expand-source flag.
- pc : The index of the instruction within the block.
- instruction : The pretty printed instruction being evaluated.
- duration : How long it took to run the instruction.
- (optional) span : Span associated with the instruction. Can be viewed via the `view span`
command. Enabled with the --spans flag.
- (optional) output : The output value of the instruction. Enabled with the --values flag.
To illustrate the depth and IDs, consider `debug profile { do { if true { echo 'spam' } } }`. A unique ID is generated each time an instruction is executed, and there are two levels of depth:
```
depth id parent_id source pc instruction
0 0 0 debug profile { do { if true { 'spam' } } } 0 <start>
1 1 0 { if true { 'spam' } } 0 load-literal %1, closure(2164)
1 2 0 { if true { 'spam' } } 1 push-positional %1
1 3 0 { do { if true { 'spam' } } } 2 redirect-out caller
1 4 0 { do { if true { 'spam' } } } 3 redirect-err caller
1 5 0 do 4 call decl 7 "do", %0
2 6 5 true 0 load-literal %1, bool(true)
2 7 5 if 1 not %1
2 8 5 if 2 branch-if %1, 5
2 9 5 'spam' 3 load-literal %0, string("spam")
2 10 5 if 4 jump 6
2 11 5 { if true { 'spam' } } 6 return %0
1 12 0 { do { if true { 'spam' } } } 5 return %0
```
Each block entered increments depth by 1 and each block left decrements it by one. This way you can
control the profiling granularity. Passing --max-depth=1 to the above would stop inside the `do`
at `if true { 'spam' }`. The id is used to identify each element. The parent_id tells you that the
instructions inside the block are being executed because of `do` (5), which in turn was spawned from
the root `debug profile { ... }`.
For a better understanding of how instructions map to source code, see the `view ir` command.
Note: In some cases, the ordering of pipeline elements might not be intuitive. For example,
`[ a bb cc ] | each { $in | str length }` involves some implicit collects and lazy evaluation
confusing the id/parent_id hierarchy. The --expr flag is helpful for investigating these issues."#
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let closure: Closure = call.req(engine_state, stack, 0)?;
let collect_spans = call.has_flag(engine_state, stack, "spans")?;
let collect_expanded_source = call.has_flag(engine_state, stack, "expanded-source")?;
let collect_values = call.has_flag(engine_state, stack, "values")?;
let collect_lines = call.has_flag(engine_state, stack, "lines")?;
let duration_values = call.has_flag(engine_state, stack, "duration-values")?;
let max_depth = call
.get_flag(engine_state, stack, "max-depth")?
.unwrap_or(2);
let duration_mode = match duration_values {
true => DurationMode::Value,
false => DurationMode::Milliseconds,
};
let profiler = Profiler::new(
ProfilerOptions {
max_depth,
collect_spans,
collect_source: true,
collect_expanded_source,
collect_values,
collect_exprs: false,
collect_instructions: true,
collect_lines,
duration_mode,
},
call.span(),
);
let lock_err = |_| ShellError::GenericError {
error: "Profiler Error".to_string(),
msg: "could not lock debugger, poisoned mutex".to_string(),
span: Some(call.head),
help: None,
inner: vec![],
};
engine_state
.activate_debugger(Box::new(profiler))
.map_err(lock_err)?;
let result = ClosureEvalOnce::new(engine_state, stack, closure).run_with_input(input);
// Return potential errors
let pipeline_data = result?;
// Collect the output
let _ = pipeline_data.into_value(call.span());
Ok(engine_state
.deactivate_debugger()
.map_err(lock_err)?
.report(engine_state, call.span())?
.into_pipeline_data())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Profile config evaluation",
example: "debug profile { source $nu.config-path }",
result: None,
},
Example {
description: "Profile config evaluation with more granularity",
example: "debug profile { source $nu.config-path } --max-depth 4",
result: None,
},
]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/sort_utils.rs | crates/nu-command/tests/sort_utils.rs | use nu_command::{Comparator, sort, sort_by, sort_record};
use nu_protocol::{
Record, Span, Value,
ast::{CellPath, PathMember},
casing::Casing,
record,
};
#[test]
fn test_sort_basic() {
let mut list = vec![
Value::test_string("foo"),
Value::test_int(2),
Value::test_int(3),
Value::test_string("bar"),
Value::test_int(1),
Value::test_string("baz"),
];
assert!(sort(&mut list, false, false).is_ok());
assert_eq!(
list,
vec![
Value::test_int(1),
Value::test_int(2),
Value::test_int(3),
Value::test_string("bar"),
Value::test_string("baz"),
Value::test_string("foo")
]
);
}
#[test]
fn test_sort_nothing() {
// Nothing values should always be sorted to the end of any list
let mut list = vec![
Value::test_int(1),
Value::test_nothing(),
Value::test_int(2),
Value::test_string("foo"),
Value::test_nothing(),
Value::test_string("bar"),
];
assert!(sort(&mut list, false, false).is_ok());
assert_eq!(
list,
vec![
Value::test_int(1),
Value::test_int(2),
Value::test_string("bar"),
Value::test_string("foo"),
Value::test_nothing(),
Value::test_nothing()
]
);
// Ensure that nothing values are sorted after *all* types,
// even types which may follow `Nothing` in the PartialOrd order
// unstable_name_collision
// can be switched to std intersperse when stabilized
let mut values: Vec<Value> =
itertools::intersperse(Value::test_values(), Value::test_nothing()).collect();
let nulls = values
.iter()
.filter(|item| item == &&Value::test_nothing())
.count();
assert!(sort(&mut values, false, false).is_ok());
// check if the last `nulls` values of the sorted list are indeed null
assert_eq!(&values[(nulls - 1)..], vec![Value::test_nothing(); nulls])
}
#[test]
fn test_sort_natural_basic() {
let mut list = vec![
Value::test_string("foo99"),
Value::test_string("foo9"),
Value::test_string("foo1"),
Value::test_string("foo100"),
Value::test_string("foo10"),
Value::test_string("1"),
Value::test_string("10"),
Value::test_string("100"),
Value::test_string("9"),
Value::test_string("99"),
];
assert!(sort(&mut list, false, false).is_ok());
assert_eq!(
list,
vec![
Value::test_string("1"),
Value::test_string("10"),
Value::test_string("100"),
Value::test_string("9"),
Value::test_string("99"),
Value::test_string("foo1"),
Value::test_string("foo10"),
Value::test_string("foo100"),
Value::test_string("foo9"),
Value::test_string("foo99"),
]
);
assert!(sort(&mut list, false, true).is_ok());
assert_eq!(
list,
vec![
Value::test_string("1"),
Value::test_string("9"),
Value::test_string("10"),
Value::test_string("99"),
Value::test_string("100"),
Value::test_string("foo1"),
Value::test_string("foo9"),
Value::test_string("foo10"),
Value::test_string("foo99"),
Value::test_string("foo100"),
]
);
}
#[test]
fn test_sort_natural_mixed_types() {
let mut list = vec![
Value::test_string("1"),
Value::test_int(99),
Value::test_int(1),
Value::test_float(1000.0),
Value::test_int(9),
Value::test_string("9"),
Value::test_int(100),
Value::test_string("99"),
Value::test_float(2.0),
Value::test_string("100"),
Value::test_int(10),
Value::test_string("10"),
];
assert!(sort(&mut list, false, false).is_ok());
assert_eq!(
list,
vec![
Value::test_int(1),
Value::test_float(2.0),
Value::test_int(9),
Value::test_int(10),
Value::test_int(99),
Value::test_int(100),
Value::test_float(1000.0),
Value::test_string("1"),
Value::test_string("10"),
Value::test_string("100"),
Value::test_string("9"),
Value::test_string("99")
]
);
assert!(sort(&mut list, false, true).is_ok());
assert_eq!(
list,
vec![
Value::test_int(1),
Value::test_string("1"),
Value::test_float(2.0),
Value::test_int(9),
Value::test_string("9"),
Value::test_int(10),
Value::test_string("10"),
Value::test_int(99),
Value::test_string("99"),
Value::test_int(100),
Value::test_string("100"),
Value::test_float(1000.0),
]
);
}
#[test]
fn test_sort_natural_no_numeric_values() {
// If list contains no numeric strings, it should be sorted the
// same with or without natural sorting
let mut normal = vec![
Value::test_string("golf"),
Value::test_bool(false),
Value::test_string("alfa"),
Value::test_string("echo"),
Value::test_int(7),
Value::test_int(10),
Value::test_bool(true),
Value::test_string("uniform"),
Value::test_int(3),
Value::test_string("tango"),
];
let mut natural = normal.clone();
assert!(sort(&mut normal, false, false).is_ok());
assert!(sort(&mut natural, false, true).is_ok());
assert_eq!(normal, natural);
}
#[test]
fn test_sort_natural_type_order() {
// This test is to prevent regression to a previous natural sort behavior
// where values of different types would be intermixed.
// Only numeric values (ints, floats, and numeric strings) should be intermixed
//
// This list would previously be incorrectly sorted like this:
// ╭────┬─────────╮
// │ 0 │ 1 │
// │ 1 │ golf │
// │ 2 │ false │
// │ 3 │ 7 │
// │ 4 │ 10 │
// │ 5 │ alfa │
// │ 6 │ true │
// │ 7 │ uniform │
// │ 8 │ true │
// │ 9 │ 3 │
// │ 10 │ false │
// │ 11 │ tango │
// ╰────┴─────────╯
let mut list = vec![
Value::test_string("golf"),
Value::test_int(1),
Value::test_bool(false),
Value::test_string("alfa"),
Value::test_int(7),
Value::test_int(10),
Value::test_bool(true),
Value::test_string("uniform"),
Value::test_bool(true),
Value::test_int(3),
Value::test_bool(false),
Value::test_string("tango"),
];
assert!(sort(&mut list, false, true).is_ok());
assert_eq!(
list,
vec![
Value::test_bool(false),
Value::test_bool(false),
Value::test_bool(true),
Value::test_bool(true),
Value::test_int(1),
Value::test_int(3),
Value::test_int(7),
Value::test_int(10),
Value::test_string("alfa"),
Value::test_string("golf"),
Value::test_string("tango"),
Value::test_string("uniform")
]
);
// Only ints, floats, and numeric strings should be intermixed
// While binary primitives and datetimes can be coerced into strings, it doesn't make sense to sort them with numbers
// Binary primitives can hold multiple values, not just one, so shouldn't be compared to single values
// Datetimes don't have a single obvious numeric representation, and if we chose one it would be ambiguous to the user
let year_three = chrono::NaiveDate::from_ymd_opt(3, 1, 1)
.unwrap()
.and_hms_opt(0, 0, 0)
.unwrap()
.and_utc();
let mut list = vec![
Value::test_int(10),
Value::test_float(6.0),
Value::test_int(1),
Value::test_binary([3]),
Value::test_string("2"),
Value::test_date(year_three.into()),
Value::test_int(4),
Value::test_binary([52]),
Value::test_float(9.0),
Value::test_string("5"),
Value::test_date(chrono::DateTime::UNIX_EPOCH.into()),
Value::test_int(7),
Value::test_string("8"),
Value::test_float(3.0),
Value::test_string("foobar"),
];
assert!(sort(&mut list, false, true).is_ok());
assert_eq!(
list,
vec![
Value::test_int(1),
Value::test_string("2"),
Value::test_float(3.0),
Value::test_int(4),
Value::test_string("5"),
Value::test_float(6.0),
Value::test_int(7),
Value::test_string("8"),
Value::test_float(9.0),
Value::test_int(10),
Value::test_string("foobar"),
// the ordering of date and binary here may change if the PartialOrd order is changed,
// but they should not be intermixed with the above
Value::test_date(year_three.into()),
Value::test_date(chrono::DateTime::UNIX_EPOCH.into()),
Value::test_binary([3]),
Value::test_binary([52]),
]
);
}
#[test]
fn test_sort_insensitive() {
// Test permutations between insensitive and natural
// Ensure that strings with equal insensitive orderings
// are sorted stably. (FOO then foo, bar then BAR)
let source = vec![
Value::test_string("FOO"),
Value::test_string("foo"),
Value::test_int(100),
Value::test_string("9"),
Value::test_string("bar"),
Value::test_int(10),
Value::test_string("baz"),
Value::test_string("BAR"),
];
let mut list;
// sensitive + non-natural
list = source.clone();
assert!(sort(&mut list, false, false).is_ok());
assert_eq!(
list,
vec![
Value::test_int(10),
Value::test_int(100),
Value::test_string("9"),
Value::test_string("BAR"),
Value::test_string("FOO"),
Value::test_string("bar"),
Value::test_string("baz"),
Value::test_string("foo"),
]
);
// sensitive + natural
list = source.clone();
assert!(sort(&mut list, false, true).is_ok());
assert_eq!(
list,
vec![
Value::test_string("9"),
Value::test_int(10),
Value::test_int(100),
Value::test_string("BAR"),
Value::test_string("FOO"),
Value::test_string("bar"),
Value::test_string("baz"),
Value::test_string("foo"),
]
);
// insensitive + non-natural
list = source.clone();
assert!(sort(&mut list, true, false).is_ok());
assert_eq!(
list,
vec![
Value::test_int(10),
Value::test_int(100),
Value::test_string("9"),
Value::test_string("bar"),
Value::test_string("BAR"),
Value::test_string("baz"),
Value::test_string("FOO"),
Value::test_string("foo"),
]
);
// insensitive + natural
list = source.clone();
assert!(sort(&mut list, true, true).is_ok());
assert_eq!(
list,
vec![
Value::test_string("9"),
Value::test_int(10),
Value::test_int(100),
Value::test_string("bar"),
Value::test_string("BAR"),
Value::test_string("baz"),
Value::test_string("FOO"),
Value::test_string("foo"),
]
);
}
// Helper function to assert that two records are equal
// with their key-value pairs in the same order
fn assert_record_eq(a: Record, b: Record) {
assert_eq!(
a.into_iter().collect::<Vec<_>>(),
b.into_iter().collect::<Vec<_>>(),
)
}
#[test]
fn test_sort_record_keys() {
// Basic record sort test
let record = record! {
"golf" => Value::test_string("bar"),
"alfa" => Value::test_string("foo"),
"echo" => Value::test_int(123),
};
let sorted = sort_record(record, false, false, false, false).unwrap();
assert_record_eq(
sorted,
record! {
"alfa" => Value::test_string("foo"),
"echo" => Value::test_int(123),
"golf" => Value::test_string("bar"),
},
);
}
#[test]
fn test_sort_record_values() {
// This test is to prevent a regression where integers and strings would be
// intermixed non-naturally when sorting a record by value without the natural flag:
//
// This record would previously be incorrectly sorted like this:
// ╭─────────┬─────╮
// │ alfa │ 1 │
// │ charlie │ 1 │
// │ india │ 10 │
// │ juliett │ 10 │
// │ foxtrot │ 100 │
// │ hotel │ 100 │
// │ delta │ 9 │
// │ echo │ 9 │
// │ bravo │ 99 │
// │ golf │ 99 │
// ╰─────────┴─────╯
let record = record! {
"alfa" => Value::test_string("1"),
"bravo" => Value::test_int(99),
"charlie" => Value::test_int(1),
"delta" => Value::test_int(9),
"echo" => Value::test_string("9"),
"foxtrot" => Value::test_int(100),
"golf" => Value::test_string("99"),
"hotel" => Value::test_string("100"),
"india" => Value::test_int(10),
"juliett" => Value::test_string("10"),
};
// non-natural sort
let sorted = sort_record(record.clone(), true, false, false, false).unwrap();
assert_record_eq(
sorted,
record! {
"charlie" => Value::test_int(1),
"delta" => Value::test_int(9),
"india" => Value::test_int(10),
"bravo" => Value::test_int(99),
"foxtrot" => Value::test_int(100),
"alfa" => Value::test_string("1"),
"juliett" => Value::test_string("10"),
"hotel" => Value::test_string("100"),
"echo" => Value::test_string("9"),
"golf" => Value::test_string("99"),
},
);
// natural sort
let sorted = sort_record(record.clone(), true, false, false, true).unwrap();
assert_record_eq(
sorted,
record! {
"alfa" => Value::test_string("1"),
"charlie" => Value::test_int(1),
"delta" => Value::test_int(9),
"echo" => Value::test_string("9"),
"india" => Value::test_int(10),
"juliett" => Value::test_string("10"),
"bravo" => Value::test_int(99),
"golf" => Value::test_string("99"),
"foxtrot" => Value::test_int(100),
"hotel" => Value::test_string("100"),
},
);
}
#[test]
fn test_sort_equivalent() {
// Ensure that sort, sort_by, and record sort have equivalent sorting logic
let phonetic = vec![
"alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india",
"juliett", "kilo", "lima", "mike", "november", "oscar", "papa", "quebec", "romeo",
"sierra", "tango", "uniform", "victor", "whiskey", "xray", "yankee", "zulu",
];
// filter out errors, since we can't sort_by on those
let mut values: Vec<Value> = Value::test_values()
.into_iter()
.filter(|val| !matches!(val, Value::Error { .. }))
.collect();
// reverse sort test values
values.sort_by(|a, b| b.partial_cmp(a).unwrap());
let mut list = values.clone();
let mut table: Vec<Value> = values
.clone()
.into_iter()
.map(|val| Value::test_record(record! { "value" => val }))
.collect();
let record = Record::from_iter(phonetic.into_iter().map(str::to_string).zip(values));
let comparator = Comparator::CellPath(CellPath {
members: vec![PathMember::String {
val: "value".to_string(),
span: Span::test_data(),
optional: false,
casing: Casing::Sensitive,
}],
});
assert!(sort(&mut list, false, false).is_ok());
assert!(
sort_by(
&mut table,
vec![comparator],
Span::test_data(),
false,
false
)
.is_ok()
);
let record_sorted = sort_record(record.clone(), true, false, false, false).unwrap();
let record_vals: Vec<Value> = record_sorted.into_iter().map(|pair| pair.1).collect();
let table_vals: Vec<Value> = table
.clone()
.into_iter()
.map(|record| record.into_record().unwrap().remove("value").unwrap())
.collect();
assert_eq!(list, record_vals);
assert_eq!(record_vals, table_vals);
// list == table_vals by transitive property
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/main.rs | crates/nu-command/tests/main.rs | mod commands;
mod format_conversions;
mod sort_utils;
mod string;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/string/mod.rs | crates/nu-command/tests/string/mod.rs | mod format;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/string/format/filesize.rs | crates/nu-command/tests/string/format/filesize.rs | use nu_test_support::nu;
#[test]
fn format_duration() {
let actual = nu!(r#"1MB | format filesize kB"#);
assert_eq!("1000 kB", actual.out);
}
#[test]
fn format_duration_with_invalid_unit() {
let actual = nu!(r#"1MB | format filesize sec"#);
assert!(actual.err.contains("invalid_unit"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/string/format/mod.rs | crates/nu-command/tests/string/format/mod.rs | mod duration;
mod filesize;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/string/format/duration.rs | crates/nu-command/tests/string/format/duration.rs | use nu_test_support::nu;
#[test]
fn format_duration() {
let actual = nu!(r#"1hr | format duration sec"#);
assert_eq!("3600 sec", actual.out);
}
#[test]
fn format_duration_with_invalid_unit() {
let actual = nu!(r#"1hr | format duration MB"#);
assert!(actual.err.contains("invalid_unit"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/merge.rs | crates/nu-command/tests/commands/merge.rs | use nu_test_support::nu;
#[test]
fn row() {
let left_sample = r#"[[name, country, luck];
[Andrés, Ecuador, 0],
[JT, USA, 0],
[Jason, Canada, 0],
[Yehuda, USA, 0]]"#;
let right_sample = r#"[[name, country, luck];
["Andrés Robalino", "Guayaquil Ecuador", 1],
["JT Turner", "New Zealand", 1]]"#;
let actual = nu!(format!(
r#"
({left_sample})
| merge ({right_sample})
| where country in ["Guayaquil Ecuador" "New Zealand"]
| get luck
| math sum
"#
));
assert_eq!(actual.out, "2");
}
#[test]
fn single_record_no_overwrite() {
assert_eq!(
nu!("
{a: 1, b: 5} | merge {c: 2} | to nuon
")
.out,
"{a: 1, b: 5, c: 2}"
);
}
#[test]
fn single_record_overwrite() {
assert_eq!(
nu!("
{a: 1, b: 2} | merge {a: 2} | to nuon
")
.out,
"{a: 2, b: 2}"
);
}
#[test]
fn single_row_table_overwrite() {
assert_eq!(
nu!("
[[a b]; [1 4]] | merge [[a b]; [2 4]] | to nuon
")
.out,
"[[a, b]; [2, 4]]"
);
}
#[test]
fn single_row_table_no_overwrite() {
assert_eq!(
nu!("
[[a b]; [1 4]] | merge [[c d]; [2 4]] | to nuon
")
.out,
"[[a, b, c, d]; [1, 4, 2, 4]]"
);
}
#[test]
fn multi_row_table_no_overwrite() {
assert_eq!(
nu!("
[[a b]; [1 4] [8 9] [9 9]] | merge [[c d]; [2 4]] | to nuon
")
.out,
"[{a: 1, b: 4, c: 2, d: 4}, {a: 8, b: 9}, {a: 9, b: 9}]"
);
}
#[test]
fn multi_row_table_overwrite() {
assert_eq!(
nu!("
[[a b]; [1 4] [8 9] [9 9]] | merge [[a b]; [7 7]] | to nuon
")
.out,
"[[a, b]; [7, 7], [8, 9], [9, 9]]"
);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/open.rs | crates/nu-command/tests/commands/open.rs | use std::path::PathBuf;
use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use rstest::rstest;
#[test]
fn parses_file_with_uppercase_extension() {
Playground::setup("open_test_uppercase_extension", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"nu.zion.JSON",
r#"{
"glossary": {
"GlossDiv": {
"GlossList": {
"GlossEntry": {
"ID": "SGML"
}
}
}
}
}"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open nu.zion.JSON
| get glossary.GlossDiv.GlossList.GlossEntry.ID
"#);
assert_eq!(actual.out, "SGML");
})
}
#[test]
fn parses_file_with_multiple_extensions() {
Playground::setup("open_test_multiple_extensions", |dirs, sandbox| {
sandbox.with_files(&[
FileWithContent("file.tar.gz", "this is a tar.gz file"),
FileWithContent("file.tar.xz", "this is a tar.xz file"),
]);
let actual = nu!(cwd: dirs.test(), r#"
hide "from tar.gz" ;
hide "from gz" ;
def "from tar.gz" [] { 'opened tar.gz' } ;
def "from gz" [] { 'opened gz' } ;
open file.tar.gz
"#);
assert_eq!(actual.out, "opened tar.gz");
let actual2 = nu!(cwd: dirs.test(), r#"
hide "from tar.xz" ;
hide "from xz" ;
hide "from tar" ;
def "from tar" [] { 'opened tar' } ;
def "from xz" [] { 'opened xz' } ;
open file.tar.xz
"#);
assert_eq!(actual2.out, "opened xz");
})
}
#[test]
fn parses_dotfile() {
Playground::setup("open_test_dotfile", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
".gitignore",
r#"
/target/
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
hide "from gitignore" ;
def "from gitignore" [] { 'opened gitignore' } ;
open .gitignore
"#);
assert_eq!(actual.out, "opened gitignore");
})
}
#[test]
fn parses_csv() {
Playground::setup("open_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"nu.zion.csv",
r#"
author,lang,source
JT Turner,Rust,New Zealand
Andres N. Robalino,Rust,Ecuador
Yehuda Katz,Rust,Estados Unidos
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open nu.zion.csv
| where author == "Andres N. Robalino"
| get source.0
"#);
assert_eq!(actual.out, "Ecuador");
})
}
// sample.db has the following format:
//
// ╭─────────┬────────────────╮
// │ strings │ [table 6 rows] │
// │ ints │ [table 5 rows] │
// │ floats │ [table 4 rows] │
// ╰─────────┴────────────────╯
//
// In this case, this represents a sqlite database
// with three tables named `strings`, `ints`, and `floats`.
//
// Each table has different columns. `strings` has `x` and `y`, while
// `ints` has just `z`, and `floats` has only the column `f`. In general, when working
// with sqlite, one will want to select a single table, e.g.:
//
// open sample.db | get ints
// ╭───┬──────╮
// │ # │ z │
// ├───┼──────┤
// │ 0 │ 1 │
// │ 1 │ 42 │
// │ 2 │ 425 │
// │ 3 │ 4253 │
// │ 4 │ │
// ╰───┴──────╯
#[cfg(feature = "sqlite")]
#[test]
fn parses_sqlite() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample.db
| columns
| length
");
assert_eq!(actual.out, "3");
}
#[cfg(feature = "sqlite")]
#[test]
fn parses_sqlite_get_column_name() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample.db
| get strings
| get x.0
");
assert_eq!(actual.out, "hello");
}
#[test]
fn parses_toml() {
let actual = nu!(
cwd: "tests/fixtures/formats",
"open cargo_sample.toml | get package.edition"
);
assert_eq!(actual.out, "2018");
}
#[test]
fn parses_tsv() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open caco3_plastics.tsv
| first
| get origin
");
assert_eq!(actual.out, "SPAIN")
}
#[test]
fn parses_json() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open sgml_description.json
| get glossary.GlossDiv.GlossList.GlossEntry.GlossSee
");
assert_eq!(actual.out, "markup")
}
#[test]
fn parses_xml() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open jt.xml
| get content
| where tag == channel
| get content
| flatten
| where tag == item
| get content
| flatten
| where tag == guid
| get content.0.content.0
");
assert_eq!(actual.out, "https://www.jntrnr.com/off-to-new-adventures/")
}
#[test]
fn errors_if_file_not_found() {
let actual = nu!(
cwd: "tests/fixtures/formats",
"open i_dont_exist.txt"
);
// Common error code between unixes and Windows for "No such file or directory"
//
// This seems to be not directly affected by localization compared to the OS
// provided error message
assert!(actual.err.contains("nu::shell::io::file_not_found"));
assert!(
actual.err.contains(
&PathBuf::from_iter(["tests", "fixtures", "formats", "i_dont_exist.txt"])
.display()
.to_string()
)
);
}
#[test]
fn open_wildcard() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open *.nu | where $it =~ echo | length
");
assert_eq!(actual.out, "3")
}
#[test]
fn open_multiple_files() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open caco3_plastics.csv caco3_plastics.tsv | get tariff_item | math sum
");
assert_eq!(actual.out, "58309279992")
}
#[test]
fn test_open_block_command() {
let actual = nu!(
cwd: "tests/fixtures/formats",
r#"
def "from blockcommandparser" [] { lines | split column ",|," }
let values = (open sample.blockcommandparser)
print ($values | get column0 | get 0)
print ($values | get column1 | get 0)
print ($values | get column0 | get 1)
print ($values | get column1 | get 1)
"#
);
assert_eq!(actual.out, "abcd")
}
#[test]
fn test_open_with_converter_flags() {
// https://github.com/nushell/nushell/issues/13722
let actual = nu!(
cwd: "tests/fixtures/formats",
r#"
def "from blockcommandparser" [ --flag ] { if $flag { "yes" } else { "no" } }
open sample.blockcommandparser
"#
);
assert_eq!(actual.out, "no")
}
#[test]
fn open_ignore_ansi() {
Playground::setup("open_test_ansi", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("nu.zion.txt")]);
let actual = nu!(cwd: dirs.test(), "
ls | find nu.zion | get 0 | get name | open $in
");
assert!(actual.err.is_empty());
})
}
#[test]
fn open_no_parameter() {
let actual = nu!("open");
assert!(actual.err.contains("needs filename"));
}
#[rstest]
#[case("a]c")]
#[case("a[c")]
#[case("a[bc]d")]
#[case("a][c")]
fn open_files_with_glob_metachars(#[case] src_name: &str) {
Playground::setup("open_test_with_glob_metachars", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(src_name, "hello")]);
let src = dirs.test().join(src_name);
let actual = nu!(
cwd: dirs.test(),
format!(
"open '{}'",
src.display(),
)
);
assert!(actual.err.is_empty());
assert!(actual.out.contains("hello"));
// also test for variables.
let actual = nu!(
cwd: dirs.test(),
format!(
"let f = '{}'; open $f",
src.display(),
)
);
assert!(actual.err.is_empty());
assert!(actual.out.contains("hello"));
});
}
#[cfg(not(windows))]
#[rstest]
#[case("a]?c")]
#[case("a*.?c")]
// windows doesn't allow filename with `*`.
fn open_files_with_glob_metachars_nw(#[case] src_name: &str) {
open_files_with_glob_metachars(src_name);
}
#[test]
fn open_files_inside_glob_metachars_dir() {
Playground::setup("open_files_inside_glob_metachars_dir", |dirs, sandbox| {
let sub_dir = "test[]";
sandbox
.within(sub_dir)
.with_files(&[FileWithContent("test_file.txt", "hello")]);
let actual = nu!(
cwd: dirs.test().join(sub_dir),
"open test_file.txt",
);
assert!(actual.err.is_empty());
assert!(actual.out.contains("hello"));
});
}
#[test]
fn test_content_types_with_open_raw() {
Playground::setup("open_files_content_type_test", |dirs, _| {
let result = nu!(cwd: dirs.formats(), "open --raw random_numbers.csv | metadata");
assert!(result.out.contains("text/csv"));
let result = nu!(cwd: dirs.formats(), "open --raw caco3_plastics.tsv | metadata");
assert!(result.out.contains("text/tab-separated-values"));
let result = nu!(cwd: dirs.formats(), "open --raw sample-simple.json | metadata");
assert!(result.out.contains("application/json"));
let result = nu!(cwd: dirs.formats(), "open --raw sample.ini | metadata");
assert!(result.out.contains("text/plain"));
let result = nu!(cwd: dirs.formats(), "open --raw sample_data.xlsx | metadata");
assert!(result.out.contains("vnd.openxmlformats-officedocument"));
let result = nu!(cwd: dirs.formats(), "open --raw sample_def.nu | metadata");
assert!(result.out.contains("application/x-nuscript"));
let result = nu!(cwd: dirs.formats(), "open --raw sample.eml | metadata");
assert!(result.out.contains("message/rfc822"));
let result = nu!(cwd: dirs.formats(), "open --raw cargo_sample.toml | metadata");
assert!(result.out.contains("text/x-toml"));
let result = nu!(cwd: dirs.formats(), "open --raw appveyor.yml | metadata");
assert!(result.out.contains("application/yaml"));
})
}
#[test]
fn test_metadata_without_raw() {
Playground::setup("open_files_content_type_test", |dirs, _| {
let result = nu!(cwd: dirs.formats(), "(open random_numbers.csv | metadata | get content_type?) == null");
assert_eq!(result.out, "true");
let result = nu!(cwd: dirs.formats(), "open random_numbers.csv | metadata | get source?");
assert!(result.out.contains("random_numbers.csv"));
let result = nu!(cwd: dirs.formats(), "(open caco3_plastics.tsv | metadata | get content_type?) == null");
assert_eq!(result.out, "true");
let result = nu!(cwd: dirs.formats(), "open caco3_plastics.tsv | metadata | get source?");
assert!(result.out.contains("caco3_plastics.tsv"));
let result = nu!(cwd: dirs.formats(), "(open sample-simple.json | metadata | get content_type?) == null");
assert_eq!(result.out, "true");
let result = nu!(cwd: dirs.formats(), "open sample-simple.json | metadata | get source?");
assert!(result.out.contains("sample-simple.json"));
// Only when not using nu_plugin_formats
let result = nu!(cwd: dirs.formats(), "open sample.ini | metadata");
assert!(result.out.contains("text/plain"));
let result = nu!(cwd: dirs.formats(), "open sample.ini | metadata | get source?");
assert!(result.out.contains("sample.ini"));
let result = nu!(cwd: dirs.formats(), "(open sample_data.xlsx | metadata | get content_type?) == null");
assert_eq!(result.out, "true");
let result = nu!(cwd: dirs.formats(), "open sample_data.xlsx | metadata | get source?");
assert!(result.out.contains("sample_data.xlsx"));
let result = nu!(cwd: dirs.formats(), "open sample_def.nu | metadata | get content_type?");
assert_eq!(result.out, "application/x-nuscript");
let result = nu!(cwd: dirs.formats(), "open sample_def.nu | metadata | get source?");
assert!(result.out.contains("sample_def"));
// Only when not using nu_plugin_formats
let result = nu!(cwd: dirs.formats(), "open sample.eml | metadata | get content_type?");
assert_eq!(result.out, "message/rfc822");
let result = nu!(cwd: dirs.formats(), "open sample.eml | metadata | get source?");
assert!(result.out.contains("sample.eml"));
let result = nu!(cwd: dirs.formats(), "(open cargo_sample.toml | metadata | get content_type?) == null");
assert_eq!(result.out, "true");
let result = nu!(cwd: dirs.formats(), "open cargo_sample.toml | metadata | get source?");
assert!(result.out.contains("cargo_sample.toml"));
let result =
nu!(cwd: dirs.formats(), "(open appveyor.yml | metadata | get content_type?) == null");
assert_eq!(result.out, "true");
let result = nu!(cwd: dirs.formats(), "open appveyor.yml | metadata | get source?");
assert!(result.out.contains("appveyor.yml"));
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/par_each.rs | crates/nu-command/tests/commands/par_each.rs | use nu_test_support::nu;
#[test]
fn par_each_does_not_flatten_nested_structures() {
// This is a regression test for issue #8497
let actual = nu!("[1 2 3] | par-each { |it| [$it, $it] } | sort | to json --raw");
assert_eq!(actual.out, "[[1,1],[2,2],[3,3]]");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/complete.rs | crates/nu-command/tests/commands/complete.rs | use nu_test_support::nu;
#[test]
fn basic_stdout() {
let without_complete = nu!(r#"
nu --testbin cococo test
"#);
let with_complete = nu!(r#"
(nu --testbin cococo test | complete).stdout
"#);
assert_eq!(with_complete.out, without_complete.out);
}
#[test]
fn basic_exit_code() {
let with_complete = nu!(r#"
(nu --testbin cococo test | complete).exit_code
"#);
assert_eq!(with_complete.out, "0");
}
#[test]
fn error() {
let actual = nu!("not-found | complete");
assert!(actual.err.contains("Command `not-found` not found"));
}
#[test]
#[cfg(not(windows))]
fn capture_error_with_too_much_stderr_not_hang_nushell() {
use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::playground::Playground;
Playground::setup("external with many stderr message", |dirs, sandbox| {
let bytes: usize = 81920;
let mut large_file_body = String::with_capacity(bytes);
for _ in 0..bytes {
large_file_body.push('a');
}
sandbox.with_files(&[FileWithContent("a_large_file.txt", &large_file_body)]);
let actual =
nu!(cwd: dirs.test(), "sh -c 'cat a_large_file.txt 1>&2' | complete | get stderr");
assert_eq!(actual.out, large_file_body);
})
}
#[test]
#[cfg(not(windows))]
fn capture_error_with_too_much_stdout_not_hang_nushell() {
use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::playground::Playground;
Playground::setup("external with many stdout message", |dirs, sandbox| {
let bytes: usize = 81920;
let mut large_file_body = String::with_capacity(bytes);
for _ in 0..bytes {
large_file_body.push('a');
}
sandbox.with_files(&[FileWithContent("a_large_file.txt", &large_file_body)]);
let actual = nu!(cwd: dirs.test(), "sh -c 'cat a_large_file.txt' | complete | get stdout");
assert_eq!(actual.out, large_file_body);
})
}
#[test]
#[cfg(not(windows))]
fn capture_error_with_both_stdout_stderr_messages_not_hang_nushell() {
use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::playground::Playground;
Playground::setup(
"external with many stdout and stderr messages",
|dirs, sandbox| {
let script_body = r#"
x=$(printf '=%.0s' $(seq 40960))
echo $x
echo $x 1>&2
"#;
let expect_body = "=".repeat(40960);
sandbox.with_files(&[FileWithContent("test.sh", script_body)]);
// check for stdout
let actual = nu!(cwd: dirs.test(), "sh test.sh | complete | get stdout | str trim");
assert_eq!(actual.out, expect_body);
// check for stderr
let actual = nu!(cwd: dirs.test(), "sh test.sh | complete | get stderr | str trim");
assert_eq!(actual.out, expect_body);
},
)
}
#[test]
fn combined_pipe_redirection() {
let actual = nu!(
"$env.FOO = 'hello'; $env.BAR = 'world'; nu --testbin echo_env_mixed out-err FOO BAR o+e>| complete | get stdout"
);
assert_eq!(actual.out, "helloworld");
}
#[test]
fn err_pipe_redirection() {
let actual =
nu!("$env.FOO = 'hello'; nu --testbin echo_env_stderr FOO e>| complete | get stdout");
assert_eq!(actual.out, "hello");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/debug_info.rs | crates/nu-command/tests/commands/debug_info.rs | use nu_test_support::nu;
#[test]
fn runs_successfully() {
let actual = nu!("debug info");
assert_eq!(actual.err, "");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/tee.rs | crates/nu-command/tests/commands/tee.rs | use nu_test_support::{fs::file_contents, nu, playground::Playground};
#[test]
fn tee_save_values_to_file() {
Playground::setup("tee_save_values_to_file_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
r#"1..5 | tee { save copy.txt } | to text"#
);
assert_eq!("12345", output.out);
assert_eq!(
"1\n2\n3\n4\n5\n",
file_contents(dirs.test().join("copy.txt"))
);
})
}
#[test]
fn tee_save_stdout_to_file() {
Playground::setup("tee_save_stdout_to_file_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
r#"
$env.FOO = "teststring"
nu --testbin echo_env FOO | tee { save copy.txt }
"#
);
assert_eq!("teststring", output.out);
assert_eq!("teststring\n", file_contents(dirs.test().join("copy.txt")));
})
}
#[test]
fn tee_save_stderr_to_file() {
Playground::setup("tee_save_stderr_to_file_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
"\
$env.FOO = \"teststring\"; \
do { nu --testbin echo_env_stderr FOO } | \
tee --stderr { save copy.txt } | \
complete | \
get stderr
"
);
assert_eq!("teststring", output.out);
assert_eq!("teststring\n", file_contents(dirs.test().join("copy.txt")));
})
}
#[test]
fn tee_single_value_streamable() {
let actual = nu!("'Hello, world!' | tee { print -e } | print");
assert!(actual.status.success());
assert_eq!("Hello, world!", actual.out);
// FIXME: note the lack of newline: this is a consequence of converting the string to a stream
// for now, but most likely the printer should be checking whether a string stream ends with a
// newline and adding it unless no_newline is true
assert_eq!("Hello, world!", actual.err);
}
#[test]
fn tee_single_value_non_streamable() {
// Non-streamable values don't have any synchronization point, so we have to wait.
let actual = nu!("500 | tee { print -e } | print; sleep 1sec");
assert!(actual.status.success());
assert_eq!("500", actual.out);
assert_eq!("500\n", actual.err);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/slice.rs | crates/nu-command/tests/commands/slice.rs | use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn selects_a_row() {
Playground::setup("slice_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("notes.txt"), EmptyFile("tests.txt")]);
let actual = nu!(cwd: dirs.test(), "
ls
| sort-by name
| slice 0..0
| get name.0
");
assert_eq!(actual.out, "notes.txt");
});
}
#[test]
fn selects_some_rows() {
Playground::setup("slice_test_2", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("notes.txt"),
EmptyFile("tests.txt"),
EmptyFile("persons.txt"),
]);
let actual = nu!(cwd: dirs.test(), "
ls
| get name
| slice 1..2
| length
");
assert_eq!(actual.out, "2");
});
}
#[test]
fn negative_indices() {
Playground::setup("slice_test_negative_indices", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("notes.txt"),
EmptyFile("tests.txt"),
EmptyFile("persons.txt"),
]);
let actual = nu!(cwd: dirs.test(), "
ls
| get name
| slice (-1..)
| length
");
assert_eq!(actual.out, "1");
});
}
#[test]
fn zero_to_zero_exclusive() {
let actual = nu!(r#"[0 1 2 3] | slice 0..<0 | to nuon"#);
assert_eq!(actual.out, "[]");
}
#[test]
fn to_negative_one_inclusive() {
let actual = nu!(r#"[0 1 2 3] | slice 2..-1 | to nuon"#);
assert_eq!(actual.out, "[2, 3]");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/first.rs | crates/nu-command/tests/commands/first.rs | use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn gets_first_rows_by_amount() {
Playground::setup("first_test_1", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("los.txt"),
EmptyFile("tres.txt"),
EmptyFile("amigos.txt"),
EmptyFile("arepas.clu"),
]);
let actual = nu!(cwd: dirs.test(), "ls | first 3 | length");
assert_eq!(actual.out, "3");
})
}
#[test]
fn gets_all_rows_if_amount_higher_than_all_rows() {
Playground::setup("first_test_2", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("los.txt"),
EmptyFile("tres.txt"),
EmptyFile("amigos.txt"),
EmptyFile("arepas.clu"),
]);
let actual = nu!(
cwd: dirs.test(), "ls | first 99 | length");
assert_eq!(actual.out, "4");
})
}
#[test]
fn gets_first_row_when_no_amount_given() {
Playground::setup("first_test_3", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("caballeros.txt"), EmptyFile("arepas.clu")]);
// FIXME: We should probably change first to return a one row table instead of a record here
let actual = nu!(cwd: dirs.test(), "ls | first | values | length");
assert_eq!(actual.out, "4");
})
}
#[test]
fn gets_first_row_as_list_when_amount_given() {
let actual = nu!("[1, 2, 3] | first 1 | describe");
assert_eq!(actual.out, "list<int>");
}
#[test]
fn gets_first_bytes() {
let actual = nu!("(0x[aa bb cc] | first 2) == 0x[aa bb]");
assert_eq!(actual.out, "true");
}
#[test]
fn gets_first_byte() {
let actual = nu!("0x[aa bb cc] | first");
assert_eq!(actual.out, "170");
}
#[test]
fn gets_first_bytes_from_stream() {
let actual = nu!("(1.. | each { 0x[aa bb cc] } | bytes collect | first 2) == 0x[aa bb]");
assert_eq!(actual.out, "true");
}
#[test]
fn gets_first_byte_from_stream() {
let actual = nu!("1.. | each { 0x[aa bb cc] } | bytes collect | first");
assert_eq!(actual.out, "170");
}
#[test]
// covers a situation where `first` used to behave strangely on list<binary> input
fn works_with_binary_list() {
let actual = nu!("([0x[01 11]] | first) == 0x[01 11]");
assert_eq!(actual.out, "true");
}
#[test]
fn errors_on_negative_rows() {
let actual = nu!("[1, 2, 3] | first -10");
assert!(actual.err.contains("use a positive value"));
}
#[test]
fn does_not_error_on_empty_list_when_no_rows_given() {
let actual = nu!("[] | first | describe");
assert!(actual.out.contains("nothing"));
}
#[test]
fn error_on_empty_list_when_no_rows_given_in_strict_mode() {
let actual = nu!("[] | first --strict | describe");
assert!(actual.err.contains("index too large"));
}
#[test]
fn gets_first_bytes_and_drops_content_type() {
let actual = nu!(format!(
"open {} | first 3 | metadata | get content_type? | describe",
file!(),
));
assert_eq!(actual.out, "nothing");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/ignore.rs | crates/nu-command/tests/commands/ignore.rs | use nu_test_support::nu;
#[test]
fn ignore_still_causes_stream_to_be_consumed_fully() {
let result = nu!("[foo bar] | each { |val| print $val; $val } | ignore");
assert_eq!("foobar", result.out);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/break_.rs | crates/nu-command/tests/commands/break_.rs | use nu_test_support::nu;
#[test]
fn break_for_loop() {
let actual = nu!("
for i in 1..10 { if $i == 2 { break }; print $i }
");
assert_eq!(actual.out, "1");
}
#[test]
fn break_while_loop() {
let actual = nu!(r#" while true { break }; print "hello" "#);
assert_eq!(actual.out, "hello");
}
#[test]
fn break_outside_loop() {
let actual = nu!(r#"break"#);
assert!(actual.err.contains("not_in_a_loop"));
let actual = nu!(r#"do { break }"#);
assert!(actual.err.contains("not_in_a_loop"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/where_.rs | crates/nu-command/tests/commands/where_.rs | use nu_test_support::nu;
#[test]
fn filters_by_unit_size_comparison() {
let actual = nu!(
cwd: "tests/fixtures/formats",
"ls | where size > 1kib | sort-by size | get name | first | str trim"
);
assert_eq!(actual.out, "cargo_sample.toml");
}
#[test]
fn filters_with_nothing_comparison() {
let actual = nu!(
r#"'[{"foo": 3}, {"foo": null}, {"foo": 4}]' | from json | get foo | compact | where $it > 1 | math sum"#
);
assert_eq!(actual.out, "7");
}
#[test]
fn where_inside_block_works() {
let actual = nu!("{|x| ls | where $it =~ 'foo' } | describe");
assert_eq!(actual.out, "closure");
}
#[test]
fn it_inside_complex_subexpression() {
let actual = nu!(r#"1..10 | where [($it * $it)].0 > 40 | to nuon"#);
assert_eq!(actual.out, r#"[7, 8, 9, 10]"#)
}
#[test]
fn filters_with_0_arity_block() {
let actual = nu!("[1 2 3 4] | where {|| $in < 3 } | to nuon");
assert_eq!(actual.out, "[1, 2]");
}
#[test]
fn filters_with_1_arity_block() {
let actual = nu!("[1 2 3 6 7 8] | where {|e| $e < 5 } | to nuon");
assert_eq!(actual.out, "[1, 2, 3]");
}
#[test]
fn unique_env_each_iteration() {
let actual = nu!(
cwd: "tests/fixtures/formats",
"[1 2] | where {|| print ($env.PWD | str ends-with 'formats') | cd '/' | true } | to nuon"
);
assert_eq!(actual.out, "truetrue[1, 2]");
}
#[test]
fn where_in_table() {
let actual = nu!(
r#"'[{"name": "foo", "size": 3}, {"name": "foo", "size": 2}, {"name": "bar", "size": 4}]' | from json | where name in ["foo"] | get size | math sum"#
);
assert_eq!(actual.out, "5");
}
#[test]
fn where_not_in_table() {
let actual = nu!(
r#"'[{"name": "foo", "size": 3}, {"name": "foo", "size": 2}, {"name": "bar", "size": 4}]' | from json | where name not-in ["foo"] | get size | math sum"#
);
assert_eq!(actual.out, "4");
}
#[test]
fn where_uses_enumerate_index() {
let actual = nu!("[7 8 9 10] | enumerate | where {|el| $el.index < 2 } | to nuon");
assert_eq!(actual.out, "[[index, item]; [0, 7], [1, 8]]");
}
#[cfg(feature = "sqlite")]
#[test]
fn binary_operator_comparisons() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample.db
| get ints
| first 4
| where z > 4200
| get z.0
");
assert_eq!(actual.out, "4253");
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample.db
| get ints
| first 4
| where z >= 4253
| get z.0
");
assert_eq!(actual.out, "4253");
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample.db
| get ints
| first 4
| where z < 10
| get z.0
");
assert_eq!(actual.out, "1");
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample.db
| get ints
| first 4
| where z <= 1
| get z.0
");
assert_eq!(actual.out, "1");
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample.db
| get ints
| where z != 1
| first
| get z
");
assert_eq!(actual.out, "42");
}
#[cfg(feature = "sqlite")]
#[test]
fn contains_operator() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample.db
| get strings
| where x =~ ell
| length
");
assert_eq!(actual.out, "4");
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample.db
| get strings
| where x !~ ell
| length
");
assert_eq!(actual.out, "2");
}
#[test]
fn fail_on_non_iterator() {
let actual = nu!(r#"{"name": "foo", "size": 3} | where name == "foo""#);
assert!(actual.err.contains("command doesn't support"));
}
// Test that filtering on columns that might be missing/null works
#[test]
fn where_gt_null() {
let actual = nu!("[{foo: 123} {}] | where foo? > 10 | to nuon");
assert_eq!(actual.out, "[[foo]; [123]]");
}
#[test]
fn has_operator() {
let actual = nu!(
r#"[[name, children]; [foo, [a, b]], [bar [b, c]], [baz, [c, d]]] | where children has "a" | to nuon"#
);
assert_eq!(actual.out, r#"[[name, children]; [foo, [a, b]]]"#);
let actual = nu!(
r#"[[name, children]; [foo, [a, b]], [bar [b, c]], [baz, [c, d]]] | where children not-has "a" | to nuon"#
);
assert_eq!(
actual.out,
r#"[[name, children]; [bar, [b, c]], [baz, [c, d]]]"#
);
let actual = nu!(r#"{foo: 1} has foo"#);
assert_eq!(actual.out, "true");
let actual = nu!(r#"{foo: 1} has bar "#);
assert_eq!(actual.out, "false");
}
#[test]
fn stored_condition() {
let actual = nu!(r#"let cond = { $in mod 2 == 0 }; 1..10 | where $cond | to nuon"#);
assert_eq!(actual.out, r#"[2, 4, 6, 8, 10]"#)
}
#[test]
fn nested_stored_condition() {
let actual =
nu!(r#"let nested = {cond: { $in mod 2 == 0 }}; 1..10 | where $nested.cond | to nuon"#);
assert_eq!(actual.out, r#"[2, 4, 6, 8, 10]"#)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/fill.rs | crates/nu-command/tests/commands/fill.rs | use nu_test_support::nu;
#[test]
fn string_fill_plain() {
let actual = nu!(r#""abc" | fill --alignment center --character "+" --width 5"#);
assert_eq!(actual.out, "+abc+");
}
#[test]
fn string_fill_fancy() {
let actual = nu!(r#"
$"(ansi red)a(ansi green)\u{65}\u{308}(ansi cyan)c(ansi reset)"
| fill --alignment center --character "+" --width 5
"#);
assert_eq!(
actual.out,
"+\u{1b}[31ma\u{1b}[32me\u{308}\u{1b}[36mc\u{1b}[0m+"
);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/reverse.rs | crates/nu-command/tests/commands/reverse.rs | use nu_test_support::nu;
#[test]
fn can_get_reverse_first() {
let actual = nu!(
cwd: "tests/fixtures/formats",
"ls | sort-by name | reverse | first | get name | str trim "
);
assert_eq!(actual.out, "utf16.ini");
}
#[test]
fn fail_on_non_iterator() {
let actual = nu!("1 | reverse");
assert!(actual.err.contains("command doesn't support"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/use_.rs | crates/nu-command/tests/commands/use_.rs | use nu_test_support::fs::Stub::{FileWithContent, FileWithContentToBeTrimmed};
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn use_module_file_within_block() {
Playground::setup("use_test_1", |dirs, nu| {
let file = dirs.test().join("spam.nu");
nu.with_files(&[FileWithContent(
file.as_os_str().to_str().unwrap(),
r#"
export def foo [] {
echo "hello world"
}
"#,
)]);
let actual = nu!(cwd: dirs.test(), "
def bar [] {
use spam.nu foo;
foo
};
bar
");
assert_eq!(actual.out, "hello world");
})
}
#[test]
fn use_keeps_doc_comments() {
Playground::setup("use_doc_comments", |dirs, nu| {
let file = dirs.test().join("spam.nu");
nu.with_files(&[FileWithContent(
file.as_os_str().to_str().unwrap(),
r#"
# this is my foo command
export def foo [
x:string # this is an x parameter
] {
echo "hello world"
}
"#,
)]);
let actual = nu!(cwd: dirs.test(), "
use spam.nu foo;
help foo
");
assert!(actual.out.contains("this is my foo command"));
assert!(actual.out.contains("this is an x parameter"));
})
}
#[test]
fn use_eval_export_env() {
Playground::setup("use_eval_export_env", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
export-env { $env.FOO = 'foo' }
"#,
)]);
let inp = &[r#"use spam.nu"#, r#"$env.FOO"#];
let actual = nu!(cwd: dirs.test(), inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn use_eval_export_env_hide() {
Playground::setup("use_eval_export_env", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
export-env { hide-env FOO }
"#,
)]);
let inp = &[r#"$env.FOO = 'foo'"#, r#"use spam.nu"#, r#"$env.FOO"#];
let actual = nu!(cwd: dirs.test(), inp.join("; "));
assert!(actual.err.contains("not_found"));
})
}
#[test]
fn use_do_cd() {
Playground::setup("use_do_cd", |dirs, sandbox| {
sandbox
.mkdir("test1/test2")
.with_files(&[FileWithContentToBeTrimmed(
"test1/test2/spam.nu",
r#"
export-env { cd test1/test2 }
"#,
)]);
let inp = &[r#"use test1/test2/spam.nu"#, r#"$env.PWD | path basename"#];
let actual = nu!(cwd: dirs.test(), inp.join("; "));
assert_eq!(actual.out, "test2");
})
}
#[test]
fn use_do_cd_file_relative() {
Playground::setup("use_do_cd_file_relative", |dirs, sandbox| {
sandbox
.mkdir("test1/test2")
.with_files(&[FileWithContentToBeTrimmed(
"test1/test2/spam.nu",
r#"
export-env { cd ($env.FILE_PWD | path join '..') }
"#,
)]);
let inp = &[r#"use test1/test2/spam.nu"#, r#"$env.PWD | path basename"#];
let actual = nu!(cwd: dirs.test(), inp.join("; "));
assert_eq!(actual.out, "test1");
})
}
#[test]
fn use_dont_cd_overlay() {
Playground::setup("use_dont_cd_overlay", |dirs, sandbox| {
sandbox
.mkdir("test1/test2")
.with_files(&[FileWithContentToBeTrimmed(
"test1/test2/spam.nu",
r#"
export-env {
overlay new spam
cd test1/test2
overlay hide spam
}
"#,
)]);
let inp = &[r#"use test1/test2/spam.nu"#, r#"$env.PWD | path basename"#];
let actual = nu!(cwd: dirs.test(), inp.join("; "));
assert_eq!(actual.out, "use_dont_cd_overlay");
})
}
#[test]
fn use_export_env_combined() {
Playground::setup("use_is_scoped", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
def foo [] { 'foo' }
alias bar = foo
export-env { $env.FOO = (bar) }
"#,
)]);
let inp = &[r#"use spam.nu"#, r#"$env.FOO"#];
let actual = nu!(cwd: dirs.test(), inp.join("; "));
assert_eq!(actual.out, "foo");
})
}
#[test]
fn use_module_creates_accurate_did_you_mean_1() {
let actual = nu!(r#"
module spam { export def foo [] { "foo" } }; use spam; foo
"#);
assert!(actual.err.contains("Did you mean `spam foo`"));
}
#[test]
fn use_module_creates_accurate_did_you_mean_2() {
let actual = nu!(r#"
module spam { export def foo [] { "foo" } }; foo
"#);
assert!(
actual
.err
.contains("A command with that name exists in module `spam`")
);
}
#[test]
fn use_main_1() {
let inp = &[
r#"module spam { export def main [] { "spam" } }"#,
r#"use spam"#,
r#"spam"#,
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn use_main_2() {
let inp = &[
r#"module spam { export def main [] { "spam" } }"#,
r#"use spam main"#,
r#"spam"#,
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn use_main_3() {
let inp = &[
r#"module spam { export def main [] { "spam" } }"#,
r#"use spam [ main ]"#,
r#"spam"#,
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn use_main_4() {
let inp = &[
r#"module spam { export def main [] { "spam" } }"#,
r#"use spam *"#,
r#"spam"#,
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn use_main_def_env() {
let inp = &[
r#"module spam { export def --env main [] { $env.SPAM = "spam" } }"#,
r#"use spam"#,
r#"spam"#,
r#"$env.SPAM"#,
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn use_main_def_known_external() {
// note: requires installed cargo
let inp = &[
r#"module cargo { export extern main [] }"#,
r#"use cargo"#,
r#"cargo --version"#,
];
let actual = nu!(&inp.join("; "));
assert!(actual.out.contains("cargo"));
}
#[test]
fn use_main_not_exported() {
let inp = &[
r#"module my-super-cool-and-unique-module-name { def main [] { "hi" } }"#,
r#"use my-super-cool-and-unique-module-name"#,
r#"my-super-cool-and-unique-module-name"#,
];
let actual = nu!(&inp.join("; "));
assert!(actual.err.contains("external_command"));
}
#[test]
fn use_sub_subname_error_if_not_from_submodule() {
let inp = r#"module spam { export def foo [] {}; export def bar [] {} }; use spam foo bar"#;
let actual = nu!(inp);
assert!(actual.err.contains("try `use <module> [<name1>, <name2>]`"))
}
#[test]
fn can_use_sub_subname_from_submodule() {
let inp =
r#"module spam { export module foo { export def bar [] {"bar"} } }; use spam foo bar; bar"#;
let actual = nu!(inp);
assert_eq!(actual.out, "bar")
}
#[test]
fn test_use_with_printing_file_pwd() {
Playground::setup("use_with_printing_file_pwd", |dirs, nu| {
let file = dirs.test().join("mod.nu");
nu.with_files(&[FileWithContent(
file.as_os_str().to_str().unwrap(),
r#"
export-env {
print $env.FILE_PWD
}
"#,
)]);
let actual = nu!(
cwd: dirs.test(),
"use ."
);
assert_eq!(actual.out, dirs.test().to_string_lossy());
});
}
#[test]
fn test_use_with_printing_current_file() {
Playground::setup("use_with_printing_current_file", |dirs, nu| {
let file = dirs.test().join("mod.nu");
nu.with_files(&[FileWithContent(
file.as_os_str().to_str().unwrap(),
r#"
export-env {
print $env.CURRENT_FILE
}
"#,
)]);
let actual = nu!(
cwd: dirs.test(),
"use ."
);
assert_eq!(actual.out, dirs.test().join("mod.nu").to_string_lossy());
});
}
#[test]
fn report_errors_in_export_env() {
let actual = nu!(r#"
module spam {
export-env { error make -u {msg: "reported"} }
}
use spam
"#);
assert!(actual.err.contains("reported"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/match_.rs | crates/nu-command/tests/commands/match_.rs | use nu_test_support::nu;
use nu_test_support::playground::Playground;
use std::fs;
#[test]
fn match_for_range() {
let actual = nu!(r#"match 3 { 1..10 => { print "success" } }"#);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success");
}
#[test]
fn match_for_range_unmatched() {
let actual = nu!(r#"match 11 { 1..10 => { print "failure" }, _ => { print "success" }}"#);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success");
}
#[test]
fn match_for_record() {
let actual = nu!("match {a: 11} { {a: $b} => { print $b }}");
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "11");
}
#[test]
fn match_for_record_shorthand() {
let actual = nu!("match {a: 12} { {$a} => { print $a }}");
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "12");
}
#[test]
fn match_list() {
let actual = nu!(
r#"match [1, 2] { [$a] => { print $"single: ($a)" }, [$b, $c] => {print $"double: ($b) ($c)"}}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "double: 1 2");
}
#[test]
fn match_list_rest_ignore() {
let actual = nu!(
r#"match [1, 2] { [$a, ..] => { print $"single: ($a)" }, [$b, $c] => {print $"double: ($b) ($c)"}}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "single: 1");
}
#[test]
fn match_list_rest() {
let actual = nu!(
r#"match [1, 2, 3] { [$a, ..$remainder] => { print $"single: ($a) ($remainder | math sum)" }, [$b, $c] => {print $"double: ($b) ($c)"}}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "single: 1 5");
}
#[test]
fn match_list_rest_empty() {
let actual = nu!(r#"match [1] { [1 ..$rest] => { $rest == [] } }"#);
assert_eq!(actual.out, "true");
}
#[test]
fn match_constant_1() {
let actual = nu!(
r#"match 2 { 1 => { print "failure"}, 2 => { print "success" }, 3 => { print "failure" }}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success");
}
#[test]
fn match_constant_2() {
let actual = nu!(
r#"match 2.3 { 1.4 => { print "failure"}, 2.3 => { print "success" }, 3 => { print "failure" }}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success");
}
#[test]
fn match_constant_3() {
let actual = nu!(
r#"match true { false => { print "failure"}, true => { print "success" }, 3 => { print "failure" }}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success");
}
#[test]
fn match_constant_4() {
let actual = nu!(
r#"match "def" { "abc" => { print "failure"}, "def" => { print "success" }, "ghi" => { print "failure" }}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success");
}
#[test]
fn match_constant_5() {
let actual = nu!(
r#"match 2019-08-23 { 2010-01-01 => { print "failure"}, 2019-08-23 => { print "success" }, 2020-02-02 => { print "failure" }}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success");
}
#[test]
fn match_constant_6() {
let actual = nu!(
r#"match 6sec { 2sec => { print "failure"}, 6sec => { print "success" }, 1min => { print "failure" }}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success");
}
#[test]
fn match_constant_7() {
let actual = nu!(
r#"match 1kib { 1kb => { print "failure"}, 1kib => { print "success" }, 2kb => { print "failure" }}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success");
}
#[test]
fn match_constant_8() {
let actual =
nu!(r#"match "foo" { r#'foo'# => { print "success" }, _ => { print "failure" } }"#);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success");
}
#[test]
fn match_null() {
let actual = nu!(r#"match null { null => { print "success"}, _ => { print "failure" }}"#);
assert_eq!(actual.out, "success");
}
#[test]
fn match_or_pattern() {
let actual = nu!(
r#"match {b: 7} { {a: $a} | {b: $b} => { print $"success: ($b)" }, _ => { print "failure" }}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success: 7");
}
#[test]
fn match_or_pattern_overlap_1() {
let actual = nu!(
r#"match {a: 7} { {a: $b} | {b: $b} => { print $"success: ($b)" }, _ => { print "failure" }}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success: 7");
}
#[test]
fn match_or_pattern_overlap_2() {
let actual = nu!(
r#"match {b: 7} { {a: $b} | {b: $b} => { print $"success: ($b)" }, _ => { print "failure" }}"#
);
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "success: 7");
}
#[test]
fn match_doesnt_overwrite_variable() {
let actual = nu!("let b = 100; match 55 { $b => {} }; print $b");
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert_eq!(actual.out, "100");
}
#[test]
fn match_with_guard() {
let actual = nu!("match [1 2 3] { [$x, ..] if $x mod 2 == 0 => { $x }, $x => { 2 } }");
assert_eq!(actual.out, "2");
}
#[test]
fn match_with_guard_block_as_guard() {
// this should work?
let actual =
nu!("match 4 { $x if { $x + 20 > 25 } => { 'good num' }, _ => { 'terrible num' } }");
assert!(actual.err.contains("Match guard not bool"));
}
#[test]
fn match_with_guard_parens_expr_as_guard() {
let actual = nu!("match 4 { $x if ($x + 20 > 25) => { 'good num' }, _ => { 'terrible num' } }");
assert_eq!(actual.out, "terrible num");
}
#[test]
fn match_with_guard_not_bool() {
let actual = nu!("match 4 { $x if $x + 1 => { 'err!()' }, _ => { 'unreachable!()' } }");
assert!(actual.err.contains("Match guard not bool"));
}
#[test]
fn match_with_guard_no_expr_after_if() {
let actual = nu!("match 4 { $x if => { 'err!()' }, _ => { 'unreachable!()' } }");
assert!(actual.err.contains("Match guard without an expression"));
}
#[test]
fn match_with_guard_multiarm() {
let actual = nu!("match 3 {1 | 2 | 3 if true => 'test'}");
assert_eq!(actual.out, "test");
}
#[test]
fn match_with_or_missing_expr() {
let actual = nu!("match $in { 1 | }");
assert!(actual.err.contains("expected pattern"));
}
#[test]
fn match_with_comment_1() {
Playground::setup("match_with_comment", |dirs, _| {
let data = r#"
match 1 {
# comment
_ => { print 'success' }
}
"#;
fs::write(dirs.root().join("match_test"), data).expect("Unable to write file");
let actual = nu!(
cwd: dirs.root(),
"source match_test"
);
assert_eq!(actual.out, "success");
});
}
#[test]
fn match_with_comment_2() {
Playground::setup("match_with_comment", |dirs, _| {
let data = r#"
match 1 {
_ => { print 'success' } # comment
}
"#;
fs::write(dirs.root().join("match_test"), data).expect("Unable to write file");
let actual = nu!(
cwd: dirs.root(),
"source match_test"
);
assert_eq!(actual.out, "success");
});
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/headers.rs | crates/nu-command/tests/commands/headers.rs | use nu_test_support::nu;
#[test]
fn headers_uses_first_row_as_header() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample_headers.xlsx
| get Sheet1
| headers
| get header0
| to json --raw");
assert_eq!(actual.out, r#"["r1c0","r2c0"]"#)
}
#[test]
fn headers_adds_missing_column_name() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open sample_headers.xlsx
| get Sheet1
| headers
| get column1
| to json --raw");
assert_eq!(actual.out, r#"["r1c1","r2c1"]"#)
}
#[test]
fn headers_handles_missing_values() {
let actual = nu!("
[{x: a, y: b}, {x: 1, y: 2}, {x: 1, z: 3}]
| headers
| to nuon
");
assert_eq!(actual.out, "[{a: 1, b: 2}, {a: 1}]")
}
#[test]
fn headers_invalid_column_type_empty_record() {
let actual = nu!("
[[a b]; [{}, 2], [3,4] ]
| headers");
assert!(
actual
.err
.contains("needs compatible type: Null, String, Bool, Float, Int")
);
}
#[test]
fn headers_invalid_column_type_record() {
let actual = nu!("
[[a b]; [1 (scope aliases)] [2 2]]
| headers");
assert!(
actual
.err
.contains("needs compatible type: Null, String, Bool, Float, Int")
);
}
#[test]
fn headers_invalid_column_type_array() {
let actual = nu!("
[[a b]; [[f,g], 2], [3,4] ]
| headers");
assert!(
actual
.err
.contains("needs compatible type: Null, String, Bool, Float, Int")
);
}
#[test]
fn headers_invalid_column_type_range() {
let actual = nu!("
[[a b]; [(1..5), 2], [3,4] ]
| headers");
assert!(
actual
.err
.contains("needs compatible type: Null, String, Bool, Float, Int")
);
}
#[test]
fn headers_invalid_column_type_duration() {
let actual = nu!("
[[a b]; [((date now) - (date now)), 2], [3,4] ]
| headers");
assert!(
actual
.err
.contains("needs compatible type: Null, String, Bool, Float, Int")
);
}
#[test]
fn headers_invalid_column_type_binary() {
let actual = nu!(r#"
[[a b]; [("aa" | into binary), 2], [3,4] ]
| headers"#);
assert!(
actual
.err
.contains("needs compatible type: Null, String, Bool, Float, Int")
);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/export_def.rs | crates/nu-command/tests/commands/export_def.rs | use nu_test_support::nu;
#[test]
fn export_subcommands_help() {
let actual = nu!("export def -h");
assert!(
actual
.out
.contains("Define a custom command and export it from a module")
);
}
#[test]
fn export_should_not_expose_arguments() {
// issue #16211
let actual = nu!(r#"
export def foo [bar: int] {}
scope variables
"#);
assert!(!actual.out.contains("bar"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/ls.rs | crates/nu-command/tests/commands/ls.rs | use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn lists_regular_files() {
Playground::setup("ls_test_1", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
]);
let actual = nu!(cwd: dirs.test(), "
ls
| length
");
assert_eq!(actual.out, "3");
})
}
#[test]
fn lists_regular_files_using_asterisk_wildcard() {
Playground::setup("ls_test_2", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("los.txt"),
EmptyFile("tres.txt"),
EmptyFile("amigos.txt"),
EmptyFile("arepas.clu"),
]);
let actual = nu!(cwd: dirs.test(), "
ls *.txt
| length
");
assert_eq!(actual.out, "3");
})
}
#[cfg(not(target_os = "windows"))]
#[test]
fn lists_regular_files_in_special_folder() {
Playground::setup("ls_test_3", |dirs, sandbox| {
sandbox
.mkdir("[abcd]")
.mkdir("[bbcd]")
.mkdir("abcd]")
.mkdir("abcd")
.mkdir("abcd/*")
.mkdir("abcd/?")
.with_files(&[EmptyFile("[abcd]/test.txt")])
.with_files(&[EmptyFile("abcd]/test.txt")])
.with_files(&[EmptyFile("abcd/*/test.txt")])
.with_files(&[EmptyFile("abcd/?/test.txt")])
.with_files(&[EmptyFile("abcd/?/test2.txt")]);
let actual = nu!(
cwd: dirs.test().join("abcd]"), format!(r#"ls | length"#));
assert_eq!(actual.out, "1");
let actual = nu!(
cwd: dirs.test(), format!(r#"ls abcd] | length"#));
assert_eq!(actual.out, "1");
let actual = nu!(
cwd: dirs.test().join("[abcd]"), format!(r#"ls | length"#));
assert_eq!(actual.out, "1");
let actual = nu!(
cwd: dirs.test().join("[bbcd]"), format!(r#"ls | length"#));
assert_eq!(actual.out, "0");
let actual = nu!(
cwd: dirs.test().join("abcd/*"), format!(r#"ls | length"#));
assert_eq!(actual.out, "1");
let actual = nu!(
cwd: dirs.test().join("abcd/?"), format!(r#"ls | length"#));
assert_eq!(actual.out, "2");
let actual = nu!(
cwd: dirs.test().join("abcd/*"), format!(r#"ls -D ../* | length"#));
assert_eq!(actual.out, "2");
let actual = nu!(
cwd: dirs.test().join("abcd/*"), format!(r#"ls ../* | length"#));
assert_eq!(actual.out, "2");
let actual = nu!(
cwd: dirs.test().join("abcd/?"), format!(r#"ls -D ../* | length"#));
assert_eq!(actual.out, "2");
let actual = nu!(
cwd: dirs.test().join("abcd/?"), format!(r#"ls ../* | length"#));
assert_eq!(actual.out, "2");
})
}
#[rstest::rstest]
#[case("j?.??.txt", 1)]
#[case("j????.txt", 2)]
#[case("?????.txt", 3)]
#[case("????c.txt", 1)]
#[case("ye??da.10.txt", 1)]
#[case("yehuda.?0.txt", 1)]
#[case("??????.10.txt", 2)]
#[case("[abcd]????.txt", 1)]
#[case("??[ac.]??.txt", 3)]
#[case("[ab]bcd/??.txt", 2)]
#[case("?bcd/[xy]y.txt", 2)]
#[case("?bcd/[xy]y.t?t", 2)]
#[case("[[]abcd[]].txt", 1)]
#[case("[[]?bcd[]].txt", 2)]
#[case("??bcd[]].txt", 2)]
#[case("??bcd].txt", 2)]
#[case("[[]?bcd].txt", 2)]
#[case("[[]abcd].txt", 1)]
#[case("[[][abcd]bcd[]].txt", 2)]
#[case("'[abcd].txt'", 1)]
#[case("'[bbcd].txt'", 1)]
fn lists_regular_files_using_question_mark(#[case] command: &str, #[case] expected: usize) {
Playground::setup("ls_test_3", |dirs, sandbox| {
sandbox.mkdir("abcd").mkdir("bbcd").with_files(&[
EmptyFile("abcd/xy.txt"),
EmptyFile("bbcd/yy.txt"),
EmptyFile("[abcd].txt"),
EmptyFile("[bbcd].txt"),
EmptyFile("yehuda.10.txt"),
EmptyFile("jt.10.txt"),
EmptyFile("jtabc.txt"),
EmptyFile("abcde.txt"),
EmptyFile("andres.10.txt"),
EmptyFile("chicken_not_to_be_picked_up.100.txt"),
]);
let actual = nu!(
cwd: dirs.test(), format!(r#"ls {command} | length"#));
assert_eq!(actual.out, expected.to_string());
})
}
#[test]
fn lists_regular_files_using_question_mark_wildcard() {
Playground::setup("ls_test_3", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.10.txt"),
EmptyFile("jt.10.txt"),
EmptyFile("andres.10.txt"),
EmptyFile("chicken_not_to_be_picked_up.100.txt"),
]);
let actual = nu!(cwd: dirs.test(), "
ls *.??.txt
| length
");
assert_eq!(actual.out, "3");
})
}
#[test]
fn lists_all_files_in_directories_from_stream() {
Playground::setup("ls_test_4", |dirs, sandbox| {
sandbox
.with_files(&[EmptyFile("root1.txt"), EmptyFile("root2.txt")])
.within("dir_a")
.with_files(&[EmptyFile("yehuda.10.txt"), EmptyFile("jt10.txt")])
.within("dir_b")
.with_files(&[
EmptyFile("andres.10.txt"),
EmptyFile("chicken_not_to_be_picked_up.100.txt"),
]);
let actual = nu!(cwd: dirs.test(), "
echo dir_a dir_b
| each { |it| ls $it }
| flatten | length
");
assert_eq!(actual.out, "4");
})
}
#[test]
fn does_not_fail_if_glob_matches_empty_directory() {
Playground::setup("ls_test_5", |dirs, sandbox| {
sandbox.within("dir_a");
let actual = nu!(cwd: dirs.test(), "
ls dir_a
| length
");
assert_eq!(actual.out, "0");
})
}
#[test]
fn fails_when_glob_doesnt_match() {
Playground::setup("ls_test_5", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("root1.txt"), EmptyFile("root2.txt")]);
let actual = nu!(
cwd: dirs.test(),
"ls root3*"
);
assert!(actual.err.contains("no matches found"));
})
}
#[test]
fn list_files_from_two_parents_up_using_multiple_dots() {
Playground::setup("ls_test_6", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yahuda.yaml"),
EmptyFile("jtjson"),
EmptyFile("andres.xml"),
EmptyFile("kevin.txt"),
]);
sandbox.within("foo").mkdir("bar");
let actual = nu!(
cwd: dirs.test().join("foo/bar"),
"
ls ... | length
"
);
assert_eq!(actual.out, "5");
let actual = nu!(
cwd: dirs.test().join("foo/bar"),
r#"ls ... | sort-by name | get name.0 | str replace -a '\' '/'"#
);
assert_eq!(actual.out, "../../andres.xml");
})
}
#[test]
fn lists_hidden_file_when_explicitly_specified() {
Playground::setup("ls_test_7", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("los.txt"),
EmptyFile("tres.txt"),
EmptyFile("amigos.txt"),
EmptyFile("arepas.clu"),
EmptyFile(".testdotfile"),
]);
let actual = nu!(cwd: dirs.test(), "
ls .testdotfile
| length
");
assert_eq!(actual.out, "1");
})
}
#[test]
fn lists_all_hidden_files_when_glob_contains_dot() {
Playground::setup("ls_test_8", |dirs, sandbox| {
sandbox
.with_files(&[
EmptyFile("root1.txt"),
EmptyFile("root2.txt"),
EmptyFile(".dotfile1"),
])
.within("dir_a")
.with_files(&[
EmptyFile("yehuda.10.txt"),
EmptyFile("jt10.txt"),
EmptyFile(".dotfile2"),
])
.within("dir_b")
.with_files(&[
EmptyFile("andres.10.txt"),
EmptyFile("chicken_not_to_be_picked_up.100.txt"),
EmptyFile(".dotfile3"),
]);
let actual = nu!(cwd: dirs.test(), "
ls **/.*
| length
");
assert_eq!(actual.out, "3");
})
}
#[test]
// TODO Remove this cfg value when we have an OS-agnostic way
// of creating hidden files using the playground.
#[cfg(unix)]
fn lists_all_hidden_files_when_glob_does_not_contain_dot() {
Playground::setup("ls_test_8", |dirs, sandbox| {
sandbox
.with_files(&[
EmptyFile("root1.txt"),
EmptyFile("root2.txt"),
EmptyFile(".dotfile1"),
])
.within("dir_a")
.with_files(&[
EmptyFile("yehuda.10.txt"),
EmptyFile("jt10.txt"),
EmptyFile(".dotfile2"),
])
.within(".dir_b")
.with_files(&[
EmptyFile("andres.10.txt"),
EmptyFile("chicken_not_to_be_picked_up.100.txt"),
EmptyFile(".dotfile3"),
]);
let actual = nu!(cwd: dirs.test(), "
ls **/*
| length
");
assert_eq!(actual.out, "5");
})
}
#[test]
// TODO Remove this cfg value when we have an OS-agnostic way
// of creating hidden files using the playground.
#[cfg(unix)]
fn glob_with_hidden_directory() {
Playground::setup("ls_test_8", |dirs, sandbox| {
sandbox.within(".dir_b").with_files(&[
EmptyFile("andres.10.txt"),
EmptyFile("chicken_not_to_be_picked_up.100.txt"),
EmptyFile(".dotfile3"),
]);
let actual = nu!(cwd: dirs.test(), "
ls **/*
| length
");
assert_eq!(actual.out, "");
assert!(actual.err.contains("No matches found"));
// will list files if provide `-a` flag.
let actual = nu!(cwd: dirs.test(), "
ls -a **/*
| length
");
assert_eq!(actual.out, "4");
})
}
#[test]
#[cfg(unix)]
fn fails_with_permission_denied() {
Playground::setup("ls_test_1", |dirs, sandbox| {
sandbox
.within("dir_a")
.with_files(&[EmptyFile("yehuda.11.txt"), EmptyFile("jt10.txt")]);
let actual_with_path_arg = nu!(cwd: dirs.test(), "
chmod 000 dir_a; ls dir_a
");
let actual_in_cwd = nu!(cwd: dirs.test(), "
chmod 100 dir_a; cd dir_a; ls
");
let get_uid = nu!(cwd: dirs.test(), "
id -u
");
let is_root = get_uid.out == "0";
assert!(actual_with_path_arg.err.contains("Permission denied") || is_root);
assert!(actual_in_cwd.err.contains("Permission denied") || is_root);
})
}
#[test]
fn lists_files_including_starting_with_dot() {
Playground::setup("ls_test_9", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
EmptyFile(".hidden1.txt"),
EmptyFile(".hidden2.txt"),
]);
let actual = nu!(cwd: dirs.test(), "
ls -a
| length
");
assert_eq!(actual.out, "5");
})
}
#[test]
fn list_all_columns() {
Playground::setup("ls_test_all_columns", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("Leonardo.yaml"),
EmptyFile("Raphael.json"),
EmptyFile("Donatello.xml"),
EmptyFile("Michelangelo.txt"),
]);
// Normal Operation
let actual = nu!(
cwd: dirs.test(),
"ls | columns | to md --list none"
);
let expected = ["name", "type", "size", "modified"].join("");
assert_eq!(actual.out, expected, "column names are incorrect for ls");
// Long
let actual = nu!(
cwd: dirs.test(),
"ls -l | columns | to md --list none"
);
let expected = {
#[cfg(unix)]
{
[
"name",
"type",
"target",
"readonly",
"mode",
"num_links",
"inode",
"user",
"group",
"size",
"created",
"accessed",
"modified",
]
.join("")
}
#[cfg(windows)]
{
[
"name", "type", "target", "readonly", "size", "created", "accessed", "modified",
]
.join("")
}
};
assert_eq!(
actual.out, expected,
"column names are incorrect for ls long"
);
});
}
#[test]
fn lists_with_directory_flag() {
Playground::setup("ls_test_flag_directory_1", |dirs, sandbox| {
sandbox
.within("dir_files")
.with_files(&[EmptyFile("nushell.json")])
.within("dir_empty");
let actual = nu!(cwd: dirs.test(), r#"
cd dir_empty;
['.' '././.' '..' '../dir_files' '../dir_files/*']
| each { |it| ls --directory ($it | into glob) }
| flatten
| get name
| to text
"#);
let expected = [".", ".", "..", "../dir_files", "../dir_files/nushell.json"].join("");
#[cfg(windows)]
let expected = expected.replace('/', "\\");
assert_eq!(
actual.out, expected,
"column names are incorrect for ls --directory (-D)"
);
});
}
#[test]
fn lists_with_directory_flag_without_argument() {
Playground::setup("ls_test_flag_directory_2", |dirs, sandbox| {
sandbox
.within("dir_files")
.with_files(&[EmptyFile("nushell.json")])
.within("dir_empty");
// Test if there are some files in the current directory
let actual = nu!(cwd: dirs.test(), "
cd dir_files;
ls --directory
| get name
| to text
");
let expected = ".";
assert_eq!(
actual.out, expected,
"column names are incorrect for ls --directory (-D)"
);
// Test if there is no file in the current directory
let actual = nu!(cwd: dirs.test(), "
cd dir_empty;
ls -D
| get name
| to text
");
let expected = ".";
assert_eq!(
actual.out, expected,
"column names are incorrect for ls --directory (-D)"
);
});
}
/// Rust's fs::metadata function is unable to read info for certain system files on Windows,
/// like the `C:\Windows\System32\Configuration` folder. https://github.com/rust-lang/rust/issues/96980
/// This test confirms that Nu can work around this successfully.
#[test]
#[cfg(windows)]
fn can_list_system_folder() {
// the awkward `ls Configuration* | where name == "Configuration"` thing is for speed;
// listing the entire System32 folder is slow and `ls Configuration*` alone
// might return more than 1 file someday
let file_type = nu!(cwd: "C:\\Windows\\System32", r#"ls Configuration* | where name == "Configuration" | get type.0"#);
assert_eq!(file_type.out, "dir");
let file_size = nu!(cwd: "C:\\Windows\\System32", r#"ls Configuration* | where name == "Configuration" | get size.0"#);
assert_ne!(file_size.out.trim(), "");
let file_modified = nu!(cwd: "C:\\Windows\\System32", r#"ls Configuration* | where name == "Configuration" | get modified.0"#);
assert_ne!(file_modified.out.trim(), "");
let file_accessed = nu!(cwd: "C:\\Windows\\System32", r#"ls -l Configuration* | where name == "Configuration" | get accessed.0"#);
assert_ne!(file_accessed.out.trim(), "");
let file_created = nu!(cwd: "C:\\Windows\\System32", r#"ls -l Configuration* | where name == "Configuration" | get created.0"#);
assert_ne!(file_created.out.trim(), "");
let ls_with_filter = nu!(cwd: "C:\\Windows\\System32", "ls | where size > 10mb");
assert_eq!(ls_with_filter.err, "");
}
#[test]
fn list_a_directory_not_exists() {
Playground::setup("ls_test_directory_not_exists", |dirs, _sandbox| {
let actual = nu!(cwd: dirs.test(), "ls a_directory_not_exists");
assert!(actual.err.contains("nu::shell::io::not_found"));
})
}
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
#[test]
fn list_directory_contains_invalid_utf8() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
Playground::setup(
"ls_test_directory_contains_invalid_utf8",
|dirs, _sandbox| {
let v: [u8; 4] = [7, 196, 144, 188];
let s = OsStr::from_bytes(&v);
let cwd = dirs.test();
let path = cwd.join(s);
std::fs::create_dir_all(path).expect("failed to create directory");
let actual = nu!(cwd: cwd, "ls");
assert!(actual.out.contains("warning: get non-utf8 filename"));
assert!(actual.err.contains("No matches found for"));
},
)
}
#[test]
fn list_ignores_ansi() {
Playground::setup("ls_test_ansi", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("los.txt"),
EmptyFile("tres.txt"),
EmptyFile("amigos.txt"),
EmptyFile("arepas.clu"),
]);
let actual = nu!(cwd: dirs.test(), "
ls | find .txt | each {|| ls $in.name }
");
assert!(actual.err.is_empty());
})
}
#[test]
fn list_unknown_long_flag() {
let actual = nu!("ls --full-path");
assert!(actual.err.contains("Did you mean: `--full-paths`?"));
}
#[test]
fn list_unknown_short_flag() {
let actual = nu!("ls -r");
assert!(actual.err.contains("Use `--help` to see available flags"));
}
#[test]
fn list_flag_false() {
// Check that ls flags respect explicit values
Playground::setup("ls_test_false_flag", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile(".hidden"),
EmptyFile("normal"),
EmptyFile("another_normal"),
]);
// TODO Remove this cfg value when we have an OS-agnostic way
// of creating hidden files using the playground.
#[cfg(unix)]
{
let actual = nu!(cwd: dirs.test(), "
ls --all=false | length
");
assert_eq!(actual.out, "2");
}
let actual = nu!(cwd: dirs.test(), "
ls --long=false | columns | length
");
assert_eq!(actual.out, "4");
let actual = nu!(cwd: dirs.test(), "
ls --full-paths=false | get name | any { $in =~ / }
");
assert_eq!(actual.out, "false");
})
}
#[test]
fn list_empty_string() {
Playground::setup("ls_empty_string", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("yehuda.txt")]);
let actual = nu!(cwd: dirs.test(), "ls ''");
assert!(actual.err.contains("does not exist"));
})
}
#[test]
fn list_with_tilde() {
Playground::setup("ls_tilde", |dirs, sandbox| {
sandbox
.within("~tilde")
.with_files(&[EmptyFile("f1.txt"), EmptyFile("f2.txt")]);
let actual = nu!(cwd: dirs.test(), "ls '~tilde'");
assert!(actual.out.contains("f1.txt"));
assert!(actual.out.contains("f2.txt"));
assert!(actual.out.contains("~tilde"));
let actual = nu!(cwd: dirs.test(), "ls ~tilde");
assert!(actual.err.contains("nu::shell::io::not_found"));
// pass variable
let actual = nu!(cwd: dirs.test(), "let f = '~tilde'; ls $f");
assert!(actual.out.contains("f1.txt"));
assert!(actual.out.contains("f2.txt"));
assert!(actual.out.contains("~tilde"));
})
}
#[test]
fn list_with_multiple_path() {
Playground::setup("ls_multiple_path", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("f1.txt"),
EmptyFile("f2.txt"),
EmptyFile("f3.txt"),
]);
let actual = nu!(cwd: dirs.test(), "ls f1.txt f2.txt");
assert!(actual.out.contains("f1.txt"));
assert!(actual.out.contains("f2.txt"));
assert!(!actual.out.contains("f3.txt"));
assert!(actual.status.success());
// report errors if one path not exists
let actual = nu!(cwd: dirs.test(), "ls asdf f1.txt");
assert!(actual.err.contains("nu::shell::io::not_found"));
assert!(!actual.status.success());
// ls with spreading empty list should returns nothing.
let actual = nu!(cwd: dirs.test(), "ls ...[] | length");
assert_eq!(actual.out, "0");
})
}
#[test]
fn list_inside_glob_metachars_dir() {
Playground::setup("list_files_inside_glob_metachars_dir", |dirs, sandbox| {
let sub_dir = "test[]";
sandbox
.within(sub_dir)
.with_files(&[EmptyFile("test_file.txt")]);
let actual = nu!(
cwd: dirs.test().join(sub_dir),
"ls test_file.txt | get name.0 | path basename",
);
assert!(actual.out.contains("test_file.txt"));
});
}
#[test]
fn list_inside_tilde_glob_metachars_dir() {
Playground::setup(
"list_files_inside_tilde_glob_metachars_dir",
|dirs, sandbox| {
let sub_dir = "~test[]";
sandbox
.within(sub_dir)
.with_files(&[EmptyFile("test_file.txt")]);
// need getname.0 | path basename because the output path
// might be too long to output as a single line.
let actual = nu!(
cwd: dirs.test().join(sub_dir),
"ls test_file.txt | get name.0 | path basename",
);
assert!(actual.out.contains("test_file.txt"));
let actual = nu!(
cwd: dirs.test(),
"ls '~test[]' | get name.0 | path basename"
);
assert!(actual.out.contains("test_file.txt"));
},
);
}
#[test]
fn list_symlink_with_full_path() {
Playground::setup("list_symlink_with_full_path", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("test_file.txt")]);
#[cfg(unix)]
let _ = std::os::unix::fs::symlink("test_file.txt", dirs.test().join("test_link1"));
#[cfg(windows)]
let _ = std::os::windows::fs::symlink_file("test_file.txt", dirs.test().join("test_link1"));
let actual = nu!(
cwd: dirs.test(),
"ls -l test_link1 | get target.0"
);
assert_eq!(actual.out, "test_file.txt");
let actual = nu!(
cwd: dirs.test(),
"ls -lf test_link1 | get target.0"
);
assert_eq!(
actual.out,
dirs.test().join("test_file.txt").to_string_lossy()
);
})
}
#[test]
fn consistent_list_order() {
Playground::setup("ls_test_order", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("los.txt"),
EmptyFile("tres.txt"),
EmptyFile("amigos.txt"),
EmptyFile("arepas.clu"),
]);
let no_arg = nu!(cwd: dirs.test(), "ls");
let with_arg = nu!(cwd: dirs.test(), "ls .");
assert_eq!(no_arg.out, with_arg.out);
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/select.rs | crates/nu-command/tests/commands/select.rs | use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn regular_columns() {
let actual = nu!(r#"
echo [
[first_name, last_name, rusty_at, type];
[Andrés Robalino '10/11/2013' A]
[JT Turner '10/12/2013' B]
[Yehuda Katz '10/11/2013' A]
]
| select rusty_at last_name
| get 0
| get last_name
"#);
assert_eq!(actual.out, "Robalino");
}
#[test]
fn complex_nested_columns() {
let sample = r#"{
"nu": {
"committers": [
{"name": "Andrés N. Robalino"},
{"name": "JT Turner"},
{"name": "Yehuda Katz"}
],
"releases": [
{"version": "0.2"}
{"version": "0.8"},
{"version": "0.9999999"}
],
"0xATYKARNU": [
["Th", "e", " "],
["BIG", " ", "UnO"],
["punto", "cero"]
]
}
}"#;
let actual = nu!(format!(
r#"
{sample}
| select nu."0xATYKARNU" nu.committers.name nu.releases.version
| get "nu.releases.version"
| where $it > "0.8"
| get 0
"#
));
assert_eq!(actual.out, "0.9999999");
}
#[test]
fn fails_if_given_unknown_column_name() {
let actual = nu!(r#"
[
[first_name, last_name, rusty_at, type];
[Andrés Robalino '10/11/2013' A]
[JT Turner '10/12/2013' B]
[Yehuda Katz '10/11/2013' A]
]
| select rrusty_at first_name
"#);
assert!(actual.err.contains("nu::shell::name_not_found"));
}
#[test]
fn column_names_with_spaces() {
let actual = nu!(r#"
echo [
["first name", "last name"];
[Andrés Robalino]
[Andrés Jnth]
]
| select "last name"
| get "last name"
| str join " "
"#);
assert_eq!(actual.out, "Robalino Jnth");
}
#[test]
fn ignores_duplicate_columns_selected() {
let actual = nu!(r#"
echo [
["first name", "last name"];
[Andrés Robalino]
[Andrés Jnth]
]
| select "first name" "last name" "first name"
| columns
| str join " "
"#);
assert_eq!(actual.out, "first name last name");
}
#[test]
fn selects_a_row() {
Playground::setup("select_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("notes.txt"), EmptyFile("arepas.txt")]);
let actual = nu!(cwd: dirs.test(), "
ls
| sort-by name
| select 0
| get name.0
");
assert_eq!(actual.out, "arepas.txt");
});
}
#[test]
fn selects_large_row_number() {
let actual = nu!("seq 1 5 | select 9999999999 | to nuon");
assert_eq!(actual.out, "[]");
}
#[test]
fn selects_many_rows() {
Playground::setup("select_test_2", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("notes.txt"), EmptyFile("arepas.txt")]);
let actual = nu!(cwd: dirs.test(), "
ls
| get name
| select 1 0
| length
");
assert_eq!(actual.out, "2");
});
}
#[test]
fn select_ignores_errors_successfully1() {
let actual = nu!("[{a: 1, b: 2} {a: 3, b: 5} {a: 3}] | select b? | length");
assert_eq!(actual.out, "3".to_string());
assert!(actual.err.is_empty());
}
#[test]
fn select_ignores_errors_successfully2() {
let actual = nu!("[{a: 1} {a: 2} {a: 3}] | select b? | to nuon");
assert_eq!(actual.out, "[[b]; [null], [null], [null]]".to_string());
assert!(actual.err.is_empty());
}
#[test]
fn select_ignores_errors_successfully3() {
let actual = nu!("{foo: bar} | select invalid_key? | to nuon");
assert_eq!(actual.out, "{invalid_key: null}".to_string());
assert!(actual.err.is_empty());
}
#[test]
fn select_ignores_errors_successfully4() {
let actual = nu!(
r#""key val\na 1\nb 2\n" | lines | split column --collapse-empty " " | select foo? | to nuon"#
);
assert_eq!(actual.out, r#"[[foo]; [null], [null], [null]]"#.to_string());
assert!(actual.err.is_empty());
}
#[test]
fn select_failed1() {
let actual = nu!("[{a: 1, b: 2} {a: 3, b: 5} {a: 3}] | select b ");
assert!(actual.out.is_empty());
assert!(actual.err.contains("cannot find column"));
}
#[test]
fn select_failed2() {
let actual = nu!("[{a: 1} {a: 2} {a: 3}] | select b");
assert!(actual.out.is_empty());
assert!(actual.err.contains("cannot find column"));
}
#[test]
fn select_failed3() {
let actual =
nu!(r#""key val\na 1\nb 2\n" | lines | split column --collapse-empty " " | select "100""#);
assert!(actual.out.is_empty());
assert!(actual.err.contains("cannot find column"));
}
#[test]
fn select_repeated_rows() {
let actual = nu!("[[a b c]; [1 2 3] [4 5 6] [7 8 9]] | select 0 0 | to nuon");
assert_eq!(actual.out, "[[a, b, c]; [1, 2, 3]]");
}
#[test]
fn select_repeated_column() {
let actual = nu!("[[a b c]; [1 2 3] [4 5 6] [7 8 9]] | select a a | to nuon");
assert_eq!(actual.out, "[[a]; [1], [4], [7]]");
}
#[test]
fn ignore_errors_works() {
let actual = nu!(r#"
let path = "foo";
[{}] | select -o $path | to nuon
"#);
assert_eq!(actual.out, "[[foo]; [null]]");
}
#[test]
fn select_on_empty_list_returns_empty_list() {
// once with a List
let actual = nu!("[] | select foo | to nuon");
assert_eq!(actual.out, "[]");
// and again with a ListStream
let actual = nu!("[] | each {|i| $i} | select foo | to nuon");
assert_eq!(actual.out, "[]");
}
#[test]
fn select_columns_with_list_spread() {
let actual = nu!(r#"
let columns = [a c];
echo [[a b c]; [1 2 3]] | select ...$columns | to nuon
"#);
assert_eq!(actual.out, "[[a, c]; [1, 3]]");
}
#[test]
fn select_rows_with_list_spread() {
let actual = nu!(r#"
let rows = [0 2];
echo [[a b c]; [1 2 3] [4 5 6] [7 8 9]] | select ...$rows | to nuon
"#);
assert_eq!(actual.out, "[[a, b, c]; [1, 2, 3], [7, 8, 9]]");
}
#[test]
fn select_single_row_with_variable() {
let actual = nu!("let idx = 2; [{a: 1, b: 2} {a: 3, b: 5} {a: 3}] | select $idx | to nuon");
assert_eq!(actual.out, "[[a]; [3]]".to_string());
assert!(actual.err.is_empty());
}
#[test]
fn select_with_negative_number_errors_out() {
let actual = nu!("[1 2 3] | select (-2)");
assert!(actual.err.contains("negative number"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/upsert.rs | crates/nu-command/tests/commands/upsert.rs | use nu_test_support::nu;
#[test]
fn sets_the_column() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml
| upsert dev-dependencies.pretty_assertions "0.7.0"
| get dev-dependencies.pretty_assertions
"#);
assert_eq!(actual.out, "0.7.0");
}
#[test]
fn doesnt_convert_record_to_table() {
let actual = nu!("{a:1} | upsert a 2 | to nuon");
assert_eq!(actual.out, "{a: 2}");
}
#[test]
fn sets_the_column_from_a_block_full_stream_output() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
{content: null}
| upsert content {|| open --raw cargo_sample.toml | lines | first 5 }
| get content.1
| str contains "nu"
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn sets_the_column_from_a_subexpression() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
{content: null}
| upsert content (open --raw cargo_sample.toml | lines | first 5)
| get content.1
| str contains "nu"
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn upsert_uses_enumerate_index_inserting() {
let actual = nu!(
"[[a]; [7] [6]] | enumerate | upsert b {|el| $el.index + 1 + $el.item.a } | flatten | to nuon"
);
assert_eq!(actual.out, "[[index, a, b]; [0, 7, 8], [1, 6, 8]]");
}
#[test]
fn upsert_uses_enumerate_index_updating() {
let actual = nu!(
"[[a]; [7] [6]] | enumerate | upsert a {|el| $el.index + 1 + $el.item.a } | flatten | to nuon"
);
assert_eq!(actual.out, "[[index, a]; [0, 8], [1, 8]]");
}
#[test]
fn upsert_into_list() {
let actual = nu!("[1, 2, 3] | upsert 1 abc | to json -r");
assert_eq!(actual.out, r#"[1,"abc",3]"#);
}
#[test]
fn upsert_at_end_of_list() {
let actual = nu!("[1, 2, 3] | upsert 3 abc | to json -r");
assert_eq!(actual.out, r#"[1,2,3,"abc"]"#);
}
#[test]
fn upsert_past_end_of_list() {
let actual = nu!("[1, 2, 3] | upsert 5 abc");
assert!(
actual
.err
.contains("can't insert at index (the next available index is 3)")
);
}
#[test]
fn upsert_into_list_stream() {
let actual = nu!("[1, 2, 3] | every 1 | upsert 1 abc | to json -r");
assert_eq!(actual.out, r#"[1,"abc",3]"#);
}
#[test]
fn upsert_at_end_of_list_stream() {
let actual = nu!("[1, 2, 3] | every 1 | upsert 3 abc | to json -r");
assert_eq!(actual.out, r#"[1,2,3,"abc"]"#);
}
#[test]
fn upsert_past_end_of_list_stream() {
let actual = nu!("[1, 2, 3] | every 1 | upsert 5 abc");
assert!(
actual
.err
.contains("can't insert at index (the next available index is 3)")
);
}
#[test]
fn deep_cell_path_creates_all_nested_records() {
let actual = nu!("{a: {}} | upsert a.b.c 0 | get a.b.c");
assert_eq!(actual.out, "0");
}
#[test]
fn upserts_all_rows_in_table_in_record() {
let actual = nu!(
"{table: [[col]; [{a: 1}], [{a: 1}]]} | upsert table.col.b 2 | get table.col.b | to nuon"
);
assert_eq!(actual.out, "[2, 2]");
}
#[test]
fn list_replacement_closure() {
let actual = nu!("[1, 2] | upsert 1 {|i| $i + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3]");
let actual = nu!("[1, 2] | upsert 1 { $in + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3]");
let actual = nu!("[1, 2] | upsert 2 {|i| if $i == null { 0 } else { $in + 1 } } | to nuon");
assert_eq!(actual.out, "[1, 2, 0]");
let actual = nu!("[1, 2] | upsert 2 { if $in == null { 0 } else { $in + 1 } } | to nuon");
assert_eq!(actual.out, "[1, 2, 0]");
}
#[test]
fn record_replacement_closure() {
let actual = nu!("{ a: text } | upsert a {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "{a: TEXT}");
let actual = nu!("{ a: text } | upsert a { str upcase } | to nuon");
assert_eq!(actual.out, "{a: TEXT}");
let actual = nu!("{ a: text } | upsert b {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "{a: text, b: TEXT}");
let actual = nu!("{ a: text } | upsert b { default TEXT } | to nuon");
assert_eq!(actual.out, "{a: text, b: TEXT}");
let actual = nu!("{ a: { b: 1 } } | upsert a.c {|r| $r.a.b } | to nuon");
assert_eq!(actual.out, "{a: {b: 1, c: 1}}");
let actual = nu!("{ a: { b: 1 } } | upsert a.c { default 0 } | to nuon");
assert_eq!(actual.out, "{a: {b: 1, c: 0}}");
}
#[test]
fn table_replacement_closure() {
let actual = nu!("[[a]; [text]] | upsert a {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "[[a]; [TEXT]]");
let actual = nu!("[[a]; [text]] | upsert a { str upcase } | to nuon");
assert_eq!(actual.out, "[[a]; [TEXT]]");
let actual = nu!("[[a]; [text]] | upsert b {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "[[a, b]; [text, TEXT]]");
let actual = nu!("[[a]; [text]] | upsert b { default TEXT } | to nuon");
assert_eq!(actual.out, "[[a, b]; [text, TEXT]]");
let actual = nu!("[[b]; [1]] | wrap a | upsert a.c {|r| $r.a.b } | to nuon");
assert_eq!(actual.out, "[[a]; [{b: 1, c: 1}]]");
let actual = nu!("[[b]; [1]] | wrap a | upsert a.c { default 0 } | to nuon");
assert_eq!(actual.out, "[[a]; [{b: 1, c: 0}]]");
}
#[test]
fn list_stream_replacement_closure() {
let actual = nu!("[1, 2] | every 1 | upsert 1 {|i| $i + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3]");
let actual = nu!("[1, 2] | every 1 | upsert 1 { $in + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3]");
let actual =
nu!("[1, 2] | every 1 | upsert 2 {|i| if $i == null { 0 } else { $in + 1 } } | to nuon");
assert_eq!(actual.out, "[1, 2, 0]");
let actual =
nu!("[1, 2] | every 1 | upsert 2 { if $in == null { 0 } else { $in + 1 } } | to nuon");
assert_eq!(actual.out, "[1, 2, 0]");
let actual = nu!("[[a]; [text]] | every 1 | upsert a {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "[[a]; [TEXT]]");
let actual = nu!("[[a]; [text]] | every 1 | upsert a { str upcase } | to nuon");
assert_eq!(actual.out, "[[a]; [TEXT]]");
let actual = nu!("[[a]; [text]] | every 1 | upsert b {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "[[a, b]; [text, TEXT]]");
let actual = nu!("[[a]; [text]] | every 1 | upsert b { default TEXT } | to nuon");
assert_eq!(actual.out, "[[a, b]; [text, TEXT]]");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/run_external.rs | crates/nu-command/tests/commands/run_external.rs | use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use rstest::{fixture, rstest};
use rstest_reuse::*;
#[fixture]
#[once]
fn nu_bin() -> String {
nu_test_support::fs::executable_path()
.to_string_lossy()
.to_string()
}
// Template for run-external test to ensure tests work when calling
// the binary directly, using the caret operator, and when using
// the run-external command
#[template]
#[rstest]
#[case("")]
#[case("^")]
#[case("run-external ")]
fn run_external_prefixes(nu_bin: &str, #[case] prefix: &str) {}
#[apply(run_external_prefixes)]
fn better_empty_redirection(nu_bin: &str, prefix: &str) {
let actual = nu!(
cwd: "tests/fixtures/formats",
format!("ls | each {{ |it| {prefix}{nu_bin} `--testbin` cococo $it.name }} | ignore")
);
eprintln!("out: {}", actual.out);
assert!(!actual.out.contains('2'));
}
#[apply(run_external_prefixes)]
fn explicit_glob(nu_bin: &str, prefix: &str) {
Playground::setup("external with explicit glob", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("D&D_volume_1.txt"),
EmptyFile("D&D_volume_2.txt"),
EmptyFile("foo.sh"),
]);
let actual = nu!(
cwd: dirs.test(),
format!(r#"{prefix}{nu_bin} `--testbin` cococo ('*.txt' | into glob)"#)
);
assert!(actual.out.contains("D&D_volume_1.txt"));
assert!(actual.out.contains("D&D_volume_2.txt"));
})
}
#[apply(run_external_prefixes)]
fn bare_word_expand_path_glob(nu_bin: &str, prefix: &str) {
Playground::setup("bare word should do the expansion", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("D&D_volume_1.txt"),
EmptyFile("D&D_volume_2.txt"),
EmptyFile("foo.sh"),
]);
let actual = nu!(
cwd: dirs.test(),
format!("{prefix}{nu_bin} `--testbin` cococo *.txt")
);
assert!(actual.out.contains("D&D_volume_1.txt"));
assert!(actual.out.contains("D&D_volume_2.txt"));
})
}
#[apply(run_external_prefixes)]
fn backtick_expand_path_glob(nu_bin: &str, prefix: &str) {
Playground::setup("backtick should do the expansion", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("D&D_volume_1.txt"),
EmptyFile("D&D_volume_2.txt"),
EmptyFile("foo.sh"),
]);
let actual = nu!(
cwd: dirs.test(),
format!(r#"{prefix}{nu_bin} `--testbin` cococo `*.txt`"#)
);
assert!(actual.out.contains("D&D_volume_1.txt"));
assert!(actual.out.contains("D&D_volume_2.txt"));
})
}
#[apply(run_external_prefixes)]
fn single_quote_does_not_expand_path_glob(nu_bin: &str, prefix: &str) {
Playground::setup("single quote do not run the expansion", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("D&D_volume_1.txt"),
EmptyFile("D&D_volume_2.txt"),
EmptyFile("foo.sh"),
]);
let actual = nu!(
cwd: dirs.test(),
format!(r#"{prefix}{nu_bin} `--testbin` cococo '*.txt'"#)
);
assert_eq!(actual.out, "*.txt");
})
}
#[apply(run_external_prefixes)]
fn double_quote_does_not_expand_path_glob(nu_bin: &str, prefix: &str) {
Playground::setup("double quote do not run the expansion", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("D&D_volume_1.txt"),
EmptyFile("D&D_volume_2.txt"),
EmptyFile("foo.sh"),
]);
let actual = nu!(
cwd: dirs.test(),
format!(r#"{prefix}{nu_bin} `--testbin` cococo "*.txt""#)
);
assert_eq!(actual.out, "*.txt");
})
}
#[apply(run_external_prefixes)]
fn failed_command_with_semicolon_will_not_execute_following_cmds(nu_bin: &str, prefix: &str) {
Playground::setup("external failed command with semicolon", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("{prefix}{nu_bin} `--testbin` fail; echo done")
);
assert!(!actual.out.contains("done"));
})
}
#[apply(run_external_prefixes)]
fn external_args_with_quoted(nu_bin: &str, prefix: &str) {
Playground::setup("external failed command with semicolon", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!(r#"{prefix}{nu_bin} `--testbin` cococo "foo=bar 'hi'""#)
);
assert_eq!(actual.out, "foo=bar 'hi'");
})
}
// don't use template for this once since echo with no prefix is an internal command
// and arguments flags are treated as arguments to run-external
// (but wrapping them in quotes defeats the point of test)
#[cfg(not(windows))]
#[test]
fn external_arg_with_option_like_embedded_quotes() {
// TODO: would be nice to make this work with cococo, but arg parsing interferes
Playground::setup(
"external arg with option like embedded quotes",
|dirs, _| {
let actual = nu!(
cwd: dirs.test(),
r#"^echo --foo='bar' -foo='bar'"#,
);
assert_eq!(actual.out, "--foo=bar -foo=bar");
},
)
}
// FIXME: parser complains about invalid characters after single quote
#[rstest]
#[case("")]
#[case("^")]
fn external_arg_with_non_option_like_embedded_quotes(nu_bin: &str, #[case] prefix: &str) {
Playground::setup(
"external arg with non option like embedded quotes",
|dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!(r#"{prefix}{nu_bin} `--testbin` cococo foo='bar' 'foo'=bar"#),
);
assert_eq!(actual.out, "foo=bar foo=bar");
},
)
}
// FIXME: parser bug prevents expressions from appearing within GlobPattern substrings
#[rstest]
#[case("")]
#[case("^")]
fn external_arg_with_string_interpolation(nu_bin: &str, #[case] prefix: &str) {
Playground::setup("external arg with string interpolation", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!(r#"{prefix}{nu_bin} `--testbin` cococo foo=(2 + 2) $"foo=(2 + 2)" foo=$"(2 + 2)""#)
);
assert_eq!(actual.out, "foo=4 foo=4 foo=4");
})
}
#[apply(run_external_prefixes)]
fn external_arg_with_variable_name(nu_bin: &str, prefix: &str) {
Playground::setup("external failed command with semicolon", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!(r#"
let dump_command = "PGPASSWORD='db_secret' pg_dump -Fc -h 'db.host' -p '$db.port' -U postgres -d 'db_name' > '/tmp/dump_name'";
{prefix}{nu_bin} `--testbin` nonu $dump_command
"#)
);
assert_eq!(
actual.out,
r#"PGPASSWORD='db_secret' pg_dump -Fc -h 'db.host' -p '$db.port' -U postgres -d 'db_name' > '/tmp/dump_name'"#
);
})
}
#[apply(run_external_prefixes)]
fn external_command_escape_args(nu_bin: &str, prefix: &str) {
Playground::setup("external failed command with semicolon", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!(r#"{prefix}{nu_bin} `--testbin` cococo "\"abcd""#)
);
assert_eq!(actual.out, r#""abcd"#);
})
}
#[apply(run_external_prefixes)]
fn external_command_ndots_args(nu_bin: &str, prefix: &str) {
let actual = nu!(format!(
r#"{prefix}{nu_bin} `--testbin` cococo foo/. foo/.. foo/... foo/./bar foo/../bar foo/.../bar ./bar ../bar .../bar"#
));
assert_eq!(
actual.out,
if cfg!(windows) {
// Windows is a bit weird right now, where if ndots has to fix something it's going to
// change everything to backslashes too. Would be good to fix that
r"foo/. foo/.. foo\..\.. foo/./bar foo/../bar foo\..\..\bar ./bar ../bar ..\..\bar"
} else {
r"foo/. foo/.. foo/../.. foo/./bar foo/../bar foo/../../bar ./bar ../bar ../../bar"
}
);
}
#[apply(run_external_prefixes)]
fn external_command_ndots_leading_dot_slash(nu_bin: &str, prefix: &str) {
// Don't expand ndots with a leading `./`
let actual = nu!(format!(
r#"{prefix}{nu_bin} `--testbin` cococo ./... ./...."#
));
assert_eq!(actual.out, "./... ./....");
}
#[apply(run_external_prefixes)]
fn external_command_url_args(nu_bin: &str, prefix: &str) {
// If ndots is not handled correctly, we can lose the double forward slashes that are needed
// here
let actual = nu!(format!(
r#"{prefix}{nu_bin} `--testbin` cococo http://example.com http://example.com/.../foo //foo"#
));
assert_eq!(
actual.out,
"http://example.com http://example.com/.../foo //foo"
);
}
#[apply(run_external_prefixes)]
#[cfg_attr(
not(target_os = "linux"),
ignore = "only runs on Linux, where controlling the HOME var is reliable"
)]
fn external_command_expand_tilde(nu_bin: &str, prefix: &str) {
let _ = nu_bin;
Playground::setup("external command expand tilde", |dirs, _| {
// Make a copy of the nu executable that we can use
let mut src = std::fs::File::open(nu_test_support::fs::binaries().join("nu"))
.expect("failed to open nu");
let mut dst = std::fs::File::create_new(dirs.test().join("test_nu"))
.expect("failed to create test_nu file");
std::io::copy(&mut src, &mut dst).expect("failed to copy data for nu binary");
// Make test_nu have the same permissions so that it's executable
dst.set_permissions(
src.metadata()
.expect("failed to get nu metadata")
.permissions(),
)
.expect("failed to set permissions on test_nu");
// Close the files
drop(dst);
drop(src);
let actual = nu!(
envs: vec![
("HOME".to_string(), dirs.test().to_string_lossy().into_owned()),
],
format!(r#"{prefix}~/test_nu `--testbin` cococo hello"#)
);
assert_eq!(actual.out, "hello");
})
}
// FIXME: parser bug prevents expressions from appearing within GlobPattern substrings
#[rstest]
#[case("")]
#[case("^")]
fn external_arg_expand_tilde(nu_bin: &str, #[case] prefix: &str) {
Playground::setup("external arg expand tilde", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!(r#"{prefix}{nu_bin} `--testbin` cococo ~/foo ~/(2 + 2)"#)
);
let home = dirs::home_dir().expect("failed to find home dir");
assert_eq!(
actual.out,
format!(
"{} {}",
home.join("foo").display(),
home.join("4").display()
)
);
})
}
#[apply(run_external_prefixes)]
fn external_command_not_expand_tilde_with_quotes(nu_bin: &str, prefix: &str) {
Playground::setup(
"external command not expand tilde with quotes",
|dirs, _| {
let actual = nu!(cwd: dirs.test(), format!(r#"{prefix}{nu_bin} `--testbin` nonu "~""#));
assert_eq!(actual.out, r#"~"#);
},
)
}
#[apply(run_external_prefixes)]
fn external_command_expand_tilde_with_back_quotes(nu_bin: &str, prefix: &str) {
Playground::setup(
"external command not expand tilde with quotes",
|dirs, _| {
let actual = nu!(cwd: dirs.test(), format!(r#"{prefix}{nu_bin} `--testbin` nonu `~`"#));
assert!(!actual.out.contains('~'));
},
)
}
#[apply(run_external_prefixes)]
fn external_command_receives_raw_binary_data(nu_bin: &str, prefix: &str) {
Playground::setup("external command receives raw binary data", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("0x[deadbeef] | {prefix}{nu_bin} `--testbin` input_bytes_length")
);
assert_eq!(actual.out, r#"4"#);
})
}
#[cfg(windows)]
#[apply(run_external_prefixes)]
fn can_run_cmd_files(nu_bin: &str, prefix: &str) {
let _ = nu_bin;
use nu_test_support::fs::Stub::FileWithContent;
Playground::setup("run a Windows cmd file", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"foo.cmd",
r#"
@echo off
echo Hello World
"#,
)]);
let actual = nu!(cwd: dirs.test(), format!("{prefix}foo.cmd"));
assert!(actual.out.contains("Hello World"));
});
}
#[cfg(windows)]
#[apply(run_external_prefixes)]
fn can_run_batch_files(nu_bin: &str, prefix: &str) {
let _ = nu_bin;
use nu_test_support::fs::Stub::FileWithContent;
Playground::setup("run a Windows batch file", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"foo.bat",
r#"
@echo off
echo Hello World
"#,
)]);
let actual = nu!(cwd: dirs.test(), format!("{prefix}foo.bat"));
assert!(actual.out.contains("Hello World"));
});
}
#[cfg(windows)]
#[apply(run_external_prefixes)]
fn can_run_batch_files_without_cmd_extension(nu_bin: &str, prefix: &str) {
let _ = nu_bin;
use nu_test_support::fs::Stub::FileWithContent;
Playground::setup(
"run a Windows cmd file without specifying the extension",
|dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"foo.cmd",
r#"
@echo off
echo Hello World
"#,
)]);
let actual = nu!(cwd: dirs.test(), format!("{prefix}foo"));
assert!(actual.out.contains("Hello World"));
},
);
}
#[cfg(windows)]
#[apply(run_external_prefixes)]
fn can_run_batch_files_without_bat_extension(nu_bin: &str, prefix: &str) {
let _ = nu_bin;
use nu_test_support::fs::Stub::FileWithContent;
Playground::setup(
"run a Windows batch file without specifying the extension",
|dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"foo.bat",
r#"
@echo off
echo Hello World
"#,
)]);
let actual = nu!(cwd: dirs.test(), format!("{prefix}foo"));
assert!(actual.out.contains("Hello World"));
},
);
}
#[apply(run_external_prefixes)]
fn quotes_trimmed_when_shelling_out(nu_bin: &str, prefix: &str) {
// regression test for a bug where we weren't trimming quotes around string args before shelling out to cmd.exe
let actual = nu!(format!(r#"{prefix}{nu_bin} `--testbin` cococo "foo""#));
assert_eq!(actual.out, "foo");
}
#[cfg(not(windows))]
#[apply(run_external_prefixes)]
fn redirect_combine(nu_bin: &str, prefix: &str) {
let _ = nu_bin;
Playground::setup("redirect_combine", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!(r#"{prefix}sh ...[-c 'echo Foo; echo >&2 Bar'] o+e>| print"#)
);
// Lines are collapsed in the nu! macro
assert_eq!(actual.out, "FooBar");
});
}
#[cfg(windows)]
#[apply(run_external_prefixes)]
fn can_run_ps1_files(nu_bin: &str, prefix: &str) {
let _ = nu_bin;
use nu_test_support::fs::Stub::FileWithContent;
Playground::setup("run_a_windows_ps_file", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"foo.ps1",
r#"
Write-Host Hello World
"#,
)]);
let actual = nu!(cwd: dirs.test(), format!("{prefix}foo.ps1"));
assert!(actual.out.contains("Hello World"));
});
}
#[cfg(windows)]
#[apply(run_external_prefixes)]
fn can_run_ps1_files_with_space_in_path(nu_bin: &str, prefix: &str) {
let _ = nu_bin;
use nu_test_support::fs::Stub::FileWithContent;
Playground::setup("run_a_windows_ps_file", |dirs, sandbox| {
sandbox
.within("path with space")
.with_files(&[FileWithContent(
"foo.ps1",
r#"
Write-Host Hello World
"#,
)]);
let actual = nu!(cwd: dirs.test().join("path with space"), format!("{prefix}foo.ps1"));
assert!(actual.out.contains("Hello World"));
});
}
#[rstest]
#[case("^")]
#[case("run-external ")]
fn can_run_external_without_path_env(nu_bin: &str, #[case] prefix: &str) {
Playground::setup("can run external without path env", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!(r#"
hide-env -i PATH
hide-env -i Path
{prefix}{nu_bin} `--testbin` cococo
"#)
);
assert_eq!(actual.out, "cococo");
})
}
#[rstest]
#[case("^")]
#[case("run-external ")]
fn expand_command_if_list(nu_bin: &str, #[case] prefix: &str) {
use nu_test_support::fs::Stub::FileWithContent;
Playground::setup("expand command if list", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent("foo.txt", "Hello World")]);
let actual = nu!(
cwd: dirs.test(),
format!(r#"let cmd = ['{nu_bin}' `--testbin`]; {prefix}$cmd meow foo.txt"#),
);
assert!(actual.out.contains("Hello World"));
})
}
#[rstest]
#[case("^")]
#[case("run-external ")]
fn error_when_command_list_empty(#[case] prefix: &str) {
Playground::setup("error when command is list with no items", |dirs, _| {
let actual = nu!(cwd: dirs.test(), format!("let cmd = []; {prefix}$cmd"));
assert!(actual.err.contains("missing parameter"));
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/merge_deep.rs | crates/nu-command/tests/commands/merge_deep.rs | use std::fmt::Display;
use nu_test_support::nu;
use rstest::rstest;
struct Strategy<'a>(Option<&'a str>);
impl<'a> Display for Strategy<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0
.map(|s| write!(f, "--strategy={s}"))
.unwrap_or(Ok(()))
}
}
const TABLE_LEFT: &str = "{inner: [{a: 1}, {b: 2}]}";
const TABLE_RIGHT: &str = "{inner: [{c: 3}]}";
const LIST_LEFT: &str = "{a: [1, 2, 3]}";
const LIST_RIGHT: &str = "{a: [4, 5, 6]}";
#[rstest]
#[case::s_table_table(None, TABLE_LEFT, TABLE_RIGHT, "{inner: [{a: 1, c: 3}, {b: 2}]}")]
#[case::s_table_list(None, LIST_LEFT, LIST_RIGHT, "{a: [4, 5, 6]}")]
#[case::s_overwrite_table("overwrite", TABLE_LEFT, TABLE_RIGHT, "{inner: [[c]; [3]]}")]
#[case::s_overwrite_list("overwrite", LIST_LEFT, LIST_RIGHT, "{a: [4, 5, 6]}")]
#[case::s_append_table("append", TABLE_LEFT, TABLE_RIGHT, "{inner: [{a: 1}, {b: 2}, {c: 3}]}")]
#[case::s_append_list("append", LIST_LEFT, LIST_RIGHT, "{a: [1, 2, 3, 4, 5, 6]}")]
#[case::s_prepend_table(
"prepend",
TABLE_LEFT,
TABLE_RIGHT,
"{inner: [{c: 3}, {a: 1}, {b: 2}]}"
)]
#[case::s_prepend_list("prepend", LIST_LEFT, LIST_RIGHT, "{a: [4, 5, 6, 1, 2, 3]}")]
#[case::record_nested_with_overwrite(
None,
"{a: {b: {c: {d: 123, e: 456}}}}",
"{a: {b: {c: {e: 654, f: 789}}}}",
"{a: {b: {c: {d: 123, e: 654, f: 789}}}}"
)]
#[case::single_row_table(
None,
"[[a]; [{foo: [1, 2, 3]}]]",
"[[a]; [{bar: [4, 5, 6]}]]",
"[[a]; [{foo: [1, 2, 3], bar: [4, 5, 6]}]]"
)]
#[case::multi_row_table(
None,
"[[a b]; [{inner: {foo: abc}} {inner: {baz: ghi}}]]",
"[[a b]; [{inner: {bar: def}} {inner: {qux: jkl}}]]",
"[[a, b]; [{inner: {foo: abc, bar: def}}, {inner: {baz: ghi, qux: jkl}}]]"
)]
fn merge_deep_tests<'a>(
#[case] strategy: impl Into<Option<&'a str>>,
#[case] left: &str,
#[case] right: &str,
#[case] expected: &str,
) {
let strategy = Strategy(strategy.into());
let actual = nu!(format!("{left} | merge deep {strategy} {right} | to nuon"));
assert_eq!(actual.out, expected)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/return_.rs | crates/nu-command/tests/commands/return_.rs | use nu_test_support::nu;
#[test]
fn early_return_if_true() {
let actual = nu!("def foo [x] { if true { return 2 }; $x }; foo 100");
assert_eq!(actual.out, r#"2"#);
}
#[test]
fn early_return_if_false() {
let actual = nu!("def foo [x] { if false { return 2 }; $x }; foo 100");
assert_eq!(actual.out, r#"100"#);
}
#[test]
fn return_works_in_script_without_def_main() {
let actual = nu!(cwd: "tests/fixtures/formats", "nu -n early_return.nu");
assert!(actual.err.is_empty());
}
#[test]
fn return_works_in_script_with_def_main() {
let actual = nu!(cwd: "tests/fixtures/formats", "nu -n early_return_outside_main.nu");
assert!(actual.err.is_empty());
}
#[test]
fn return_does_not_set_last_exit_code() {
let actual = nu!("hide-env LAST_EXIT_CODE; do --env { return 42 }; $env.LAST_EXIT_CODE?");
assert!(matches!(actual.out.as_str(), ""));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/utouch.rs | crates/nu-command/tests/commands/utouch.rs | use chrono::{DateTime, Days, Local, TimeDelta, Utc};
use filetime::FileTime;
use nu_test_support::fs::{Stub, files_exist_at};
use nu_test_support::nu;
use nu_test_support::playground::{Dirs, Playground};
use std::path::Path;
// Use 1 instead of 0 because 0 has a special meaning in Windows
const TIME_ONE: FileTime = FileTime::from_unix_time(1, 0);
fn file_times(file: impl AsRef<Path>) -> (FileTime, FileTime) {
(
file.as_ref().metadata().unwrap().accessed().unwrap().into(),
file.as_ref().metadata().unwrap().modified().unwrap().into(),
)
}
fn symlink_times(path: &nu_path::AbsolutePath) -> (filetime::FileTime, filetime::FileTime) {
let metadata = path.symlink_metadata().unwrap();
(
filetime::FileTime::from_system_time(metadata.accessed().unwrap()),
filetime::FileTime::from_system_time(metadata.modified().unwrap()),
)
}
// From https://github.com/nushell/nushell/pull/14214
fn setup_symlink_fs(dirs: &Dirs, sandbox: &mut Playground<'_>) {
sandbox.mkdir("d");
sandbox.with_files(&[Stub::EmptyFile("f"), Stub::EmptyFile("d/f")]);
sandbox.symlink("f", "fs");
sandbox.symlink("d", "ds");
sandbox.symlink("d/f", "fds");
// sandbox.symlink does not handle symlinks to missing files well. It panics
// But they are useful, and they should be tested.
#[cfg(unix)]
{
std::os::unix::fs::symlink(dirs.test().join("m"), dirs.test().join("fms")).unwrap();
}
#[cfg(windows)]
{
std::os::windows::fs::symlink_file(dirs.test().join("m"), dirs.test().join("fms")).unwrap();
}
// Change the file times to a known "old" value for comparison
filetime::set_symlink_file_times(dirs.test().join("f"), TIME_ONE, TIME_ONE).unwrap();
filetime::set_symlink_file_times(dirs.test().join("d"), TIME_ONE, TIME_ONE).unwrap();
filetime::set_symlink_file_times(dirs.test().join("d/f"), TIME_ONE, TIME_ONE).unwrap();
filetime::set_symlink_file_times(dirs.test().join("ds"), TIME_ONE, TIME_ONE).unwrap();
filetime::set_symlink_file_times(dirs.test().join("fs"), TIME_ONE, TIME_ONE).unwrap();
filetime::set_symlink_file_times(dirs.test().join("fds"), TIME_ONE, TIME_ONE).unwrap();
filetime::set_symlink_file_times(dirs.test().join("fms"), TIME_ONE, TIME_ONE).unwrap();
}
#[test]
fn creates_a_file_when_it_doesnt_exist() {
Playground::setup("create_test_1", |dirs, _sandbox| {
nu!(
cwd: dirs.test(),
"touch i_will_be_created.txt"
);
let path = dirs.test().join("i_will_be_created.txt");
assert!(path.exists());
})
}
#[test]
fn creates_two_files() {
Playground::setup("create_test_2", |dirs, _sandbox| {
nu!(
cwd: dirs.test(),
"touch a b"
);
let path = dirs.test().join("a");
assert!(path.exists());
let path2 = dirs.test().join("b");
assert!(path2.exists());
})
}
// Windows forbids file names with reserved characters
// https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
#[test]
#[cfg(not(windows))]
fn creates_a_file_when_glob_is_quoted() {
Playground::setup("create_test_glob", |dirs, _sandbox| {
nu!(
cwd: dirs.test(),
"touch '*.txt'"
);
let path = dirs.test().join("*.txt");
assert!(path.exists());
})
}
#[test]
fn fails_when_glob_has_no_matches() {
Playground::setup("create_test_glob_no_matches", |dirs, _sandbox| {
let actual = nu!(
cwd: dirs.test(),
"touch *.txt"
);
assert!(actual.err.contains("No matches found for glob *.txt"));
})
}
#[test]
fn change_modified_time_of_file_to_today() {
Playground::setup("change_time_test_9", |dirs, sandbox| {
sandbox.with_files(&[Stub::EmptyFile("file.txt")]);
let path = dirs.test().join("file.txt");
// Set file.txt's times to the past before the test to make sure `touch` actually changes the mtime to today
filetime::set_file_times(&path, TIME_ONE, TIME_ONE).unwrap();
nu!(
cwd: dirs.test(),
"touch -m file.txt"
);
let metadata = path.metadata().unwrap();
// Check only the date since the time may not match exactly
let today = Local::now().date_naive();
let mtime_day = DateTime::<Local>::from(metadata.modified().unwrap()).date_naive();
assert_eq!(today, mtime_day);
// Check that atime remains unchanged
assert_eq!(
TIME_ONE,
FileTime::from_system_time(metadata.accessed().unwrap())
);
})
}
#[test]
fn change_access_time_of_file_to_today() {
Playground::setup("change_time_test_18", |dirs, sandbox| {
sandbox.with_files(&[Stub::EmptyFile("file.txt")]);
let path = dirs.test().join("file.txt");
// Set file.txt's times to the past before the test to make sure `touch` actually changes the atime to today
filetime::set_file_times(&path, TIME_ONE, TIME_ONE).unwrap();
nu!(
cwd: dirs.test(),
"touch -a file.txt"
);
let metadata = path.metadata().unwrap();
// Check only the date since the time may not match exactly
let today = Local::now().date_naive();
let atime_day = DateTime::<Local>::from(metadata.accessed().unwrap()).date_naive();
assert_eq!(today, atime_day);
// Check that mtime remains unchanged
assert_eq!(
TIME_ONE,
FileTime::from_system_time(metadata.modified().unwrap())
);
})
}
#[test]
fn change_modified_and_access_time_of_file_to_today() {
Playground::setup("change_time_test_27", |dirs, sandbox| {
sandbox.with_files(&[Stub::EmptyFile("file.txt")]);
let path = dirs.test().join("file.txt");
filetime::set_file_times(&path, TIME_ONE, TIME_ONE).unwrap();
nu!(
cwd: dirs.test(),
"touch -a -m file.txt"
);
let metadata = path.metadata().unwrap();
// Check only the date since the time may not match exactly
let today = Local::now().date_naive();
let mtime_day = DateTime::<Local>::from(metadata.modified().unwrap()).date_naive();
let atime_day = DateTime::<Local>::from(metadata.accessed().unwrap()).date_naive();
assert_eq!(today, mtime_day);
assert_eq!(today, atime_day);
})
}
#[test]
fn change_modified_and_access_time_of_files_matching_glob_to_today() {
Playground::setup("change_mtime_atime_test_glob", |dirs, sandbox| {
sandbox.with_files(&[Stub::EmptyFile("file.txt")]);
let path = dirs.test().join("file.txt");
filetime::set_file_times(&path, TIME_ONE, TIME_ONE).unwrap();
nu!(
cwd: dirs.test(),
"touch *.txt"
);
let metadata = path.metadata().unwrap();
// Check only the date since the time may not match exactly
let today = Local::now().date_naive();
let mtime_day = DateTime::<Local>::from(metadata.modified().unwrap()).date_naive();
let atime_day = DateTime::<Local>::from(metadata.accessed().unwrap()).date_naive();
assert_eq!(today, mtime_day);
assert_eq!(today, atime_day);
})
}
#[test]
fn not_create_file_if_it_not_exists() {
Playground::setup("change_time_test_28", |dirs, _sandbox| {
let outcome = nu!(
cwd: dirs.test(),
"touch -c file.txt"
);
let path = dirs.test().join("file.txt");
assert!(!path.exists());
// If --no-create is improperly handled `touch` may error when trying to change the times of a nonexistent file
assert!(outcome.status.success())
})
}
#[test]
fn change_file_times_if_exists_with_no_create() {
Playground::setup(
"change_file_times_if_exists_with_no_create",
|dirs, sandbox| {
sandbox.with_files(&[Stub::EmptyFile("file.txt")]);
let path = dirs.test().join("file.txt");
filetime::set_file_times(&path, TIME_ONE, TIME_ONE).unwrap();
nu!(
cwd: dirs.test(),
"touch -c file.txt"
);
let metadata = path.metadata().unwrap();
// Check only the date since the time may not match exactly
let today = Local::now().date_naive();
let mtime_day = DateTime::<Local>::from(metadata.modified().unwrap()).date_naive();
let atime_day = DateTime::<Local>::from(metadata.accessed().unwrap()).date_naive();
assert_eq!(today, mtime_day);
assert_eq!(today, atime_day);
},
)
}
#[test]
fn creates_file_three_dots() {
Playground::setup("create_test_1", |dirs, _sandbox| {
nu!(
cwd: dirs.test(),
"touch file..."
);
let path = dirs.test().join("file...");
assert!(path.exists());
})
}
#[test]
fn creates_file_four_dots() {
Playground::setup("create_test_1", |dirs, _sandbox| {
nu!(
cwd: dirs.test(),
"touch file...."
);
let path = dirs.test().join("file....");
assert!(path.exists());
})
}
#[test]
fn creates_file_four_dots_quotation_marks() {
Playground::setup("create_test_1", |dirs, _sandbox| {
nu!(
cwd: dirs.test(),
"touch 'file....'"
);
let path = dirs.test().join("file....");
assert!(path.exists());
})
}
#[test]
fn change_file_times_to_reference_file() {
Playground::setup("change_dir_times_to_reference_dir", |dirs, sandbox| {
sandbox.with_files(&[
Stub::EmptyFile("reference_file"),
Stub::EmptyFile("target_file"),
]);
let reference = dirs.test().join("reference_file");
let target = dirs.test().join("target_file");
// Change the times for reference
filetime::set_file_times(&reference, FileTime::from_unix_time(1337, 0), TIME_ONE).unwrap();
// target should have today's date since it was just created, but reference should be different
assert_ne!(
reference.metadata().unwrap().accessed().unwrap(),
target.metadata().unwrap().accessed().unwrap()
);
assert_ne!(
reference.metadata().unwrap().modified().unwrap(),
target.metadata().unwrap().modified().unwrap()
);
nu!(
cwd: dirs.test(),
"touch -r reference_file target_file"
);
assert_eq!(
reference.metadata().unwrap().accessed().unwrap(),
target.metadata().unwrap().accessed().unwrap()
);
assert_eq!(
reference.metadata().unwrap().modified().unwrap(),
target.metadata().unwrap().modified().unwrap()
);
})
}
#[test]
fn change_file_mtime_to_reference() {
Playground::setup("change_file_mtime_to_reference", |dirs, sandbox| {
sandbox.with_files(&[
Stub::EmptyFile("reference_file"),
Stub::EmptyFile("target_file"),
]);
let reference = dirs.test().join("reference_file");
let target = dirs.test().join("target_file");
// Change the times for reference
filetime::set_file_times(&reference, TIME_ONE, FileTime::from_unix_time(1337, 0)).unwrap();
// target should have today's date since it was just created, but reference should be different
assert_ne!(file_times(&reference), file_times(&target));
// Save target's current atime to make sure it is preserved
let target_original_atime = target.metadata().unwrap().accessed().unwrap();
nu!(
cwd: dirs.test(),
"touch -mr reference_file target_file"
);
assert_eq!(
reference.metadata().unwrap().modified().unwrap(),
target.metadata().unwrap().modified().unwrap()
);
assert_ne!(
reference.metadata().unwrap().accessed().unwrap(),
target.metadata().unwrap().accessed().unwrap()
);
assert_eq!(
target_original_atime,
target.metadata().unwrap().accessed().unwrap()
);
})
}
// TODO when https://github.com/uutils/coreutils/issues/6629 is fixed,
// unignore this test
#[test]
#[ignore]
fn change_file_times_to_reference_file_with_date() {
Playground::setup(
"change_file_times_to_reference_file_with_date",
|dirs, sandbox| {
sandbox.with_files(&[
Stub::EmptyFile("reference_file"),
Stub::EmptyFile("target_file"),
]);
let reference = dirs.test().join("reference_file");
let target = dirs.test().join("target_file");
let now = Utc::now();
let ref_atime = now;
let ref_mtime = now.checked_sub_days(Days::new(5)).unwrap();
// Change the times for reference
filetime::set_file_times(
reference,
FileTime::from_unix_time(ref_atime.timestamp(), ref_atime.timestamp_subsec_nanos()),
FileTime::from_unix_time(ref_mtime.timestamp(), ref_mtime.timestamp_subsec_nanos()),
)
.unwrap();
nu!(
cwd: dirs.test(),
r#"touch -r reference_file -d "yesterday" target_file"#
);
let (got_atime, got_mtime) = file_times(target);
let got = (
DateTime::from_timestamp(got_atime.seconds(), got_atime.nanoseconds()).unwrap(),
DateTime::from_timestamp(got_mtime.seconds(), got_mtime.nanoseconds()).unwrap(),
);
assert_eq!(
(
now.checked_sub_days(Days::new(1)).unwrap(),
now.checked_sub_days(Days::new(6)).unwrap()
),
got
);
},
)
}
#[test]
fn change_file_times_to_timestamp() {
Playground::setup("change_file_times_to_timestamp", |dirs, sandbox| {
sandbox.with_files(&[Stub::EmptyFile("target_file")]);
let target = dirs.test().join("target_file");
let timestamp = DateTime::from_timestamp(TIME_ONE.unix_seconds(), TIME_ONE.nanoseconds())
.unwrap()
.to_rfc3339();
nu!(cwd: dirs.test(), format!("touch --timestamp {} target_file", timestamp));
assert_eq!((TIME_ONE, TIME_ONE), file_times(target));
})
}
#[test]
fn change_modified_time_of_dir_to_today() {
Playground::setup("change_dir_mtime", |dirs, sandbox| {
sandbox.mkdir("test_dir");
let path = dirs.test().join("test_dir");
filetime::set_file_mtime(&path, TIME_ONE).unwrap();
nu!(
cwd: dirs.test(),
"touch -m test_dir"
);
// Check only the date since the time may not match exactly
let today = Local::now().date_naive();
let mtime_day =
DateTime::<Local>::from(path.metadata().unwrap().modified().unwrap()).date_naive();
assert_eq!(today, mtime_day);
})
}
#[test]
fn change_access_time_of_dir_to_today() {
Playground::setup("change_dir_atime", |dirs, sandbox| {
sandbox.mkdir("test_dir");
let path = dirs.test().join("test_dir");
filetime::set_file_atime(&path, TIME_ONE).unwrap();
nu!(
cwd: dirs.test(),
"touch -a test_dir"
);
// Check only the date since the time may not match exactly
let today = Local::now().date_naive();
let atime_day =
DateTime::<Local>::from(path.metadata().unwrap().accessed().unwrap()).date_naive();
assert_eq!(today, atime_day);
})
}
#[test]
fn change_modified_and_access_time_of_dir_to_today() {
Playground::setup("change_dir_times", |dirs, sandbox| {
sandbox.mkdir("test_dir");
let path = dirs.test().join("test_dir");
filetime::set_file_times(&path, TIME_ONE, TIME_ONE).unwrap();
nu!(
cwd: dirs.test(),
"touch -a -m test_dir"
);
let metadata = path.metadata().unwrap();
// Check only the date since the time may not match exactly
let today = Local::now().date_naive();
let mtime_day = DateTime::<Local>::from(metadata.modified().unwrap()).date_naive();
let atime_day = DateTime::<Local>::from(metadata.accessed().unwrap()).date_naive();
assert_eq!(today, mtime_day);
assert_eq!(today, atime_day);
})
}
// TODO when https://github.com/uutils/coreutils/issues/6629 is fixed,
// unignore this test
#[test]
#[ignore]
fn change_file_times_to_date() {
Playground::setup("change_file_times_to_date", |dirs, sandbox| {
sandbox.with_files(&[Stub::EmptyFile("target_file")]);
let expected = Utc::now().checked_sub_signed(TimeDelta::hours(2)).unwrap();
nu!(cwd: dirs.test(), "touch -d '-2 hours' target_file");
let (got_atime, got_mtime) = file_times(dirs.test().join("target_file"));
let got_atime =
DateTime::from_timestamp(got_atime.seconds(), got_atime.nanoseconds()).unwrap();
let got_mtime =
DateTime::from_timestamp(got_mtime.seconds(), got_mtime.nanoseconds()).unwrap();
let threshold = TimeDelta::minutes(1);
assert!(
got_atime.signed_duration_since(expected).lt(&threshold)
&& got_mtime.signed_duration_since(expected).lt(&threshold),
"Expected: {expected}. Got: atime={got_atime}, mtime={got_mtime}"
);
assert!(got_mtime.signed_duration_since(expected).lt(&threshold));
})
}
#[test]
fn change_dir_three_dots_times() {
Playground::setup("change_dir_three_dots_times", |dirs, sandbox| {
sandbox.mkdir("test_dir...");
let path = dirs.test().join("test_dir...");
filetime::set_file_times(&path, TIME_ONE, TIME_ONE).unwrap();
nu!(
cwd: dirs.test(),
"touch test_dir..."
);
let metadata = path.metadata().unwrap();
// Check only the date since the time may not match exactly
let today = Local::now().date_naive();
let mtime_day = DateTime::<Local>::from(metadata.modified().unwrap()).date_naive();
let atime_day = DateTime::<Local>::from(metadata.accessed().unwrap()).date_naive();
assert_eq!(today, mtime_day);
assert_eq!(today, atime_day);
})
}
#[test]
fn change_dir_times_to_reference_dir() {
Playground::setup("change_dir_times_to_reference_dir", |dirs, sandbox| {
sandbox.mkdir("reference_dir");
sandbox.mkdir("target_dir");
let reference = dirs.test().join("reference_dir");
let target = dirs.test().join("target_dir");
// Change the times for reference
filetime::set_file_times(&reference, FileTime::from_unix_time(1337, 0), TIME_ONE).unwrap();
// target should have today's date since it was just created, but reference should be different
assert_ne!(
reference.metadata().unwrap().accessed().unwrap(),
target.metadata().unwrap().accessed().unwrap()
);
assert_ne!(
reference.metadata().unwrap().modified().unwrap(),
target.metadata().unwrap().modified().unwrap()
);
nu!(
cwd: dirs.test(),
"touch -r reference_dir target_dir"
);
assert_eq!(
reference.metadata().unwrap().accessed().unwrap(),
target.metadata().unwrap().accessed().unwrap()
);
assert_eq!(
reference.metadata().unwrap().modified().unwrap(),
target.metadata().unwrap().modified().unwrap()
);
})
}
#[test]
fn change_dir_atime_to_reference() {
Playground::setup("change_dir_atime_to_reference", |dirs, sandbox| {
sandbox.mkdir("reference_dir");
sandbox.mkdir("target_dir");
let reference = dirs.test().join("reference_dir");
let target = dirs.test().join("target_dir");
// Change the times for reference
filetime::set_file_times(&reference, FileTime::from_unix_time(1337, 0), TIME_ONE).unwrap();
// target should have today's date since it was just created, but reference should be different
assert_ne!(
reference.metadata().unwrap().accessed().unwrap(),
target.metadata().unwrap().accessed().unwrap()
);
assert_ne!(
reference.metadata().unwrap().modified().unwrap(),
target.metadata().unwrap().modified().unwrap()
);
// Save target's current mtime to make sure it is preserved
let target_original_mtime = target.metadata().unwrap().modified().unwrap();
nu!(
cwd: dirs.test(),
"touch -ar reference_dir target_dir"
);
assert_eq!(
reference.metadata().unwrap().accessed().unwrap(),
target.metadata().unwrap().accessed().unwrap()
);
assert_ne!(
reference.metadata().unwrap().modified().unwrap(),
target.metadata().unwrap().modified().unwrap()
);
assert_eq!(
target_original_mtime,
target.metadata().unwrap().modified().unwrap()
);
})
}
#[test]
fn create_a_file_with_tilde() {
Playground::setup("touch with tilde", |dirs, _| {
let actual = nu!(cwd: dirs.test(), "touch '~tilde'");
assert!(actual.err.is_empty());
assert!(files_exist_at(&[Path::new("~tilde")], dirs.test()));
// pass variable
let actual = nu!(cwd: dirs.test(), "let f = '~tilde2'; touch $f");
assert!(actual.err.is_empty());
assert!(files_exist_at(&[Path::new("~tilde2")], dirs.test()));
})
}
#[test]
fn respects_cwd() {
Playground::setup("touch_respects_cwd", |dirs, _sandbox| {
nu!(
cwd: dirs.test(),
"mkdir 'dir'; cd 'dir'; touch 'i_will_be_created.txt'"
);
let path = dirs.test().join("dir/i_will_be_created.txt");
assert!(path.exists());
})
}
#[test]
fn reference_respects_cwd() {
Playground::setup("touch_reference_respects_cwd", |dirs, _sandbox| {
nu!(
cwd: dirs.test(),
"mkdir 'dir'; cd 'dir'; touch 'ref.txt'; touch --reference 'ref.txt' 'foo.txt'"
);
let path = dirs.test().join("dir/foo.txt");
assert!(path.exists());
})
}
#[test]
fn recognizes_stdout() {
Playground::setup("touch_recognizes_stdout", |dirs, _sandbox| {
nu!(cwd: dirs.test(), "touch -");
assert!(!dirs.test().join("-").exists());
})
}
#[test]
fn follow_symlinks() {
Playground::setup("touch_follows_symlinks", |dirs, sandbox| {
setup_symlink_fs(&dirs, sandbox);
let missing = dirs.test().join("m");
assert!(!missing.exists());
nu!(
cwd: dirs.test(),
"
touch fds
touch ds
touch fs
touch fms
"
);
// We created the missing symlink target
assert!(missing.exists());
// The timestamps for files and directories were changed from TIME_ONE
let file_times = symlink_times(&dirs.test().join("f"));
let dir_times = symlink_times(&dirs.test().join("d"));
let dir_file_times = symlink_times(&dirs.test().join("d/f"));
assert_ne!(file_times, (TIME_ONE, TIME_ONE));
assert_ne!(dir_times, (TIME_ONE, TIME_ONE));
assert_ne!(dir_file_times, (TIME_ONE, TIME_ONE));
// For symlinks, they remain (mostly) the same
// We can't test accessed times, since to reach the target file, the symlink must be accessed!
let file_symlink_times = symlink_times(&dirs.test().join("fs"));
let dir_symlink_times = symlink_times(&dirs.test().join("ds"));
let dir_file_symlink_times = symlink_times(&dirs.test().join("fds"));
let file_missing_symlink_times = symlink_times(&dirs.test().join("fms"));
assert_eq!(file_symlink_times.1, TIME_ONE);
assert_eq!(dir_symlink_times.1, TIME_ONE);
assert_eq!(dir_file_symlink_times.1, TIME_ONE);
assert_eq!(file_missing_symlink_times.1, TIME_ONE);
})
}
#[test]
fn no_follow_symlinks() {
Playground::setup("touch_touches_symlinks", |dirs, sandbox| {
setup_symlink_fs(&dirs, sandbox);
let missing = dirs.test().join("m");
assert!(!missing.exists());
nu!(
cwd: dirs.test(),
"
touch fds -s
touch ds -s
touch fs -s
touch fms -s
"
);
// We did not create the missing symlink target
assert!(!missing.exists());
// The timestamps for files and directories remain the same
let file_times = symlink_times(&dirs.test().join("f"));
let dir_times = symlink_times(&dirs.test().join("d"));
let dir_file_times = symlink_times(&dirs.test().join("d/f"));
assert_eq!(file_times, (TIME_ONE, TIME_ONE));
assert_eq!(dir_times, (TIME_ONE, TIME_ONE));
assert_eq!(dir_file_times, (TIME_ONE, TIME_ONE));
// For symlinks, everything changed. (except their targets, and paths, and personality)
let file_symlink_times = symlink_times(&dirs.test().join("fs"));
let dir_symlink_times = symlink_times(&dirs.test().join("ds"));
let dir_file_symlink_times = symlink_times(&dirs.test().join("fds"));
let file_missing_symlink_times = symlink_times(&dirs.test().join("fms"));
assert_ne!(file_symlink_times, (TIME_ONE, TIME_ONE));
assert_ne!(dir_symlink_times, (TIME_ONE, TIME_ONE));
assert_ne!(dir_file_symlink_times, (TIME_ONE, TIME_ONE));
assert_ne!(file_missing_symlink_times, (TIME_ONE, TIME_ONE));
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/mut_.rs | crates/nu-command/tests/commands/mut_.rs | use nu_test_support::nu;
use rstest::rstest;
#[test]
fn mut_variable() {
let actual = nu!("mut x = 3; $x = $x + 1; $x");
assert_eq!(actual.out, "4");
}
#[rstest]
#[case("mut in = 3")]
#[case("mut in: int = 3")]
fn mut_name_builtin_var(#[case] assignment: &str) {
assert!(
nu!(assignment)
.err
.contains("'in' is the name of a builtin Nushell variable")
);
}
#[test]
fn mut_name_builtin_var_with_dollar() {
let actual = nu!("mut $env = 3");
assert!(
actual
.err
.contains("'env' is the name of a builtin Nushell variable")
)
}
#[test]
fn mut_variable_in_loop() {
let actual = nu!("mut x = 1; for i in 1..10 { $x = $x + $i}; $x");
assert_eq!(actual.out, "56");
}
#[test]
fn capture_of_mutable_var() {
let actual = nu!("mut x = 123; {|| $x }");
assert!(actual.err.contains("capture of mutable variable"));
}
#[test]
fn mut_add_assign() {
let actual = nu!("mut y = 3; $y += 2; $y");
assert_eq!(actual.out, "5");
}
#[test]
fn mut_minus_assign() {
let actual = nu!("mut y = 3; $y -= 2; $y");
assert_eq!(actual.out, "1");
}
#[test]
fn mut_multiply_assign() {
let actual = nu!("mut y = 3; $y *= 2; $y");
assert_eq!(actual.out, "6");
}
#[test]
fn mut_divide_assign() {
let actual = nu!("mut y: number = 8; $y /= 2; $y");
assert_eq!(actual.out, "4.0");
}
#[test]
fn mut_divide_assign_should_error() {
let actual = nu!("mut y = 8; $y /= 2; $y");
assert!(actual.err.contains("parser::operator_incompatible_types"));
}
#[test]
fn mut_subtract_assign_should_error() {
let actual = nu!("mut x = (date now); $x -= 2019-05-10");
assert!(actual.err.contains("parser::operator_incompatible_types"));
}
#[test]
fn mut_assign_number() {
let actual = nu!("mut x: number = 1; $x = 2.0; $x");
assert_eq!(actual.out, "2.0");
}
#[test]
fn mut_assign_glob() {
let actual = nu!(r#"mut x: glob = ""; $x = "meow"; $x"#);
assert_eq!(actual.out, "meow");
}
#[test]
fn mut_path_insert() {
let actual = nu!("mut y = {abc: 123}; $y.abc = 456; $y.abc");
assert_eq!(actual.out, "456");
}
#[test]
fn mut_path_insert_list() {
let actual = nu!("mut a = [0 1 2]; $a.3 = 3; $a | to nuon");
assert_eq!(actual.out, "[0, 1, 2, 3]");
}
#[test]
fn mut_path_upsert() {
let actual = nu!("mut a = {b:[{c:1}]}; $a.b.0.d = 11; $a.b.0.d");
assert_eq!(actual.out, "11");
}
#[test]
fn mut_path_upsert_list() {
let actual = nu!("mut a = [[[3] 2] 1]; $a.0.0.1 = 0; $a.0.2 = 0; $a.2 = 0; $a | to nuon");
assert_eq!(actual.out, "[[[3, 0], 2, 0], 1, 0]");
}
#[test]
fn mut_path_operator_assign_should_error_enforce_runtime() {
// should error on the division
let actual = nu!(
experimental: vec!["enforce-runtime-annotations".to_string()],
"mut a: record<b: int> = {b:1}; $a.b += 3; $a.b -= 2; $a.b *= 10; $a.b /= 4; $a.b",
);
assert!(actual.err.contains("nu::shell::cant_convert"));
}
#[test]
fn mut_records_update_properly() {
let actual = nu!("mut a = {}; $a.b.c = 100; $a.b.c");
assert_eq!(actual.out, "100");
}
#[test]
fn mut_value_with_if() {
let actual = nu!("mut a = 3; $a = if 3 == 3 { 10 }; echo $a");
assert_eq!(actual.out, "10");
}
#[test]
fn mut_value_with_match() {
let actual = nu!("mut a = 'maybe?'; $a = match 3 { 1 => { 'yes!' }, _ => { 'no!' } }; echo $a");
assert_eq!(actual.out, "no!");
}
#[test]
fn mut_glob_type() {
let actual = nu!("mut x: glob = 'aa'; $x | describe");
assert_eq!(actual.out, "glob");
}
#[test]
fn mut_raw_string() {
let actual = nu!(r#"mut x = r#'abcde""fghi"''''jkl'#; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"''''jkl"#);
let actual = nu!(r#"mut x = r##'abcde""fghi"''''#jkl'##; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"''''#jkl"#);
let actual = nu!(r#"mut x = r###'abcde""fghi"'''##'#jkl'###; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"'''##'#jkl"#);
let actual = nu!(r#"mut x = r#'abc'#; $x"#);
assert_eq!(actual.out, "abc");
}
#[test]
fn def_should_not_mutate_mut() {
let actual = nu!("mut a = 3; def foo [] { $a = 4}");
assert!(actual.err.contains("capture of mutable variable"));
assert!(!actual.status.success())
}
#[test]
fn assign_to_non_mut_variable_raises_parse_error() {
let actual = nu!("let x = 3; $x = 4");
assert!(
actual
.err
.contains("parser::assignment_requires_mutable_variable")
);
let actual = nu!("mut x = 3; x = 5");
assert!(actual.err.contains("parser::assignment_requires_variable"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/parse.rs | crates/nu-command/tests/commands/parse.rs | use nu_test_support::fs::Stub;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
mod simple {
use super::*;
#[test]
fn extracts_fields_from_the_given_the_pattern() {
Playground::setup("parse_test_simple_1", |dirs, sandbox| {
sandbox.with_files(&[Stub::FileWithContentToBeTrimmed(
"key_value_separated_arepa_ingredients.txt",
r#"
VAR1=Cheese
VAR2=JTParsed
VAR3=NushellSecretIngredient
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open key_value_separated_arepa_ingredients.txt
| lines
| each { |it| echo $it | parse "{Name}={Value}" }
| flatten
| get 1
| get Value
"#);
assert_eq!(actual.out, "JTParsed");
})
}
#[test]
fn double_open_curly_evaluates_to_a_single_curly() {
let actual = nu!(r#"
echo "{abc}123"
| parse "{{abc}{name}"
| get name.0
"#);
assert_eq!(actual.out, "123");
}
#[test]
fn properly_escapes_text() {
let actual = nu!(r#"
echo "(abc)123"
| parse "(abc){name}"
| get name.0
"#);
assert_eq!(actual.out, "123");
}
#[test]
fn properly_captures_empty_column() {
let actual = nu!(r#"
echo ["1:INFO:component:all is well" "2:ERROR::something bad happened"]
| parse "{timestamp}:{level}:{tag}:{entry}"
| get entry
| get 1
"#);
assert_eq!(actual.out, "something bad happened");
}
#[test]
fn errors_when_missing_closing_brace() {
let actual = nu!(r#"
echo "(abc)123"
| parse "(abc){name"
| get name
"#);
assert!(
actual
.err
.contains("Found opening `{` without an associated closing `}`")
);
}
#[test]
fn ignore_multiple_placeholder() {
let actual = nu!(r#"
echo ["1:INFO:component:all is well" "2:ERROR::something bad happened"]
| parse "{_}:{level}:{_}:{entry}"
| to json -r
"#);
assert_eq!(
actual.out,
r#"[{"level":"INFO","entry":"all is well"},{"level":"ERROR","entry":"something bad happened"}]"#
);
}
}
mod regex {
use super::*;
fn nushell_git_log_oneline<'a>() -> Vec<Stub<'a>> {
vec![Stub::FileWithContentToBeTrimmed(
"nushell_git_log_oneline.txt",
r#"
ae87582c Fix missing invocation errors (#1846)
b89976da let format access variables also (#1842)
"#,
)]
}
#[test]
fn extracts_fields_with_all_named_groups() {
Playground::setup("parse_test_regex_1", |dirs, sandbox| {
sandbox.with_files(&nushell_git_log_oneline());
let actual = nu!(cwd: dirs.test(), r#"
open nushell_git_log_oneline.txt
| parse --regex "(?P<Hash>\\w+) (?P<Message>.+) \\(#(?P<PR>\\d+)\\)"
| get 1
| get PR
"#);
assert_eq!(actual.out, "1842");
})
}
#[test]
fn extracts_fields_with_all_unnamed_groups() {
Playground::setup("parse_test_regex_2", |dirs, sandbox| {
sandbox.with_files(&nushell_git_log_oneline());
let actual = nu!(cwd: dirs.test(), r#"
open nushell_git_log_oneline.txt
| parse --regex "(\\w+) (.+) \\(#(\\d+)\\)"
| get 1
| get capture0
"#);
assert_eq!(actual.out, "b89976da");
})
}
#[test]
fn extracts_fields_with_named_and_unnamed_groups() {
Playground::setup("parse_test_regex_3", |dirs, sandbox| {
sandbox.with_files(&nushell_git_log_oneline());
let actual = nu!(cwd: dirs.test(), r#"
open nushell_git_log_oneline.txt
| parse --regex "(?P<Hash>\\w+) (.+) \\(#(?P<PR>\\d+)\\)"
| get 1
| get capture1
"#);
assert_eq!(actual.out, "let format access variables also");
})
}
#[test]
fn errors_with_invalid_regex() {
Playground::setup("parse_test_regex_1", |dirs, sandbox| {
sandbox.with_files(&nushell_git_log_oneline());
let actual = nu!(cwd: dirs.test(), r#"
open nushell_git_log_oneline.txt
| parse --regex "(?P<Hash>\\w+ unfinished capture group"
"#);
assert!(
actual
.err
.contains("Opening parenthesis without closing parenthesis")
);
})
}
#[test]
fn parse_works_with_streaming() {
let actual =
nu!(r#"seq char a z | each {|c| $c + " a"} | parse '{letter} {a}' | describe"#);
assert_eq!(actual.out, "table<letter: string, a: string> (stream)")
}
#[test]
fn parse_does_not_truncate_list_streams() {
let actual = nu!(r#"
[a b c]
| each {|x| $x}
| parse --regex "[ac]"
| length
"#);
assert_eq!(actual.out, "2");
}
#[test]
fn parse_handles_external_stream_chunking() {
Playground::setup("parse_test_streaming_1", |dirs, sandbox| {
let data: String = "abcdefghijklmnopqrstuvwxyz".repeat(1000);
sandbox.with_files(&[Stub::FileWithContent("data.txt", &data)]);
let actual = nu!(
cwd: dirs.test(),
r#"open data.txt | parse --regex "(abcdefghijklmnopqrstuvwxyz)" | length"#
);
assert_eq!(actual.out, "1000");
})
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/insert.rs | crates/nu-command/tests/commands/insert.rs | use nu_test_support::nu;
#[test]
fn insert_the_column() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml
| insert dev-dependencies.new_assertions "0.7.0"
| get dev-dependencies.new_assertions
"#);
assert_eq!(actual.out, "0.7.0");
}
#[test]
fn doesnt_convert_record_to_table() {
let actual = nu!("{a:1} | insert b 2 | to nuon");
assert_eq!(actual.out, "{a: 1, b: 2}");
}
#[test]
fn insert_the_column_conflict() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml
| insert dev-dependencies.pretty_assertions "0.7.0"
"#);
assert!(
actual
.err
.contains("column 'pretty_assertions' already exists")
);
}
#[test]
fn insert_into_list() {
let actual = nu!("[1, 2, 3] | insert 1 abc | to json -r");
assert_eq!(actual.out, r#"[1,"abc",2,3]"#);
}
#[test]
fn insert_at_start_of_list() {
let actual = nu!("[1, 2, 3] | insert 0 abc | to json -r");
assert_eq!(actual.out, r#"["abc",1,2,3]"#);
}
#[test]
fn insert_at_end_of_list() {
let actual = nu!("[1, 2, 3] | insert 3 abc | to json -r");
assert_eq!(actual.out, r#"[1,2,3,"abc"]"#);
}
#[test]
fn insert_past_end_of_list() {
let actual = nu!("[1, 2, 3] | insert 5 abc");
assert!(
actual
.err
.contains("can't insert at index (the next available index is 3)")
);
}
#[test]
fn insert_into_list_stream() {
let actual = nu!("[1, 2, 3] | every 1 | insert 1 abc | to json -r");
assert_eq!(actual.out, r#"[1,"abc",2,3]"#);
}
#[test]
fn insert_at_end_of_list_stream() {
let actual = nu!("[1, 2, 3] | every 1 | insert 3 abc | to json -r");
assert_eq!(actual.out, r#"[1,2,3,"abc"]"#);
}
#[test]
fn insert_past_end_of_list_stream() {
let actual = nu!("[1, 2, 3] | every 1 | insert 5 abc");
assert!(
actual
.err
.contains("can't insert at index (the next available index is 3)")
);
}
#[test]
fn insert_uses_enumerate_index() {
let actual = nu!(
"[[a]; [7] [6]] | enumerate | insert b {|el| $el.index + 1 + $el.item.a } | flatten | to nuon"
);
assert_eq!(actual.out, "[[index, a, b]; [0, 7, 8], [1, 6, 8]]");
}
#[test]
fn deep_cell_path_creates_all_nested_records() {
let actual = nu!("{a: {}} | insert a.b.c 0 | get a.b.c");
assert_eq!(actual.out, "0");
}
#[test]
fn inserts_all_rows_in_table_in_record() {
let actual = nu!(
"{table: [[col]; [{a: 1}], [{a: 1}]]} | insert table.col.b 2 | get table.col.b | to nuon"
);
assert_eq!(actual.out, "[2, 2]");
}
#[test]
fn list_replacement_closure() {
let actual = nu!("[1, 2] | insert 1 {|i| $i + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3, 2]");
let actual = nu!("[1, 2] | insert 1 { $in + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3, 2]");
let actual = nu!("[1, 2] | insert 2 {|i| if $i == null { 0 } else { $in + 1 } } | to nuon");
assert_eq!(actual.out, "[1, 2, 0]");
let actual = nu!("[1, 2] | insert 2 { if $in == null { 0 } else { $in + 1 } } | to nuon");
assert_eq!(actual.out, "[1, 2, 0]");
}
#[test]
fn record_replacement_closure() {
let actual = nu!("{ a: text } | insert b {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "{a: text, b: TEXT}");
let actual = nu!("{ a: text } | insert b { $in.a | str upcase } | to nuon");
assert_eq!(actual.out, "{a: text, b: TEXT}");
let actual = nu!("{ a: { b: 1 } } | insert a.c {|r| $r.a.b } | to nuon");
assert_eq!(actual.out, "{a: {b: 1, c: 1}}");
let actual = nu!("{ a: { b: 1 } } | insert a.c { $in.a.b } | to nuon");
assert_eq!(actual.out, "{a: {b: 1, c: 1}}");
}
#[test]
fn table_replacement_closure() {
let actual = nu!("[[a]; [text]] | insert b {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "[[a, b]; [text, TEXT]]");
let actual = nu!("[[a]; [text]] | insert b { $in.a | str upcase } | to nuon");
assert_eq!(actual.out, "[[a, b]; [text, TEXT]]");
let actual = nu!("[[b]; [1]] | wrap a | insert a.c {|r| $r.a.b } | to nuon");
assert_eq!(actual.out, "[[a]; [{b: 1, c: 1}]]");
let actual = nu!("[[b]; [1]] | wrap a | insert a.c { $in.a.b } | to nuon");
assert_eq!(actual.out, "[[a]; [{b: 1, c: 1}]]");
}
#[test]
fn list_stream_replacement_closure() {
let actual = nu!("[1, 2] | every 1 | insert 1 {|i| $i + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3, 2]");
let actual = nu!("[1, 2] | every 1 | insert 1 { $in + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3, 2]");
let actual =
nu!("[1, 2] | every 1 | insert 2 {|i| if $i == null { 0 } else { $in + 1 } } | to nuon");
assert_eq!(actual.out, "[1, 2, 0]");
let actual =
nu!("[1, 2] | every 1 | insert 2 { if $in == null { 0 } else { $in + 1 } } | to nuon");
assert_eq!(actual.out, "[1, 2, 0]");
let actual = nu!("[[a]; [text]] | every 1 | insert b {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "[[a, b]; [text, TEXT]]");
let actual = nu!("[[a]; [text]] | every 1 | insert b { $in.a | str upcase } | to nuon");
assert_eq!(actual.out, "[[a, b]; [text, TEXT]]");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/update.rs | crates/nu-command/tests/commands/update.rs | use nu_test_support::nu;
#[test]
fn sets_the_column() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml
| update dev-dependencies.pretty_assertions "0.7.0"
| get dev-dependencies.pretty_assertions
"#);
assert_eq!(actual.out, "0.7.0");
}
#[test]
fn doesnt_convert_record_to_table() {
let actual = nu!("{a:1} | update a 2 | to nuon");
assert_eq!(actual.out, "{a: 2}");
}
#[test]
fn sets_the_column_from_a_block_full_stream_output() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
{content: null}
| update content {|| open --raw cargo_sample.toml | lines | first 5 }
| get content.1
| str contains "nu"
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn sets_the_column_from_a_subexpression() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
{content: null}
| update content (open --raw cargo_sample.toml | lines | first 5)
| get content.1
| str contains "nu"
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn upsert_column_missing() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml
| update dev-dependencies.new_assertions "0.7.0"
"#);
assert!(actual.err.contains("cannot find column"));
}
#[test]
fn update_list() {
let actual = nu!("[1, 2, 3] | update 1 abc | to json -r");
assert_eq!(actual.out, r#"[1,"abc",3]"#);
}
#[test]
fn update_past_end_of_list() {
let actual = nu!("[1, 2, 3] | update 5 abc | to json -r");
assert!(actual.err.contains("too large"));
}
#[test]
fn update_list_stream() {
let actual = nu!("[1, 2, 3] | every 1 | update 1 abc | to json -r");
assert_eq!(actual.out, r#"[1,"abc",3]"#);
}
#[test]
fn update_past_end_of_list_stream() {
let actual = nu!("[1, 2, 3] | every 1 | update 5 abc | to json -r");
assert!(actual.err.contains("too large"));
}
#[test]
fn update_nonexistent_column() {
let actual = nu!("{a:1} | update b 2");
assert!(actual.err.contains("cannot find column 'b'"));
}
#[test]
fn update_uses_enumerate_index() {
let actual = nu!(
"[[a]; [7] [6]] | enumerate | update item.a {|el| $el.index + 1 + $el.item.a } | flatten | to nuon"
);
assert_eq!(actual.out, "[[index, a]; [0, 8], [1, 8]]");
}
#[test]
fn list_replacement_closure() {
let actual = nu!("[1, 2] | update 1 {|i| $i + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3]");
let actual = nu!("[1, 2] | update 1 { $in + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3]");
}
#[test]
fn record_replacement_closure() {
let actual = nu!("{ a: text } | update a {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "{a: TEXT}");
let actual = nu!("{ a: text } | update a { str upcase } | to nuon");
assert_eq!(actual.out, "{a: TEXT}");
}
#[test]
fn table_replacement_closure() {
let actual = nu!("[[a]; [text]] | update a {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "[[a]; [TEXT]]");
let actual = nu!("[[a]; [text]] | update a { str upcase } | to nuon");
assert_eq!(actual.out, "[[a]; [TEXT]]");
}
#[test]
fn list_stream_replacement_closure() {
let actual = nu!("[1, 2] | every 1 | update 1 {|i| $i + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3]");
let actual = nu!("[1, 2] | every 1 | update 1 { $in + 1 } | to nuon");
assert_eq!(actual.out, "[1, 3]");
let actual = nu!("[[a]; [text]] | every 1 | update a {|r| $r.a | str upcase } | to nuon");
assert_eq!(actual.out, "[[a]; [TEXT]]");
let actual = nu!("[[a]; [text]] | every 1 | update a { str upcase } | to nuon");
assert_eq!(actual.out, "[[a]; [TEXT]]");
}
#[test]
fn update_optional_column_present() {
let actual = nu!("{a: 1} | update a? 2 | to nuon");
assert_eq!(actual.out, "{a: 2}");
}
#[test]
fn update_optional_column_absent() {
let actual = nu!("{a: 1} | update b? 2 | to nuon");
assert_eq!(actual.out, "{a: 1}");
}
#[test]
fn update_optional_column_in_table_present() {
let actual = nu!("[[a, b]; [1, 2], [3, 4]] | update a? 10 | to nuon");
assert_eq!(actual.out, "[[a, b]; [10, 2], [10, 4]]");
}
#[test]
fn update_optional_column_in_table_absent() {
let actual = nu!("[[a, b]; [1, 2], [3, 4]] | update c? 10 | to nuon");
assert_eq!(actual.out, "[[a, b]; [1, 2], [3, 4]]");
}
#[test]
fn update_optional_column_in_table_mixed() {
let actual = nu!("[{a: 1, b: 2}, {b: 3}, {a: 4, b: 5}] | update a? 10 | to nuon");
assert_eq!(actual.out, "[{a: 10, b: 2}, {b: 3}, {a: 10, b: 5}]");
}
#[test]
fn update_optional_index_present() {
let actual = nu!("[1, 2, 3] | update 1? 10 | to nuon");
assert_eq!(actual.out, "[1, 10, 3]");
}
#[test]
fn update_optional_index_absent() {
let actual = nu!("[1, 2, 3] | update 5? 10 | to nuon");
assert_eq!(actual.out, "[1, 2, 3]");
}
#[test]
fn update_optional_column_with_closure_present() {
let actual = nu!("{a: 5} | update a? {|x| $x.a * 2 } | to nuon");
assert_eq!(actual.out, "{a: 10}");
}
#[test]
fn update_optional_column_with_closure_absent() {
let actual = nu!("{a: 5} | update b? {|x| 10 } | to nuon");
assert_eq!(actual.out, "{a: 5}");
}
#[test]
fn update_optional_column_in_table_with_closure() {
let actual = nu!("[[a]; [1], [2]] | update a? { $in * 2 } | to nuon");
assert_eq!(actual.out, "[[a]; [2], [4]]");
}
#[test]
fn update_optional_column_in_table_with_closure_mixed() {
let actual = nu!("[{a: 1, b: 2}, {b: 3}, {a: 4, b: 5}] | update a? { $in * 10 } | to nuon");
assert_eq!(actual.out, "[{a: 10, b: 2}, {b: 3}, {a: 40, b: 5}]");
}
#[test]
fn update_optional_index_with_closure_present() {
let actual = nu!("[1, 2, 3] | update 1? { $in * 10 } | to nuon");
assert_eq!(actual.out, "[1, 20, 3]");
}
#[test]
fn update_optional_index_with_closure_absent() {
let actual = nu!("[1, 2, 3] | update 5? { $in * 10 } | to nuon");
assert_eq!(actual.out, "[1, 2, 3]");
}
#[test]
fn update_optional_in_list_stream() {
let actual = nu!("[[a, b]; [1, 2], [3, 4]] | every 1 | update c? 10 | to nuon");
assert_eq!(actual.out, "[[a, b]; [1, 2], [3, 4]]");
}
#[test]
fn update_optional_in_list_stream_with_closure() {
let actual = nu!("[{a: 1}, {b: 2}, {a: 3}] | every 1 | update a? { $in * 10 } | to nuon");
assert_eq!(actual.out, "[{a: 10}, {b: 2}, {a: 30}]");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/all.rs | crates/nu-command/tests/commands/all.rs | use nu_test_support::nu;
#[test]
fn checks_all_rows_are_true() {
let actual = nu!(r#"
echo [ "Andrés", "Andrés", "Andrés" ]
| all {|it| $it == "Andrés" }
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn checks_all_rows_are_false_with_param() {
let actual = nu!(" [1, 2, 3, 4] | all { |a| $a >= 5 } ");
assert_eq!(actual.out, "false");
}
#[test]
fn checks_all_rows_are_true_with_param() {
let actual = nu!(" [1, 2, 3, 4] | all { |a| $a < 5 } ");
assert_eq!(actual.out, "true");
}
#[test]
fn checks_all_columns_of_a_table_is_true() {
let actual = nu!("
echo [
[ first_name, last_name, rusty_at, likes ];
[ Andrés, Robalino, '10/11/2013', 1 ]
[ JT, Turner, '10/12/2013', 1 ]
[ Darren, Schroeder, '10/11/2013', 1 ]
[ Yehuda, Katz, '10/11/2013', 1 ]
]
| all {|x| $x.likes > 0 }
");
assert_eq!(actual.out, "true");
}
#[test]
fn checks_if_all_returns_error_with_invalid_command() {
// Using `with-env` to remove `st` possibly being an external program
let actual = nu!(r#"
with-env {PATH: ""} {
[red orange yellow green blue purple] | all {|it| ($it | st length) > 4 }
}
"#);
assert!(
actual.err.contains("Command `st` not found") && actual.err.contains("Did you mean `ast`?")
);
}
#[test]
fn works_with_1_param_blocks() {
let actual = nu!("[1 2 3] | all {|e| print $e | true }");
assert_eq!(actual.out, "123true");
}
#[test]
fn works_with_0_param_blocks() {
let actual = nu!("[1 2 3] | all {|| print $in | true }");
assert_eq!(actual.out, "123true");
}
#[test]
fn early_exits_with_1_param_blocks() {
let actual = nu!("[1 2 3] | all {|e| print $e | false }");
assert_eq!(actual.out, "1false");
}
#[test]
fn early_exits_with_0_param_blocks() {
let actual = nu!("[1 2 3] | all {|| print $in | false }");
assert_eq!(actual.out, "1false");
}
#[test]
fn all_uses_enumerate_index() {
let actual = nu!("[7 8 9] | enumerate | all {|el| print $el.index | true }");
assert_eq!(actual.out, "012true");
}
#[test]
fn unique_env_each_iteration() {
let actual = nu!(
cwd: "tests/fixtures/formats",
"[1 2] | all {|| print ($env.PWD | str ends-with 'formats') | cd '/' | true } | to nuon"
);
assert_eq!(actual.out, "truetruetrue");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/compact.rs | crates/nu-command/tests/commands/compact.rs | use nu_test_support::nu;
#[test]
fn discards_rows_where_given_column_is_empty() {
let sample_json = r#"{
"amigos": [
{"name": "Yehuda", "rusty_luck": 1},
{"name": "JT", "rusty_luck": 1},
{"name": "Andres", "rusty_luck": 1},
{"name":"GorbyPuff"}
]
}"#;
let actual = nu!(format!(
"
{sample_json}
| get amigos
| compact rusty_luck
| length
"
));
assert_eq!(actual.out, "3");
}
#[test]
fn discards_empty_rows_by_default() {
let actual = nu!(r#"
echo "[1,2,3,14,null]"
| from json
| compact
| length
"#);
assert_eq!(actual.out, "4");
}
#[test]
fn discard_empty_list_in_table() {
let actual = nu!(r#"
[["a", "b"]; ["c", "d"], ["h", []]] | compact -e b | length
"#);
assert_eq!(actual.out, "1");
}
#[test]
fn discard_empty_record_in_table() {
let actual = nu!(r#"
[["a", "b"]; ["c", "d"], ["h", {}]] | compact -e b | length
"#);
assert_eq!(actual.out, "1");
}
#[test]
fn dont_discard_empty_record_in_table_if_column_not_set() {
let actual = nu!(r#"
[["a", "b"]; ["c", "d"], ["h", {}]] | compact -e | length
"#);
assert_eq!(actual.out, "2");
}
#[test]
fn dont_discard_empty_list_in_table_if_column_not_set() {
let actual = nu!(r#"
[["a", "b"]; ["c", "d"], ["h", []]] | compact -e | length
"#);
assert_eq!(actual.out, "2");
}
#[test]
fn dont_discard_null_in_table_if_column_not_set() {
let actual = nu!(r#"
[["a", "b"]; ["c", "d"], ["h", null]] | compact -e | length
"#);
assert_eq!(actual.out, "2");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/do_.rs | crates/nu-command/tests/commands/do_.rs | use nu_test_support::nu;
#[test]
fn capture_errors_works() {
let actual = nu!("do -c {$env.use}");
eprintln!("actual.err: {:?}", actual.err);
assert!(actual.err.contains("column_not_found"));
}
// TODO: need to add tests under display_error.exit_code = true
#[test]
fn capture_errors_works_for_external() {
let actual = nu!("do -c {nu --testbin fail}");
assert!(!actual.status.success());
assert!(!actual.err.contains("exited with code"));
}
// TODO: need to add tests under display_error.exit_code = true
#[test]
fn capture_errors_works_for_external_with_pipeline() {
let actual = nu!("do -c {nu --testbin fail} | echo `text`");
assert!(!actual.status.success());
assert!(!actual.err.contains("exited with code"));
}
// TODO: need to add tests under display_error.exit_code = true
#[test]
fn capture_errors_works_for_external_with_semicolon() {
let actual = nu!(r#"do -c {nu --testbin fail}; echo `text`"#);
assert!(!actual.status.success());
assert!(!actual.err.contains("exited with code"));
}
#[test]
fn do_with_semicolon_break_on_failed_external() {
let actual = nu!(r#"do { nu --not_exist_flag }; `text`"#);
assert_eq!(actual.out, "");
}
#[test]
fn ignore_error_should_work_for_external_command() {
let actual = nu!(r#"do -i { nu --testbin fail 1 }; echo post"#);
assert_eq!(actual.err, "");
assert_eq!(actual.out, "post");
}
#[test]
fn ignore_error_works_with_list_stream() {
let actual = nu!(r#"do -i { ["a", null, "b"] | ansi strip }"#);
assert!(actual.err.is_empty());
}
#[test]
fn run_closure_with_it_using() {
let actual = nu!(r#"let x = {let it = 3; $it}; do $x"#);
assert!(actual.err.is_empty());
assert_eq!(actual.out, "3");
}
#[test]
fn required_argument_type_checked() {
let actual = nu!(r#"do {|x: string| $x} 4"#);
assert!(actual.out.is_empty());
assert!(actual.err.contains("nu::shell::cant_convert"));
}
#[test]
fn optional_argument_type_checked() {
let actual = nu!(r#"do {|x?: string| $x} 4"#);
assert_eq!(actual.out, "");
assert!(actual.err.contains("nu::shell::cant_convert"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/prepend.rs | crates/nu-command/tests/commands/prepend.rs | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn adds_a_row_to_the_beginning() {
Playground::setup("prepend_test_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"los_tres_caballeros.txt",
r#"
Andrés N. Robalino
JT Turner
Yehuda Katz
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
open los_tres_caballeros.txt
| lines
| prepend "pollo loco"
| get 0
"#);
assert_eq!(actual.out, "pollo loco");
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/griddle.rs | crates/nu-command/tests/commands/griddle.rs | use nu_test_support::nu;
#[test]
fn grid_errors_with_few_columns() {
let actual = nu!("[1 2 3 4 5] | grid --width 5");
assert!(actual.err.contains("Couldn't fit grid into 5 columns"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/cd.rs | crates/nu-command/tests/commands/cd.rs | use nu_path::Path;
use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn cd_works_with_in_var() {
Playground::setup("cd_test_1", |dirs, _| {
let actual = nu!(
cwd: dirs.root(),
r#"
"cd_test_1" | cd $in; $env.PWD | path split | last
"#
);
assert_eq!("cd_test_1", actual.out);
})
}
#[test]
fn filesystem_change_from_current_directory_using_relative_path() {
Playground::setup("cd_test_1", |dirs, _| {
let actual = nu!( cwd: dirs.root(), "cd cd_test_1; $env.PWD");
assert_eq!(Path::new(&actual.out), dirs.test());
})
}
#[test]
fn filesystem_change_from_current_directory_using_relative_path_with_trailing_slash() {
Playground::setup("cd_test_1_slash", |dirs, _| {
// Intentionally not using correct path sep because this should work on Windows
let actual = nu!( cwd: dirs.root(), "cd cd_test_1_slash/; $env.PWD");
assert_eq!(Path::new(&actual.out), *dirs.test());
})
}
#[test]
fn filesystem_change_from_current_directory_using_absolute_path() {
Playground::setup("cd_test_2", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!(
r#"
cd '{}'
$env.PWD
"#,
dirs.formats().display()
)
);
assert_eq!(Path::new(&actual.out), dirs.formats());
})
}
#[test]
fn filesystem_change_from_current_directory_using_absolute_path_with_trailing_slash() {
Playground::setup("cd_test_2", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!(
r#"
cd '{}{}'
$env.PWD
"#,
dirs.formats().display(),
std::path::MAIN_SEPARATOR_STR,
)
);
assert_eq!(Path::new(&actual.out), dirs.formats());
})
}
#[test]
fn filesystem_switch_back_to_previous_working_directory() {
Playground::setup("cd_test_3", |dirs, sandbox| {
sandbox.mkdir("odin");
let actual = nu!(
cwd: dirs.test().join("odin"),
format!(
"
cd {}
cd -
$env.PWD
",
dirs.test().display()
)
);
assert_eq!(Path::new(&actual.out), dirs.test().join("odin"));
})
}
#[test]
fn filesystem_change_from_current_directory_using_relative_path_and_dash() {
Playground::setup("cd_test_4", |dirs, sandbox| {
sandbox.within("odin").mkdir("-");
let actual = nu!(
cwd: dirs.test(),
"
cd odin/-
$env.PWD
"
);
assert_eq!(Path::new(&actual.out), dirs.test().join("odin").join("-"));
})
}
#[test]
fn filesystem_change_current_directory_to_parent_directory() {
Playground::setup("cd_test_5", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"
cd ..
$env.PWD
"
);
assert_eq!(Path::new(&actual.out), *dirs.root());
})
}
#[test]
fn filesystem_change_current_directory_to_two_parents_up_using_multiple_dots() {
Playground::setup("cd_test_6", |dirs, sandbox| {
sandbox.within("foo").mkdir("bar");
let actual = nu!(
cwd: dirs.test().join("foo/bar"),
"
cd ...
$env.PWD
"
);
assert_eq!(Path::new(&actual.out), *dirs.test());
})
}
#[test]
fn filesystem_change_to_home_directory() {
Playground::setup("cd_test_8", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"
cd ~
$env.PWD
"
);
assert_eq!(Path::new(&actual.out), dirs::home_dir().unwrap());
})
}
#[test]
fn filesystem_change_to_a_directory_containing_spaces() {
Playground::setup("cd_test_9", |dirs, sandbox| {
sandbox.mkdir("robalino turner katz");
let actual = nu!(
cwd: dirs.test(),
r#"
cd "robalino turner katz"
$env.PWD
"#
);
assert_eq!(
Path::new(&actual.out),
dirs.test().join("robalino turner katz")
);
})
}
#[test]
fn filesystem_not_a_directory() {
Playground::setup("cd_test_10", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("ferris_did_it.txt")]);
let actual = nu!(
cwd: dirs.test(),
"cd ferris_did_it.txt"
);
assert!(
actual.err.contains("ferris_did_it.txt"),
"actual={:?}",
actual.err
);
assert!(
actual.err.contains("nu::shell::io::not_a_directory"),
"actual={:?}",
actual.err
);
})
}
#[test]
fn filesystem_directory_not_found() {
Playground::setup("cd_test_11", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"cd dir_that_does_not_exist"
);
assert!(
actual.err.contains("dir_that_does_not_exist"),
"actual={:?}",
actual.err
);
assert!(
actual.err.contains("nu::shell::io::directory_not_found"),
"actual={:?}",
actual.err
);
})
}
#[test]
fn filesystem_change_directory_to_symlink_relative() {
Playground::setup("cd_test_12", |dirs, sandbox| {
sandbox.mkdir("foo");
sandbox.mkdir("boo");
sandbox.symlink("foo", "foo_link");
let actual = nu!(
cwd: dirs.test().join("boo"),
"
cd ../foo_link
$env.PWD
"
);
assert_eq!(Path::new(&actual.out), dirs.test().join("foo_link"));
let actual = nu!(
cwd: dirs.test().join("boo"),
"
cd -P ../foo_link
$env.PWD
"
);
assert_eq!(Path::new(&actual.out), dirs.test().join("foo"));
})
}
// FIXME: jt: needs more work
#[ignore]
#[cfg(target_os = "windows")]
#[test]
fn test_change_windows_drive() {
Playground::setup("cd_test_20", |dirs, sandbox| {
sandbox.mkdir("test_folder");
let _actual = nu!(
cwd: dirs.test(),
r#"
subst Z: test_folder
Z:
echo "some text" | save test_file.txt
cd ~
subst Z: /d
"#
);
assert!(
dirs.test()
.join("test_folder")
.join("test_file.txt")
.exists()
);
})
}
#[cfg(unix)]
#[test]
fn cd_permission_denied_folder() {
Playground::setup("cd_test_21", |dirs, sandbox| {
sandbox.mkdir("banned");
let actual = nu!(
cwd: dirs.test(),
"
chmod -x banned
cd banned
"
);
assert!(actual.err.contains("nu::shell::io::permission_denied"));
nu!(
cwd: dirs.test(),
"
chmod +x banned
rm banned
"
);
});
}
// FIXME: cd_permission_denied_folder on windows
#[ignore]
#[cfg(windows)]
#[test]
fn cd_permission_denied_folder() {
Playground::setup("cd_test_21", |dirs, sandbox| {
sandbox.mkdir("banned");
let actual = nu!(
cwd: dirs.test(),
r"
icacls banned /deny BUILTIN\Administrators:F
cd banned
"
);
assert!(actual.err.contains("Folder is not able to read"));
});
}
#[test]
#[cfg(unix)]
fn pwd_recovery() {
let nu = nu_test_support::fs::executable_path().display().to_string();
let tmpdir = std::env::temp_dir().join("foobar").display().to_string();
// We `cd` into a temporary directory, then spawn another `nu` process to
// delete that directory. Then we attempt to recover by running `cd /`.
let cmd = format!("mkdir {tmpdir}; cd {tmpdir}; {nu} -c 'cd /; rm -r {tmpdir}'; cd /; pwd");
let actual = nu!(cmd);
assert_eq!(actual.out, "/");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/filter.rs | crates/nu-command/tests/commands/filter.rs | use nu_test_support::nu;
#[test]
fn filter_with_return_in_closure() {
let actual = nu!("
1..10 | filter { |it|
if $it mod 2 == 0 {
return true
};
return false;
} | to nuon
");
assert_eq!(actual.out, "[2, 4, 6, 8, 10]");
assert!(actual.err.contains("deprecated"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/split_row.rs | crates/nu-command/tests/commands/split_row.rs | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn to_row() {
Playground::setup("split_row_test_1", |dirs, sandbox| {
sandbox.with_files(&[
FileWithContentToBeTrimmed(
"sample.txt",
r#"
importer,shipper,tariff_item,name,origin
"#,
),
FileWithContentToBeTrimmed(
"sample2.txt",
r#"
importer , shipper , tariff_item,name , origin
"#,
),
]);
let actual = nu!(cwd: dirs.test(), r#"
open sample.txt
| lines
| str trim
| split row ","
| length
"#);
assert!(actual.out.contains('5'));
let actual = nu!(cwd: dirs.test(), r"
open sample2.txt
| lines
| str trim
| split row -r '\s*,\s*'
| length
");
assert!(actual.out.contains('5'));
let actual = nu!(r#"
def foo [a: list<string>] {
$a | describe
}
foo (["a b", "c d"] | split row " ")
"#);
assert!(actual.out.contains("list<string>"));
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/rm.rs | crates/nu-command/tests/commands/rm.rs | #[cfg(not(windows))]
use nu_path::AbsolutePath;
use nu_test_support::fs::{Stub::EmptyFile, files_exist_at};
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use rstest::rstest;
#[cfg(not(windows))]
use std::fs;
#[cfg(windows)]
use std::{fs::OpenOptions, os::windows::fs::OpenOptionsExt};
#[test]
fn removes_a_file() {
Playground::setup("rm_test_1", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("i_will_be_deleted.txt")]);
nu!(
cwd: dirs.root(),
"rm rm_test_1/i_will_be_deleted.txt"
);
let path = dirs.test().join("i_will_be_deleted.txt");
assert!(!path.exists());
})
}
#[test]
fn removes_files_with_wildcard() {
Playground::setup("rm_test_2", |dirs, sandbox| {
sandbox
.within("src")
.with_files(&[
EmptyFile("cli.rs"),
EmptyFile("lib.rs"),
EmptyFile("prelude.rs"),
])
.within("src/parser")
.with_files(&[EmptyFile("parse.rs"), EmptyFile("parser.rs")])
.within("src/parser/parse")
.with_files(&[EmptyFile("token_tree.rs")])
.within("src/parser/hir")
.with_files(&[
EmptyFile("baseline_parse.rs"),
EmptyFile("baseline_parse_tokens.rs"),
]);
nu!(
cwd: dirs.test(),
r#"rm src/*/*/*.rs"#
);
assert!(!files_exist_at(
&[
"src/parser/parse/token_tree.rs",
"src/parser/hir/baseline_parse.rs",
"src/parser/hir/baseline_parse_tokens.rs"
],
dirs.test()
));
assert_eq!(
Playground::glob_vec(&format!("{}/src/*/*/*.rs", dirs.test().display())),
Vec::<std::path::PathBuf>::new()
);
})
}
#[test]
fn removes_deeply_nested_directories_with_wildcard_and_recursive_flag() {
Playground::setup("rm_test_3", |dirs, sandbox| {
sandbox
.within("src")
.with_files(&[
EmptyFile("cli.rs"),
EmptyFile("lib.rs"),
EmptyFile("prelude.rs"),
])
.within("src/parser")
.with_files(&[EmptyFile("parse.rs"), EmptyFile("parser.rs")])
.within("src/parser/parse")
.with_files(&[EmptyFile("token_tree.rs")])
.within("src/parser/hir")
.with_files(&[
EmptyFile("baseline_parse.rs"),
EmptyFile("baseline_parse_tokens.rs"),
]);
nu!(
cwd: dirs.test(),
"rm -r src/*"
);
assert!(!files_exist_at(
&["src/parser/parse", "src/parser/hir"],
dirs.test()
));
})
}
#[test]
fn removes_directory_contents_without_recursive_flag_if_empty() {
Playground::setup("rm_test_4", |dirs, _| {
nu!(
cwd: dirs.root(),
"rm rm_test_4"
);
assert!(!dirs.test().exists());
})
}
#[test]
fn removes_directory_contents_with_recursive_flag() {
Playground::setup("rm_test_5", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
]);
nu!(
cwd: dirs.root(),
"rm rm_test_5 --recursive"
);
assert!(!dirs.test().exists());
})
}
#[test]
fn errors_if_attempting_to_delete_a_directory_with_content_without_recursive_flag() {
Playground::setup("rm_test_6", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("some_empty_file.txt")]);
let actual = nu!(
cwd: dirs.root(),
"rm rm_test_6"
);
assert!(dirs.test().exists());
assert!(actual.err.contains("cannot remove non-empty directory"));
})
}
#[test]
fn errors_if_attempting_to_delete_home() {
Playground::setup("rm_test_8", |dirs, _| {
let actual = nu!(
cwd: dirs.root(),
"$env.HOME = 'myhome' ; rm -rf ~"
);
assert!(actual.err.contains("please use -I or -i"));
})
}
#[test]
fn errors_if_attempting_to_delete_single_dot_as_argument() {
Playground::setup("rm_test_7", |dirs, _| {
let actual = nu!(
cwd: dirs.root(),
"rm ."
);
assert!(actual.err.contains("cannot remove any parent directory"));
})
}
#[test]
fn errors_if_attempting_to_delete_two_dot_as_argument() {
Playground::setup("rm_test_8", |dirs, _| {
let actual = nu!(
cwd: dirs.root(),
"rm .."
);
assert!(actual.err.contains("cannot"));
})
}
#[test]
fn removes_multiple_directories() {
Playground::setup("rm_test_9", |dirs, sandbox| {
sandbox
.within("src")
.with_files(&[EmptyFile("a.rs"), EmptyFile("b.rs")])
.within("src/cli")
.with_files(&[EmptyFile("c.rs"), EmptyFile("d.rs")])
.within("test")
.with_files(&[EmptyFile("a_test.rs"), EmptyFile("b_test.rs")]);
nu!(
cwd: dirs.test(),
"rm src test --recursive"
);
assert_eq!(
Playground::glob_vec(&format!("{}/*", dirs.test().display())),
Vec::<std::path::PathBuf>::new()
);
})
}
#[test]
fn removes_multiple_files() {
Playground::setup("rm_test_10", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
]);
nu!(
cwd: dirs.test(),
"rm yehuda.txt jttxt andres.txt"
);
assert_eq!(
Playground::glob_vec(&format!("{}/*", dirs.test().display())),
Vec::<std::path::PathBuf>::new()
);
})
}
#[test]
fn removes_multiple_files_with_asterisks() {
Playground::setup("rm_test_11", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jt.txt"),
EmptyFile("andres.toml"),
]);
nu!(
cwd: dirs.test(),
"rm *.txt *.toml"
);
assert_eq!(
Playground::glob_vec(&format!("{}/*", dirs.test().display())),
Vec::<std::path::PathBuf>::new()
);
})
}
#[test]
fn allows_doubly_specified_file() {
Playground::setup("rm_test_12", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("yehuda.txt"), EmptyFile("jt.toml")]);
let actual = nu!(
cwd: dirs.test(),
"rm *.txt yehuda* *.toml"
);
assert_eq!(
Playground::glob_vec(&format!("{}/*", dirs.test().display())),
Vec::<std::path::PathBuf>::new()
);
assert!(!actual.out.contains("error"))
})
}
#[test]
fn remove_files_from_two_parents_up_using_multiple_dots_and_glob() {
Playground::setup("rm_test_13", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jt.txt"),
EmptyFile("kevin.txt"),
]);
sandbox.within("foo").mkdir("bar");
nu!(
cwd: dirs.test().join("foo/bar"),
"rm .../*.txt"
);
assert!(!files_exist_at(
&["yehuda.txt", "jttxt", "kevin.txt"],
dirs.test()
));
})
}
#[test]
fn no_errors_if_attempting_to_delete_non_existent_file_with_f_flag() {
Playground::setup("rm_test_14", |dirs, _| {
let actual = nu!(
cwd: dirs.root(),
"rm -f non_existent_file.txt"
);
assert!(!actual.err.contains("no valid path"));
})
}
#[test]
fn rm_wildcard_keeps_dotfiles() {
Playground::setup("rm_test_15", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("foo"), EmptyFile(".bar")]);
nu!(
cwd: dirs.test(),
r#"rm *"#
);
assert!(!files_exist_at(&["foo"], dirs.test()));
assert!(files_exist_at(&[".bar"], dirs.test()));
})
}
#[test]
fn rm_wildcard_leading_dot_deletes_dotfiles() {
Playground::setup("rm_test_16", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("foo"), EmptyFile(".bar")]);
nu!(
cwd: dirs.test(),
"rm .*"
);
assert!(files_exist_at(&["foo"], dirs.test()));
assert!(!files_exist_at(&[".bar"], dirs.test()));
})
}
#[test]
fn removes_files_with_case_sensitive_glob_matches_by_default() {
Playground::setup("glob_test", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("A0"), EmptyFile("a1")]);
nu!(
cwd: dirs.root(),
"rm glob_test/A*"
);
let deleted_path = dirs.test().join("A0");
let skipped_path = dirs.test().join("a1");
assert!(!deleted_path.exists());
assert!(skipped_path.exists());
})
}
#[test]
fn remove_ignores_ansi() {
Playground::setup("rm_test_ansi", |_dirs, sandbox| {
sandbox.with_files(&[EmptyFile("test.txt")]);
let actual = nu!(
cwd: sandbox.cwd(),
"ls | find test | get name | rm $in.0; ls | is-empty",
);
assert_eq!(actual.out, "true");
});
}
#[test]
fn removes_symlink() {
let symlink_target = "symlink_target";
let symlink = "symlink";
Playground::setup("rm_test_symlink", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile(symlink_target)]);
#[cfg(not(windows))]
std::os::unix::fs::symlink(dirs.test().join(symlink_target), dirs.test().join(symlink))
.unwrap();
#[cfg(windows)]
std::os::windows::fs::symlink_file(
dirs.test().join(symlink_target),
dirs.test().join(symlink),
)
.unwrap();
let _ = nu!(cwd: sandbox.cwd(), "rm symlink");
assert!(!dirs.test().join(symlink).exists());
});
}
#[test]
fn removes_symlink_pointing_to_directory() {
Playground::setup("rm_symlink_to_directory", |dirs, sandbox| {
sandbox.mkdir("test").symlink("test", "test_link");
nu!(cwd: sandbox.cwd(), "rm test_link");
assert!(!dirs.test().join("test_link").exists());
// The pointed directory should not be deleted.
assert!(dirs.test().join("test").exists());
});
}
#[test]
fn removes_file_after_cd() {
Playground::setup("rm_after_cd", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("delete.txt")]);
nu!(
cwd: dirs.root(),
"let file = 'delete.txt'; cd rm_after_cd; rm $file",
);
let path = dirs.test().join("delete.txt");
assert!(!path.exists());
})
}
#[cfg(not(windows))]
struct Cleanup<'a> {
dir_to_clean: &'a AbsolutePath,
}
#[cfg(not(windows))]
fn set_dir_read_only(directory: &AbsolutePath, read_only: bool) {
let mut permissions = fs::metadata(directory).unwrap().permissions();
permissions.set_readonly(read_only);
fs::set_permissions(directory, permissions).expect("failed to set directory permissions");
}
#[cfg(not(windows))]
impl Drop for Cleanup<'_> {
/// Restores write permissions to the given directory so that the Playground can be successfully
/// cleaned up.
fn drop(&mut self) {
set_dir_read_only(self.dir_to_clean, false);
}
}
#[test]
// This test is only about verifying file names are included in rm error messages. It is easier
// to only have this work on non-windows systems (i.e., unix-like) than to try to get the
// permissions to work on all platforms.
#[cfg(not(windows))]
fn rm_prints_filenames_on_error() {
Playground::setup("rm_prints_filenames_on_error", |dirs, sandbox| {
let file_names = vec!["test1.txt", "test2.txt"];
let with_files: Vec<_> = file_names
.iter()
.map(|file_name| EmptyFile(file_name))
.collect();
sandbox.with_files(&with_files);
let test_dir = dirs.test();
set_dir_read_only(test_dir, true);
let _cleanup = Cleanup {
dir_to_clean: test_dir,
};
// This rm is expected to fail, and stderr output indicating so is also expected.
let actual = nu!(cwd: test_dir, "rm test*.txt");
assert!(files_exist_at(&file_names, test_dir));
for file_name in file_names {
assert!(actual.err.contains("nu::shell::io::permission_denied"));
assert!(actual.err.contains(file_name));
}
});
}
#[test]
fn rm_files_inside_glob_metachars_dir() {
Playground::setup("rm_files_inside_glob_metachars_dir", |dirs, sandbox| {
let sub_dir = "test[]";
sandbox
.within(sub_dir)
.with_files(&[EmptyFile("test_file.txt")]);
let actual = nu!(
cwd: dirs.test().join(sub_dir),
"rm test_file.txt",
);
assert!(actual.err.is_empty());
assert!(!files_exist_at(
&["test_file.txt"],
dirs.test().join(sub_dir)
));
});
}
#[rstest]
#[case("a]c")]
#[case("a[c")]
#[case("a[bc]d")]
#[case("a][c")]
fn rm_files_with_glob_metachars(#[case] src_name: &str) {
Playground::setup("rm_files_with_glob_metachars", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile(src_name)]);
let src = dirs.test().join(src_name);
let actual = nu!(
cwd: dirs.test(),
format!(
"rm '{}'",
src.display(),
)
);
assert!(actual.err.is_empty());
assert!(!src.exists());
// test with variables
sandbox.with_files(&[EmptyFile(src_name)]);
let actual = nu!(
cwd: dirs.test(),
format!(
"let f = '{}'; rm $f",
src.display(),
)
);
assert!(actual.err.is_empty());
assert!(!src.exists());
});
}
#[cfg(not(windows))]
#[rstest]
#[case("a]?c")]
#[case("a*.?c")]
// windows doesn't allow filename with `*`.
fn rm_files_with_glob_metachars_nw(#[case] src_name: &str) {
rm_files_with_glob_metachars(src_name);
}
#[test]
fn force_rm_suppress_error() {
Playground::setup("force_rm_suppress_error", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("test_file.txt")]);
// the second rm should suppress error.
let actual = nu!(
cwd: dirs.test(),
"rm test_file.txt; rm -f test_file.txt",
);
assert!(actual.err.is_empty());
});
}
#[test]
fn rm_with_tilde() {
Playground::setup("rm_tilde", |dirs, sandbox| {
sandbox.within("~tilde").with_files(&[
EmptyFile("f1.txt"),
EmptyFile("f2.txt"),
EmptyFile("f3.txt"),
]);
let actual = nu!(cwd: dirs.test(), "rm '~tilde/f1.txt'");
assert!(actual.err.is_empty());
assert!(!files_exist_at(&["f1.txt"], dirs.test().join("~tilde")));
// pass variable
let actual = nu!(cwd: dirs.test(), "let f = '~tilde/f2.txt'; rm $f");
assert!(actual.err.is_empty());
assert!(!files_exist_at(&["f2.txt"], dirs.test().join("~tilde")));
// remove directory
let actual = nu!(cwd: dirs.test(), "let f = '~tilde'; rm -r $f");
assert!(actual.err.is_empty());
assert!(!files_exist_at(&["~tilde"], dirs.test()));
})
}
#[test]
#[cfg(windows)]
fn rm_already_in_use() {
Playground::setup("rm_already_in_use", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("i_will_be_used.txt")]);
let file_path = dirs.root().join("rm_already_in_use/i_will_be_used.txt");
let _file = OpenOptions::new()
.read(true)
.write(false)
.share_mode(0) // deny all sharing
.open(file_path)
.unwrap();
let outcome = nu!(
cwd: dirs.root(),
"rm rm_already_in_use/i_will_be_used.txt"
);
assert!(outcome.err.contains("nu::shell::io::already_in_use"));
assert!(!outcome.status.success())
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/ucp.rs | crates/nu-command/tests/commands/ucp.rs | use nu_test_support::fs::file_contents;
use nu_test_support::fs::{
Stub::{EmptyFile, FileWithContent, FileWithPermission},
files_exist_at,
};
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use rstest::rstest;
#[cfg(not(target_os = "windows"))]
const PATH_SEPARATOR: &str = "/";
#[cfg(target_os = "windows")]
const PATH_SEPARATOR: &str = "\\";
fn get_file_hash<T: std::fmt::Display>(file: T) -> String {
nu!(format!("open -r {file} | to text | hash md5")).out
}
#[test]
fn copies_a_file() {
copies_a_file_impl(false);
copies_a_file_impl(true);
}
fn copies_a_file_impl(progress: bool) {
Playground::setup("ucp_test_1", |dirs, _| {
let test_file = dirs.formats().join("sample.ini");
let progress_flag = if progress { "-p" } else { "" };
// Get the hash of the file content to check integrity after copy.
let first_hash = get_file_hash(test_file.display());
nu!(
cwd: dirs.root(),
format!(
"cp {progress_flag} `{}` ucp_test_1/sample.ini",
test_file.display()
)
);
assert!(dirs.test().join("sample.ini").exists());
// Get the hash of the copied file content to check against first_hash.
let after_cp_hash = get_file_hash(dirs.test().join("sample.ini").display());
assert_eq!(first_hash, after_cp_hash);
});
}
#[test]
fn copies_the_file_inside_directory_if_path_to_copy_is_directory() {
copies_the_file_inside_directory_if_path_to_copy_is_directory_impl(false);
copies_the_file_inside_directory_if_path_to_copy_is_directory_impl(true);
}
fn copies_the_file_inside_directory_if_path_to_copy_is_directory_impl(progress: bool) {
Playground::setup("ucp_test_2", |dirs, _| {
let expected_file = dirs.test().join("sample.ini");
let progress_flag = if progress { "-p" } else { "" };
// Get the hash of the file content to check integrity after copy.
let first_hash = get_file_hash(dirs.formats().join("../formats/sample.ini").display());
nu!(
cwd: dirs.formats(),
format!(
"cp {progress_flag} ../formats/sample.ini {}",
expected_file.parent().unwrap().as_os_str().to_str().unwrap(),
)
);
assert!(dirs.test().join("sample.ini").exists());
// Check the integrity of the file.
let after_cp_hash = get_file_hash(expected_file.display());
assert_eq!(first_hash, after_cp_hash);
})
}
// error msg changes on coreutils
#[test]
fn error_if_attempting_to_copy_a_directory_to_another_directory() {
error_if_attempting_to_copy_a_directory_to_another_directory_impl(false);
error_if_attempting_to_copy_a_directory_to_another_directory_impl(true);
}
fn error_if_attempting_to_copy_a_directory_to_another_directory_impl(progress: bool) {
Playground::setup("ucp_test_3", |dirs, _| {
let progress_flag = if progress { "-p" } else { "" };
let actual = nu!(
cwd: dirs.formats(),
format!(
"cp {progress_flag} ../formats {}",
dirs.test().display()
)
);
assert!(actual.err.contains("formats"));
assert!(actual.err.contains("resolves to a directory (not copied)"));
});
}
#[test]
fn copies_the_directory_inside_directory_if_path_to_copy_is_directory_and_with_recursive_flag() {
copies_the_directory_inside_directory_if_path_to_copy_is_directory_and_with_recursive_flag_impl(
false,
);
copies_the_directory_inside_directory_if_path_to_copy_is_directory_and_with_recursive_flag_impl(
true,
);
}
fn copies_the_directory_inside_directory_if_path_to_copy_is_directory_and_with_recursive_flag_impl(
progress: bool,
) {
Playground::setup("ucp_test_4", |dirs, sandbox| {
sandbox
.within("originals")
.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
])
.mkdir("expected");
let expected_dir = dirs.test().join("expected").join("originals");
let progress_flag = if progress { "-p" } else { "" };
nu!(
cwd: dirs.test(),
format!("cp {progress_flag} originals expected -r")
);
assert!(expected_dir.exists());
assert!(files_exist_at(
&["yehuda.txt", "jttxt", "andres.txt"],
&expected_dir
));
})
}
#[test]
fn deep_copies_with_recursive_flag() {
deep_copies_with_recursive_flag_impl(false);
deep_copies_with_recursive_flag_impl(true);
}
fn deep_copies_with_recursive_flag_impl(progress: bool) {
Playground::setup("ucp_test_5", |dirs, sandbox| {
sandbox
.within("originals")
.with_files(&[EmptyFile("manifest.txt")])
.within("originals/contributors")
.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
])
.within("originals/contributors/JT")
.with_files(&[EmptyFile("errors.txt"), EmptyFile("multishells.txt")])
.within("originals/contributors/andres")
.with_files(&[EmptyFile("coverage.txt"), EmptyFile("commands.txt")])
.within("originals/contributors/yehuda")
.with_files(&[EmptyFile("defer-evaluation.txt")])
.mkdir("expected");
let expected_dir = dirs.test().join("expected").join("originals");
let progress_flag = if progress { "-p" } else { "" };
let jts_expected_copied_dir = expected_dir.join("contributors").join("JT");
let andres_expected_copied_dir = expected_dir.join("contributors").join("andres");
let yehudas_expected_copied_dir = expected_dir.join("contributors").join("yehuda");
nu!(
cwd: dirs.test(),
format!("cp {progress_flag} originals expected --recursive"),
);
assert!(expected_dir.exists());
assert!(files_exist_at(
&["errors.txt", "multishells.txt"],
jts_expected_copied_dir
));
assert!(files_exist_at(
&["coverage.txt", "commands.txt"],
andres_expected_copied_dir
));
assert!(files_exist_at(
&["defer-evaluation.txt"],
yehudas_expected_copied_dir
));
})
}
#[test]
fn copies_using_path_with_wildcard() {
copies_using_path_with_wildcard_impl(false);
copies_using_path_with_wildcard_impl(true);
}
fn copies_using_path_with_wildcard_impl(progress: bool) {
Playground::setup("ucp_test_6", |dirs, _| {
let progress_flag = if progress { "-p" } else { "" };
// Get the hash of the file content to check integrity after copy.
let src_hashes = nu!(
cwd: dirs.formats(),
"for file in (ls ../formats/*) { open --raw $file.name | to text | hash md5 }"
)
.out;
nu!(
cwd: dirs.formats(),
format!(
"cp {progress_flag} -r ../formats/* {}",
dirs.test().display()
)
);
assert!(files_exist_at(
&[
"caco3_plastics.csv",
"cargo_sample.toml",
"jt.xml",
"sample.ini",
"sgml_description.json",
"utf16.ini",
],
dirs.test()
));
// Check integrity after the copy is done
let dst_hashes = nu!(
cwd: dirs.formats(),
format!(
r#"
for file in (ls {}) {{
open --raw $file.name
| to text
| hash md5
}}
"#,
dirs.test().display()
)
)
.out;
assert_eq!(src_hashes, dst_hashes);
})
}
#[test]
fn copies_using_a_glob() {
copies_using_a_glob_impl(false);
copies_using_a_glob_impl(true);
}
fn copies_using_a_glob_impl(progress: bool) {
Playground::setup("ucp_test_7", |dirs, _| {
let progress_flag = if progress { "-p" } else { "" };
// Get the hash of the file content to check integrity after copy.
let src_hashes = nu!(
cwd: dirs.formats(),
"for file in (ls *) { open --raw $file.name | to text | hash md5 }"
)
.out;
nu!(
cwd: dirs.formats(),
format!(
"cp {progress_flag} -r * {}",
dirs.test().display()
)
);
assert!(files_exist_at(
&[
"caco3_plastics.csv",
"cargo_sample.toml",
"jt.xml",
"sample.ini",
"sgml_description.json",
"utf16.ini",
],
dirs.test()
));
// Check integrity after the copy is done
let dst_hashes = nu!(
cwd: dirs.formats(),
format!(
r#"
for file in (ls {}) {{
open --raw $file.name
| to text
| hash md5
}}
"#,
dirs.test().display()
)
)
.out;
assert_eq!(src_hashes, dst_hashes);
});
}
#[test]
fn copies_same_file_twice() {
copies_same_file_twice_impl(false);
copies_same_file_twice_impl(true);
}
fn copies_same_file_twice_impl(progress: bool) {
Playground::setup("ucp_test_8", |dirs, _| {
let progress_flag = if progress { "-p" } else { "" };
nu!(
cwd: dirs.root(),
format!(
"cp {progress_flag} `{}` ucp_test_8/sample.ini",
dirs.formats().join("sample.ini").display()
)
);
nu!(
cwd: dirs.root(),
format!(
"cp {progress_flag} `{}` ucp_test_8/sample.ini",
dirs.formats().join("sample.ini").display()
)
);
assert!(dirs.test().join("sample.ini").exists());
});
}
#[test]
#[ignore = "Behavior not supported by uutils cp"]
fn copy_files_using_glob_two_parents_up_using_multiple_dots() {
copy_files_using_glob_two_parents_up_using_multiple_dots_imp(false);
copy_files_using_glob_two_parents_up_using_multiple_dots_imp(true);
}
fn copy_files_using_glob_two_parents_up_using_multiple_dots_imp(progress: bool) {
Playground::setup("ucp_test_9", |dirs, sandbox| {
sandbox.within("foo").within("bar").with_files(&[
EmptyFile("jtjson"),
EmptyFile("andres.xml"),
EmptyFile("yehuda.yaml"),
EmptyFile("kevin.txt"),
EmptyFile("many_more.ppl"),
]);
let progress_flag = if progress { "-p" } else { "" };
nu!(
cwd: dirs.test().join("foo/bar"),
format!("cp {progress_flag} * ...")
);
assert!(files_exist_at(
&[
"yehuda.yaml",
"jtjson",
"andres.xml",
"kevin.txt",
"many_more.ppl",
],
dirs.test()
));
})
}
#[test]
fn copy_file_and_dir_from_two_parents_up_using_multiple_dots_to_current_dir_recursive() {
copy_file_and_dir_from_two_parents_up_using_multiple_dots_to_current_dir_recursive_impl(false);
copy_file_and_dir_from_two_parents_up_using_multiple_dots_to_current_dir_recursive_impl(true);
}
fn copy_file_and_dir_from_two_parents_up_using_multiple_dots_to_current_dir_recursive_impl(
progress: bool,
) {
Playground::setup("ucp_test_10", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("hello_there")]);
sandbox.mkdir("hello_again");
sandbox.within("foo").mkdir("bar");
let progress_flag = if progress { "-p" } else { "" };
nu!(
cwd: dirs.test().join("foo/bar"),
format!("cp {progress_flag} -r .../hello* .")
);
let expected = dirs.test().join("foo/bar");
assert!(files_exist_at(&["hello_there", "hello_again"], expected));
})
}
// error msg changes on coreutils
#[test]
fn copy_to_non_existing_dir() {
copy_to_non_existing_dir_impl(false);
copy_to_non_existing_dir_impl(true);
}
fn copy_to_non_existing_dir_impl(progress: bool) {
Playground::setup("ucp_test_11", |_dirs, sandbox| {
sandbox.with_files(&[EmptyFile("empty_file")]);
let progress_flag = if progress { "-p" } else { "" };
let actual = nu!(
cwd: sandbox.cwd(),
format!("cp {progress_flag} empty_file ~/not_a_dir{PATH_SEPARATOR}")
);
assert!(actual.err.contains("is not a directory"));
});
}
#[test]
fn copy_dir_contains_symlink_ignored() {
copy_dir_contains_symlink_ignored_impl(false);
copy_dir_contains_symlink_ignored_impl(true);
}
fn copy_dir_contains_symlink_ignored_impl(progress: bool) {
Playground::setup("ucp_test_12", |_dirs, sandbox| {
sandbox
.within("tmp_dir")
.with_files(&[EmptyFile("hello_there"), EmptyFile("good_bye")])
.within("tmp_dir")
.symlink("good_bye", "dangle_symlink");
let progress_flag = if progress { "-p" } else { "" };
// make symbolic link and copy.
nu!(
cwd: sandbox.cwd(),
format!("rm {progress_flag} tmp_dir/good_bye; cp -r tmp_dir tmp_dir_2")
);
// check hello_there exists inside `tmp_dir_2`, and `dangle_symlink` don't exists inside `tmp_dir_2`.
let expected = sandbox.cwd().join("tmp_dir_2");
assert!(files_exist_at(&["hello_there"], expected));
// GNU cp will copy the broken symlink, so following their behavior
// thus commenting out below
// let path = expected.join("dangle_symlink");
// assert!(!path.exists() && !path.is_symlink());
});
}
#[test]
fn copy_dir_contains_symlink() {
copy_dir_contains_symlink_impl(false);
copy_dir_contains_symlink_impl(true);
}
fn copy_dir_contains_symlink_impl(progress: bool) {
Playground::setup("ucp_test_13", |_dirs, sandbox| {
sandbox
.within("tmp_dir")
.with_files(&[EmptyFile("hello_there"), EmptyFile("good_bye")])
.within("tmp_dir")
.symlink("good_bye", "dangle_symlink");
let progress_flag = if progress { "-p" } else { "" };
// make symbolic link and copy.
nu!(
cwd: sandbox.cwd(),
format!("rm tmp_dir/good_bye; cp {progress_flag} -r -n tmp_dir tmp_dir_2")
);
// check hello_there exists inside `tmp_dir_2`, and `dangle_symlink` also exists inside `tmp_dir_2`.
let expected = sandbox.cwd().join("tmp_dir_2");
assert!(files_exist_at(&["hello_there"], expected.clone()));
let path = expected.join("dangle_symlink");
assert!(path.is_symlink());
});
}
#[test]
fn copy_dir_symlink_file_body_not_changed() {
copy_dir_symlink_file_body_not_changed_impl(false);
copy_dir_symlink_file_body_not_changed_impl(true);
}
fn copy_dir_symlink_file_body_not_changed_impl(progress: bool) {
Playground::setup("ucp_test_14", |_dirs, sandbox| {
sandbox
.within("tmp_dir")
.with_files(&[EmptyFile("hello_there"), EmptyFile("good_bye")])
.within("tmp_dir")
.symlink("good_bye", "dangle_symlink");
let progress_flag = if progress { "-p" } else { "" };
// make symbolic link and copy.
nu!(
cwd: sandbox.cwd(),
format!(r#"
rm tmp_dir/good_bye
cp {progress_flag} -r -n tmp_dir tmp_dir_2
rm -r tmp_dir
cp {progress_flag} -r -n tmp_dir_2 tmp_dir
echo hello_data | save tmp_dir/good_bye
"#),
);
// check dangle_symlink in tmp_dir is no longer dangling.
let expected_file = sandbox.cwd().join("tmp_dir").join("dangle_symlink");
let actual = file_contents(expected_file);
assert!(actual.contains("hello_data"));
});
}
// error msg changes on coreutils
#[test]
fn copy_identical_file() {
copy_identical_file_impl(false);
copy_identical_file_impl(true);
}
fn copy_identical_file_impl(progress: bool) {
Playground::setup("ucp_test_15", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("same.txt")]);
let progress_flag = if progress { "-p" } else { "" };
let actual = nu!(
cwd: dirs.test(),
format!("cp {progress_flag} same.txt same.txt"),
);
let msg = format!(
"'{}' and '{}' are the same file",
dirs.test().join("same.txt").display(),
dirs.test().join("same.txt").display(),
);
// debug messages in CI
if !actual.err.contains(&msg) {
panic!("stderr was: {}", actual.err);
}
});
}
#[test]
#[ignore = "File name in progress bar not on uutils impl"]
fn copy_ignores_ansi() {
copy_ignores_ansi_impl(false);
copy_ignores_ansi_impl(true);
}
fn copy_ignores_ansi_impl(progress: bool) {
Playground::setup("ucp_test_16", |_dirs, sandbox| {
sandbox.with_files(&[EmptyFile("test.txt")]);
let progress_flag = if progress { "-p" } else { "" };
let actual = nu!(
cwd: sandbox.cwd(),
format!("ls | find test | get name | cp {progress_flag} $in.0 success.txt; ls | find success | get name | ansi strip | get 0"),
);
assert_eq!(actual.out, "success.txt");
});
}
//apparently on windows error msg is different, but linux(where i test) is fine.
//fix later FIXME
#[cfg(unix)]
#[test]
fn copy_file_not_exists_dst() {
copy_file_not_exists_dst_impl(false);
copy_file_not_exists_dst_impl(true);
}
#[cfg(unix)]
fn copy_file_not_exists_dst_impl(progress: bool) {
Playground::setup("ucp_test_17", |_dirs, sandbox| {
sandbox.with_files(&[EmptyFile("valid.txt")]);
let progress_flag = if progress { "-p" } else { "" };
let actual = nu!(
cwd: sandbox.cwd(),
format!("cp {progress_flag} valid.txt ~/invalid_dir/invalid_dir1"),
);
assert!(
actual.err.contains("invalid_dir1") && actual.err.contains("No such file or directory")
);
});
}
//again slightly different error message on windows on tests
// compared to linux
#[test]
#[ignore] //FIXME: This test needs to be re-enabled once uu_cp has fixed the bug
fn copy_file_with_read_permission() {
copy_file_with_read_permission_impl(false);
copy_file_with_read_permission_impl(true);
}
fn copy_file_with_read_permission_impl(progress: bool) {
Playground::setup("ucp_test_18", |_dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("valid.txt"),
FileWithPermission("invalid_prem.txt", false),
]);
let progress_flag = if progress { "-p" } else { "" };
let actual = nu!(
cwd: sandbox.cwd(),
format!("cp {progress_flag} valid.txt invalid_prem.txt"),
);
assert!(actual.err.contains("invalid_prem.txt") && actual.err.contains("denied"));
});
}
// uutils/coreutils copy tests
static TEST_EXISTING_FILE: &str = "existing_file.txt";
static TEST_HELLO_WORLD_SOURCE: &str = "hello_world.txt";
static TEST_HELLO_WORLD_DEST: &str = "copy_of_hello_world.txt";
static TEST_HOW_ARE_YOU_SOURCE: &str = "how_are_you.txt";
static TEST_HOW_ARE_YOU_DEST: &str = "hello_dir/how_are_you.txt";
static TEST_COPY_TO_FOLDER: &str = "hello_dir/";
static TEST_COPY_TO_FOLDER_FILE: &str = "hello_dir/hello_world.txt";
static TEST_COPY_FROM_FOLDER: &str = "hello_dir_with_file/";
static TEST_COPY_FROM_FOLDER_FILE: &str = "hello_dir_with_file/hello_world.txt";
static TEST_COPY_TO_FOLDER_NEW: &str = "hello_dir_new";
static TEST_COPY_TO_FOLDER_NEW_FILE: &str = "hello_dir_new/hello_world.txt";
#[test]
fn test_cp_cp() {
Playground::setup("ucp_test_19", |dirs, _| {
let src = dirs.fixtures.join("cp").join(TEST_HELLO_WORLD_SOURCE);
// Get the hash of the file content to check integrity after copy.
let src_hash = get_file_hash(src.display());
nu!(
cwd: dirs.root(),
format!(
"cp {} ucp_test_19/{TEST_HELLO_WORLD_DEST}",
src.display(),
)
);
assert!(dirs.test().join(TEST_HELLO_WORLD_DEST).exists());
// Get the hash of the copied file content to check against first_hash.
let after_cp_hash = get_file_hash(dirs.test().join(TEST_HELLO_WORLD_DEST).display());
assert_eq!(src_hash, after_cp_hash);
});
}
#[test]
fn test_cp_existing_target() {
Playground::setup("ucp_test_20", |dirs, _| {
let src = dirs.fixtures.join("cp").join(TEST_HELLO_WORLD_SOURCE);
let existing = dirs.fixtures.join("cp").join(TEST_EXISTING_FILE);
// Get the hash of the file content to check integrity after copy.
let src_hash = get_file_hash(src.display());
// Copy existing file to destination, so that it exists for the test
nu!(
cwd: dirs.root(),
format!(
"cp {} ucp_test_20/{TEST_EXISTING_FILE}",
existing.display(),
)
);
// At this point the src and existing files should be different
assert!(dirs.test().join(TEST_EXISTING_FILE).exists());
// Now for the test
nu!(
cwd: dirs.root(),
format!(
"cp {} ucp_test_20/{TEST_EXISTING_FILE}",
src.display(),
)
);
assert!(dirs.test().join(TEST_EXISTING_FILE).exists());
// Get the hash of the copied file content to check against first_hash.
let after_cp_hash = get_file_hash(dirs.test().join(TEST_EXISTING_FILE).display());
assert_eq!(src_hash, after_cp_hash);
});
}
#[test]
fn test_cp_multiple_files() {
Playground::setup("ucp_test_21", |dirs, sandbox| {
let src1 = dirs.fixtures.join("cp").join(TEST_HELLO_WORLD_SOURCE);
let src2 = dirs.fixtures.join("cp").join(TEST_HOW_ARE_YOU_SOURCE);
// Get the hash of the file content to check integrity after copy.
let src1_hash = get_file_hash(src1.display());
let src2_hash = get_file_hash(src2.display());
//Create target directory
sandbox.mkdir(TEST_COPY_TO_FOLDER);
// Start test
nu!(
cwd: dirs.root(),
format!(
"cp {} {} ucp_test_21/{TEST_COPY_TO_FOLDER}",
src1.display(),
src2.display(),
)
);
assert!(dirs.test().join(TEST_COPY_TO_FOLDER).exists());
// Get the hash of the copied file content to check against first_hash.
let after_cp_1_hash = get_file_hash(dirs.test().join(TEST_COPY_TO_FOLDER_FILE).display());
let after_cp_2_hash = get_file_hash(dirs.test().join(TEST_HOW_ARE_YOU_DEST).display());
assert_eq!(src1_hash, after_cp_1_hash);
assert_eq!(src2_hash, after_cp_2_hash);
});
}
#[test]
fn test_cp_recurse() {
Playground::setup("ucp_test_22", |dirs, sandbox| {
// Create the relevant target directories
sandbox.mkdir(TEST_COPY_FROM_FOLDER);
sandbox.mkdir(TEST_COPY_TO_FOLDER_NEW);
let src = dirs
.fixtures
.join("cp")
.join(TEST_COPY_FROM_FOLDER)
.join(TEST_COPY_FROM_FOLDER_FILE);
let src_hash = get_file_hash(src.display());
// Start test
nu!(
cwd: dirs.root(),
format!("cp -r {TEST_COPY_FROM_FOLDER} ucp_test_22/{TEST_COPY_TO_FOLDER_NEW}"),
);
let after_cp_hash = get_file_hash(dirs.test().join(TEST_COPY_TO_FOLDER_NEW_FILE).display());
assert_eq!(src_hash, after_cp_hash);
});
}
#[test]
fn test_cp_with_dirs() {
Playground::setup("ucp_test_23", |dirs, sandbox| {
let src = dirs.fixtures.join("cp").join(TEST_HELLO_WORLD_SOURCE);
let src_hash = get_file_hash(src.display());
//Create target directory
sandbox.mkdir(TEST_COPY_TO_FOLDER);
// Start test
nu!(
cwd: dirs.root(),
format!(
"cp {} ucp_test_23/{TEST_COPY_TO_FOLDER}",
src.display(),
)
);
let after_cp_hash = get_file_hash(dirs.test().join(TEST_COPY_TO_FOLDER_FILE).display());
assert_eq!(src_hash, after_cp_hash);
// Other way around
sandbox.mkdir(TEST_COPY_FROM_FOLDER);
let src2 = dirs.fixtures.join("cp").join(TEST_COPY_FROM_FOLDER_FILE);
let src2_hash = get_file_hash(src2.display());
nu!(
cwd: dirs.root(),
format!(
"cp {} ucp_test_23/{TEST_HELLO_WORLD_DEST}",
src2.display(),
)
);
let after_cp_2_hash = get_file_hash(dirs.test().join(TEST_HELLO_WORLD_DEST).display());
assert_eq!(src2_hash, after_cp_2_hash);
});
}
#[cfg(not(windows))]
#[test]
fn test_cp_arg_force() {
Playground::setup("ucp_test_24", |dirs, sandbox| {
let src = dirs.fixtures.join("cp").join(TEST_HELLO_WORLD_SOURCE);
let src_hash = get_file_hash(src.display());
sandbox.with_files(&[FileWithPermission("invalid_prem.txt", false)]);
nu!(
cwd: dirs.root(),
format!(
"cp {} --force ucp_test_24/{}",
src.display(),
"invalid_prem.txt"
)
);
let after_cp_hash = get_file_hash(dirs.test().join("invalid_prem.txt").display());
// Check content was copied by the use of --force
assert_eq!(src_hash, after_cp_hash);
});
}
#[test]
fn test_cp_directory_to_itself_disallowed() {
Playground::setup("ucp_test_25", |dirs, sandbox| {
sandbox.mkdir("d");
let actual = nu!(
cwd: dirs.root(),
format!(
"cp -r ucp_test_25/{} ucp_test_25/{}",
"d",
"d"
)
);
actual
.err
.contains("cannot copy a directory, 'd', into itself, 'd/d'");
});
}
#[test]
fn test_cp_nested_directory_to_itself_disallowed() {
Playground::setup("ucp_test_26", |dirs, sandbox| {
sandbox.mkdir("a");
sandbox.mkdir("a/b");
sandbox.mkdir("a/b/c");
let actual = nu!(
cwd: dirs.test(),
format!(
"cp -r {} {}",
"a/b",
"a/b/c"
)
);
actual
.err
.contains("cannot copy a directory, 'a/b', into itself, 'a/b/c/b'");
});
}
#[cfg(not(windows))]
#[test]
fn test_cp_same_file_force() {
Playground::setup("ucp_test_27", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("f")]);
let actual = nu!(
cwd: dirs.test(),
format!(
"cp --force {} {}",
"f",
"f"
)
);
actual.err.contains("cp: 'f' and 'f' are the same file");
assert!(!dirs.test().join("f~").exists());
});
}
#[test]
fn test_cp_arg_no_clobber() {
Playground::setup("ucp_test_28", |dirs, _| {
let src = dirs.fixtures.join("cp").join(TEST_HELLO_WORLD_SOURCE);
let target = dirs.fixtures.join("cp").join(TEST_HOW_ARE_YOU_SOURCE);
let target_hash = get_file_hash(target.display());
let _ = nu!(
cwd: dirs.root(),
format!(
"cp {} {} --no-clobber",
src.display(),
target.display()
)
);
let after_cp_hash = get_file_hash(target.display());
// Check content was not clobbered
assert_eq!(after_cp_hash, target_hash);
});
}
#[test]
fn test_cp_arg_no_clobber_twice() {
Playground::setup("ucp_test_29", |dirs, sandbox| {
sandbox.with_files(&[
FileWithContent("source.txt", "fake data"),
FileWithContent("source_with_body.txt", "some-body"),
]);
nu!(
cwd: dirs.root(),
format!(
"cp --no-clobber ucp_test_29/{} ucp_test_29/{}",
"source.txt",
"dest.txt"
)
);
assert!(dirs.test().join("dest.txt").exists());
nu!(
cwd: dirs.root(),
format!(
"cp --no-clobber ucp_test_29/{} ucp_test_29/{}",
"source_with_body.txt",
"dest.txt"
)
);
// Should have same contents of original empty file as --no-clobber should not overwrite dest.txt
assert_eq!(file_contents(dirs.test().join("dest.txt")), "fake data");
});
}
#[test]
fn test_cp_debug_default() {
Playground::setup("ucp_test_30", |dirs, _| {
let src = dirs.fixtures.join("cp").join(TEST_HELLO_WORLD_SOURCE);
let actual = nu!(
cwd: dirs.root(),
format!(
"cp --debug {} ucp_test_30/{TEST_HELLO_WORLD_DEST}",
src.display(),
)
);
#[cfg(target_os = "macos")]
if !actual
.out
.contains("copy offload: unknown, reflink: unsupported, sparse detection: unsupported")
{
panic!("{}", format!("Failure: stdout was \n{}", actual.out));
}
#[cfg(target_os = "linux")]
if !actual
.out
.contains("copy offload: yes, reflink: unsupported, sparse detection: no")
{
panic!("{}", format!("Failure: stdout was \n{}", actual.out));
}
#[cfg(target_os = "freebsd")]
if !actual.out.contains(
"copy offload: unsupported, reflink: unsupported, sparse detection: unsupported",
) {
panic!("{}", format!("Failure: stdout was \n{}", actual.out));
}
#[cfg(windows)]
if !actual.out.contains(
"copy offload: unsupported, reflink: unsupported, sparse detection: unsupported",
) {
panic!("{}", format!("Failure: stdout was \n{}", actual.out));
}
// assert!(actual.out.contains("cp-debug-copy-offload"));
});
}
#[test]
fn test_cp_verbose_default() {
Playground::setup("ucp_test_31", |dirs, _| {
let src = dirs.fixtures.join("cp").join(TEST_HELLO_WORLD_SOURCE);
let actual = nu!(
cwd: dirs.root(),
format!(
"cp --verbose {} {TEST_HELLO_WORLD_DEST}",
src.display(),
)
);
assert!(
actual.out.contains(
format!(
"'{}' -> '{}'",
src.display(),
dirs.root().join(TEST_HELLO_WORLD_DEST).display()
)
.as_str(),
)
);
});
}
#[test]
fn test_cp_only_source_no_dest() {
Playground::setup("ucp_test_32", |dirs, _| {
let src = dirs.fixtures.join("cp").join(TEST_HELLO_WORLD_SOURCE);
let actual = nu!(
cwd: dirs.root(),
format!(
"cp {}",
src.display(),
)
);
assert!(
actual
.err
.contains("Missing destination path operand after")
);
assert!(actual.err.contains(TEST_HELLO_WORLD_SOURCE));
});
}
#[test]
fn test_cp_with_vars() {
Playground::setup("ucp_test_33", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("input")]);
nu!(
cwd: dirs.test(),
"let src = 'input'; let dst = 'target'; cp $src $dst",
);
assert!(dirs.test().join("target").exists());
});
}
#[test]
fn test_cp_destination_after_cd() {
Playground::setup("ucp_test_34", |dirs, sandbox| {
sandbox.mkdir("test");
sandbox.with_files(&[EmptyFile("test/file.txt")]);
nu!(
cwd: dirs.test(),
// Defining variable avoid path expansion of cp argument.
// If argument was not expanded ucp wrapper should do it
"cd test; let file = 'copy.txt'; cp file.txt $file",
);
assert!(dirs.test().join("test").join("copy.txt").exists());
});
}
#[rstest]
#[case("a]c")]
#[case("a[c")]
#[case("a[bc]d")]
#[case("a][c")]
fn copies_files_with_glob_metachars(#[case] src_name: &str) {
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/sort.rs | crates/nu-command/tests/commands/sort.rs | use nu_test_support::nu;
#[test]
fn by_invalid_types() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml --raw
| echo ["foo" 1]
| sort
| to json -r
"#);
let json_output = r#"[1,"foo"]"#;
assert_eq!(actual.out, json_output);
}
#[test]
fn sort_primitive_values() {
let actual = nu!(cwd: "tests/fixtures/formats", "
open cargo_sample.toml --raw
| lines
| skip 1
| first 6
| sort
| first
");
assert_eq!(actual.out, "authors = [\"The Nushell Project Developers\"]");
}
#[test]
fn sort_table() {
// if a table's records are compared directly rather than holistically as a table,
// [100, 10, 5] will come before [100, 5, 8] because record comparison
// compares columns by alphabetical order, so price will be checked before quantity
let actual =
nu!("[[id, quantity, price]; [100, 10, 5], [100, 5, 8], [100, 5, 1]] | sort | to nuon");
assert_eq!(
actual.out,
r#"[[id, quantity, price]; [100, 5, 1], [100, 5, 8], [100, 10, 5]]"#
);
}
#[test]
fn sort_different_types() {
let actual = nu!("[a, 1, b, 2, c, 3, [4, 5, 6], d, 4, [1, 2, 3]] | sort | to json --raw");
let json_output = r#"[1,2,3,4,"a","b","c","d",[1,2,3],[4,5,6]]"#;
assert_eq!(actual.out, json_output);
}
#[test]
fn sort_natural() {
let actual = nu!("['1' '2' '3' '4' '5' '10' '100'] | sort -n | to nuon");
assert_eq!(actual.out, r#"["1", "2", "3", "4", "5", "10", "100"]"#);
}
#[test]
fn sort_record_natural() {
let actual = nu!("{10:0,99:0,1:0,9:0,100:0} | sort -n | to nuon");
assert_eq!(
actual.out,
r#"{"1": 0, "9": 0, "10": 0, "99": 0, "100": 0}"#
);
}
#[test]
fn sort_record_insensitive() {
let actual = nu!("{abe:1,zed:2,ABE:3} | sort -i | to nuon");
assert_eq!(actual.out, r#"{abe: 1, ABE: 3, zed: 2}"#);
}
#[test]
fn sort_record_insensitive_reverse() {
let actual = nu!("{abe:1,zed:2,ABE:3} | sort -ir | to nuon");
assert_eq!(actual.out, r#"{zed: 2, ABE: 3, abe: 1}"#);
}
#[test]
fn sort_record_values_natural() {
let actual = nu!(r#"{1:"1",2:"2",4:"100",3:"10"} | sort -vn | to nuon"#);
assert_eq!(actual.out, r#"{"1": "1", "2": "2", "3": "10", "4": "100"}"#);
}
#[test]
fn sort_record_values_insensitive() {
let actual = nu!("{1:abe,2:zed,3:ABE} | sort -vi | to nuon");
assert_eq!(actual.out, r#"{"1": abe, "3": ABE, "2": zed}"#);
}
#[test]
fn sort_record_values_insensitive_reverse() {
let actual = nu!("{1:abe,2:zed,3:ABE} | sort -vir | to nuon");
assert_eq!(actual.out, r#"{"2": zed, "3": ABE, "1": abe}"#);
}
#[test]
fn sort_empty() {
let actual = nu!("[] | sort | to nuon");
assert_eq!(actual.out, "[]");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/rename.rs | crates/nu-command/tests/commands/rename.rs | use nu_test_support::nu;
#[test]
fn changes_the_column_name() {
let sample = r#"[
["Andrés N. Robalino"],
["JT Turner"],
["Yehuda Katz"],
["Jason Gedge"]
]"#;
let actual = nu!(format!(
"
{sample}
| wrap name
| rename mosqueteros
| get mosqueteros
| length
"
));
assert_eq!(actual.out, "4");
}
#[test]
fn keeps_remaining_original_names_given_less_new_names_than_total_original_names() {
let sample = r#"[
["Andrés N. Robalino"],
["JT Turner"],
["Yehuda Katz"],
["Jason Gedge"]
]"#;
let actual = nu!(format!(
r#"
{sample}
| wrap name
| default "arepa!" hit
| rename mosqueteros
| get hit
| length
"#
));
assert_eq!(actual.out, "4");
}
#[test]
fn errors_if_no_columns_present() {
let sample = r#"[
["Andrés N. Robalino"],
["JT Turner"],
["Yehuda Katz"],
["Jason Gedge"]
]"#;
let actual = nu!(format!("{sample} | rename mosqueteros"));
assert!(actual.err.contains("command doesn't support"));
}
#[test]
fn errors_if_columns_param_is_empty() {
let sample = r#"[
["Andrés N. Robalino"],
["JT Turner"],
["Yehuda Katz"],
["Jason Gedge"]
]"#;
let actual = nu!(format!(
r#"
{sample}
| wrap name
| default "arepa!" hit
| rename --column {{}}
"#
));
assert!(actual.err.contains("The column info cannot be empty"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/with_env.rs | crates/nu-command/tests/commands/with_env.rs | use nu_test_support::nu;
#[test]
fn with_env_extends_environment() {
let actual = nu!("with-env { FOO: BARRRR } {echo $env} | get FOO");
assert_eq!(actual.out, "BARRRR");
}
#[test]
fn with_env_shorthand() {
let actual = nu!("FOO=BARRRR echo $env | get FOO");
assert_eq!(actual.out, "BARRRR");
}
#[test]
fn shorthand_doesnt_reorder_arguments() {
let actual = nu!("FOO=BARRRR nu --testbin cococo first second");
assert_eq!(actual.out, "first second");
}
#[test]
fn with_env_shorthand_trims_quotes() {
let actual = nu!("FOO='BARRRR' echo $env | get FOO");
assert_eq!(actual.out, "BARRRR");
}
#[test]
fn with_env_and_shorthand_same_result() {
let actual_shorthand = nu!("FOO='BARRRR' echo $env | get FOO");
let actual_normal = nu!("with-env { FOO: BARRRR } {echo $env} | get FOO");
assert_eq!(actual_shorthand.out, actual_normal.out);
}
#[test]
fn test_redirection2() {
let actual =
nu!("let x = (FOO=BAR nu --testbin cococo niceenvvar); $x | str trim | str length");
assert_eq!(actual.out, "10");
}
#[test]
fn with_env_hides_variables_in_parent_scope() {
let actual = nu!(r#"
$env.FOO = "1"
print $env.FOO
with-env { FOO: null } {
echo $env.FOO
}
print $env.FOO
"#);
assert_eq!(actual.out, "11");
}
#[test]
fn with_env_shorthand_can_not_hide_variables() {
let actual = nu!(r#"
$env.FOO = "1"
print $env.FOO
FOO=null print $env.FOO
print $env.FOO
"#);
assert_eq!(actual.out, "1null1");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/empty.rs | crates/nu-command/tests/commands/empty.rs | use nu_test_support::nu;
#[test]
fn reports_emptiness() {
let actual = nu!(r#"
[[] '' {} null]
| all {||
is-empty
}
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn reports_nonemptiness() {
let actual = nu!(r#"
[[1] ' ' {a:1} 0]
| any {||
is-empty
}
"#);
assert_eq!(actual.out, "false");
}
#[test]
fn reports_emptiness_by_columns() {
let actual = nu!("
[{a:1 b:null c:null} {a:2 b:null c:null}]
| any {||
is-empty b c
}
");
assert_eq!(actual.out, "true");
}
#[test]
fn reports_nonemptiness_by_columns() {
let actual = nu!("
[{a:1 b:null c:3} {a:null b:5 c:2}]
| any {||
is-empty a b
}
");
assert_eq!(actual.out, "false");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/chunks.rs | crates/nu-command/tests/commands/chunks.rs | use nu_test_support::nu;
#[test]
fn chunk_size_negative() {
let actual = nu!("[0 1 2] | chunks -1");
assert!(actual.err.contains("positive"));
}
#[test]
fn chunk_size_zero() {
let actual = nu!("[0 1 2] | chunks 0");
assert!(actual.err.contains("zero"));
}
#[test]
fn chunk_size_not_int() {
let actual = nu!("[0 1 2] | chunks (if true { 1sec })");
assert!(actual.err.contains("can't convert"));
}
#[test]
fn empty() {
let actual = nu!("[] | chunks 2 | is-empty");
assert_eq!(actual.out, "true");
}
#[test]
fn list_stream() {
let actual = nu!("([0 1 2] | every 1 | chunks 2) == ([0 1 2] | chunks 2)");
assert_eq!(actual.out, "true");
}
#[test]
fn table_stream() {
let actual = nu!(
"([[foo bar]; [0 1] [2 3] [4 5]] | every 1 | chunks 2) == ([[foo bar]; [0 1] [2 3] [4 5]] | chunks 2)"
);
assert_eq!(actual.out, "true");
}
#[test]
fn no_empty_chunks() {
let actual = nu!("([0 1 2 3 4 5] | chunks 3 | length) == 2");
assert_eq!(actual.out, "true");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/config_env_default.rs | crates/nu-command/tests/commands/config_env_default.rs | use nu_test_support::nu;
#[test]
fn print_config_env_default_to_stdout() {
let actual = nu!("config env --default");
assert_eq!(
actual.out,
nu_utils::ConfigFileKind::Env
.default()
.replace(['\n', '\r'], "")
);
assert!(actual.err.is_empty());
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/try_.rs | crates/nu-command/tests/commands/try_.rs | use nu_test_support::nu;
#[test]
fn try_succeed() {
let output = nu!("try { 345 } catch { echo 'hello' }");
assert!(output.out.contains("345"));
}
#[test]
fn try_catch() {
let output = nu!("try { foobarbaz } catch { echo 'hello' }");
assert!(output.out.contains("hello"));
}
#[test]
fn catch_can_access_error() {
let output = nu!("try { foobarbaz } catch { |err| $err | get raw }");
assert!(output.err.contains("External command failed"));
}
#[test]
fn catch_can_access_error_as_dollar_in() {
let output = nu!("try { foobarbaz } catch { $in | get raw }");
assert!(output.err.contains("External command failed"));
}
#[test]
fn external_failed_should_be_caught() {
let output = nu!("try { nu --testbin fail; echo 'success' } catch { echo 'fail' }");
assert!(output.out.contains("fail"));
}
#[test]
fn loop_try_break_should_be_successful() {
let output =
nu!("loop { try { print 'successful'; break } catch { print 'failed'; continue } }");
assert_eq!(output.out, "successful");
}
#[test]
fn loop_try_break_should_pop_error_handlers() {
let output = nu!(r#"
do {
loop {
try {
break
} catch {
print 'jumped to catch block'
return
}
}
error make -u {msg: "success"}
}
"#);
assert!(!output.status.success(), "error was caught");
assert!(output.err.contains("success"));
}
#[test]
fn loop_nested_try_break_should_pop_error_handlers() {
let output = nu!(r#"
do {
loop {
try {
try {
break
} catch {
print 'jumped to inner catch block'
return
}
} catch {
print 'jumped to outer catch block'
return
}
}
error make -u {msg: "success"}
}
"#);
assert!(!output.status.success(), "error was caught");
assert!(output.err.contains("success"));
}
#[test]
fn loop_try_continue_should_pop_error_handlers() {
let output = nu!(r#"
do {
mut error = false
loop {
if $error {
error make -u {msg: "success"}
}
try {
$error = true
continue
} catch {
print 'jumped to catch block'
return
}
}
}
"#);
assert!(!output.status.success(), "error was caught");
assert!(output.err.contains("success"));
}
#[test]
fn loop_catch_break_should_show_failed() {
let output = nu!("loop {
try { invalid 1;
continue; } catch { print 'failed'; break }
}
");
assert_eq!(output.out, "failed");
}
#[test]
fn loop_try_ignores_continue() {
let output = nu!("mut total = 0;
for i in 0..10 {
try { if ($i mod 2) == 0 {
continue;}
$total += 1
} catch { echo 'failed'; break }
}
echo $total
");
assert_eq!(output.out, "5");
}
#[test]
fn loop_try_break_on_command_should_show_successful() {
let output = nu!("loop { try { ls; break } catch { echo 'failed';continue }}");
assert!(!output.out.contains("failed"));
}
#[test]
fn catch_block_can_use_error_object() {
let output = nu!("try {1 / 0} catch {|err| print ($err | get msg)}");
assert_eq!(output.out, "Division by zero.")
}
#[test]
fn catch_input_type_mismatch_and_rethrow() {
let actual = nu!(
"let x: any = 1; try { $x | get 1 } catch {|err| error make { msg: ($err | get msg) } }"
);
assert!(actual.err.contains("Input type not supported"));
}
// This test is disabled on Windows because they cause a stack overflow in CI (but not locally!).
// For reasons we don't understand, the Windows CI runners are prone to stack overflow.
// TODO: investigate so we can enable on Windows
#[cfg(not(target_os = "windows"))]
#[test]
fn can_catch_infinite_recursion() {
let actual = nu!(r#"
def bang [] { try { bang } catch { "Caught infinite recursion" } }; bang
"#);
assert_eq!(actual.out, "Caught infinite recursion");
}
#[test]
fn exit_code_available_in_catch_env() {
let actual = nu!("try { nu -c 'exit 42' } catch { $env.LAST_EXIT_CODE }");
assert_eq!(actual.out, "42");
}
#[test]
fn exit_code_available_in_catch() {
let actual = nu!("try { nu -c 'exit 42' } catch { |e| $e.exit_code }");
assert_eq!(actual.out, "42");
}
#[test]
fn catches_exit_code_in_assignment() {
let actual = nu!("let x = try { nu -c 'exit 42' } catch { |e| $e.exit_code }; $x");
assert_eq!(actual.out, "42");
}
#[test]
fn catches_exit_code_in_expr() {
let actual = nu!("print (try { nu -c 'exit 42' } catch { |e| $e.exit_code })");
assert_eq!(actual.out, "42");
}
#[test]
fn prints_only_if_last_pipeline() {
let actual = nu!("try { 'should not print' }; 'last value'");
assert_eq!(actual.out, "last value");
let actual = nu!("try { ['should not print'] | every 1 }; 'last value'");
assert_eq!(actual.out, "last value");
}
#[test]
fn get_error_columns() {
let actual = nu!(" try { non_existent_command } catch {|err| $err} | columns | to json -r");
assert_eq!(
actual.out,
"[\"msg\",\"debug\",\"raw\",\"rendered\",\"json\"]"
);
}
#[test]
fn get_json_error() {
let actual = nu!(
"try { non_existent_command } catch {|err| $err} | get json | from json | update labels.span {{start: 0 end: 0}} | to json -r"
);
assert_eq!(
actual.out,
"{\"msg\":\"External command failed\",\"labels\":[{\"text\":\"Command `non_existent_command` not found\",\"span\":{\"start\":0,\"end\":0}}],\"code\":\"nu::shell::external_command\",\"url\":null,\"help\":\"`non_existent_command` is neither a Nushell built-in or a known external command\",\"inner\":[]}"
);
}
#[test]
fn pipefail_works() {
let actual = nu!(
experimental: vec!["pipefail".to_string()],
"try { let x = nu --testbin fail | lines | length; print $x } catch {|e| print $e.exit_code}"
);
assert_eq!(actual.out, "1")
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/help.rs | crates/nu-command/tests/commands/help.rs | use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::playground::Playground;
use nu_test_support::{nu, nu_repl_code};
// Note: These tests might slightly overlap with tests/scope/mod.rs
#[test]
fn help_commands_length() {
let actual = nu!("help commands | length");
let output = actual.out;
let output_int: i32 = output.parse().unwrap();
let is_positive = output_int.is_positive();
assert!(is_positive);
}
#[test]
fn help_shows_signature() {
let actual = nu!("help str distance");
assert!(actual.out.contains("Input/output types"));
// don't show signature for parser keyword
let actual = nu!("help alias");
assert!(!actual.out.contains("Input/output types"));
}
#[test]
fn help_aliases() {
let code = &[
"alias SPAM = print 'spam'",
"help aliases | where name == SPAM | length",
];
let actual = nu!(nu_repl_code(code));
assert_eq!(actual.out, "1");
}
#[test]
fn help_alias_description_1() {
Playground::setup("help_alias_description_1", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
# line1
alias SPAM = print 'spam'
"#,
)]);
let code = &[
"source spam.nu",
"help aliases | where name == SPAM | get 0.description",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(code));
assert_eq!(actual.out, "line1");
})
}
#[test]
fn help_alias_description_2() {
let code = &[
"alias SPAM = print 'spam' # line2",
"help aliases | where name == SPAM | get 0.description",
];
let actual = nu!(nu_repl_code(code));
assert_eq!(actual.out, "line2");
}
#[test]
fn help_alias_description_3() {
Playground::setup("help_alias_description_3", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
# line1
alias SPAM = print 'spam' # line2
"#,
)]);
let code = &[
"source spam.nu",
"help aliases | where name == SPAM | get 0.description",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(code));
assert!(actual.out.contains("line1"));
assert!(actual.out.contains("line2"));
})
}
#[test]
fn help_alias_name() {
Playground::setup("help_alias_name", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
# line1
alias SPAM = print 'spam' # line2
"#,
)]);
let code = &["source spam.nu", "help aliases SPAM"];
let actual = nu!(cwd: dirs.test(), nu_repl_code(code));
assert!(actual.out.contains("line1"));
assert!(actual.out.contains("line2"));
assert!(actual.out.contains("SPAM"));
assert!(actual.out.contains("print 'spam'"));
})
}
#[test]
fn help_alias_name_f() {
Playground::setup("help_alias_name_f", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
# line1
alias SPAM = print 'spam' # line2
"#,
)]);
let code = &["source spam.nu", "help aliases -f SPAM | get 0.description"];
let actual = nu!(cwd: dirs.test(), nu_repl_code(code));
assert!(actual.out.contains("line1"));
assert!(actual.out.contains("line2"));
})
}
#[test]
fn help_export_alias_name_single_word() {
Playground::setup("help_export_alias_name_single_word", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
# line1
export alias SPAM = print 'spam' # line2
"#,
)]);
let code = &["use spam.nu SPAM", "help aliases SPAM"];
let actual = nu!(cwd: dirs.test(), nu_repl_code(code));
assert!(actual.out.contains("line1"));
assert!(actual.out.contains("line2"));
assert!(actual.out.contains("SPAM"));
assert!(actual.out.contains("print 'spam'"));
})
}
#[test]
fn help_export_alias_name_multi_word() {
Playground::setup("help_export_alias_name_multi_word", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
# line1
export alias SPAM = print 'spam' # line2
"#,
)]);
let code = &["use spam.nu", "help aliases spam SPAM"];
let actual = nu!(cwd: dirs.test(), nu_repl_code(code));
assert!(actual.out.contains("line1"));
assert!(actual.out.contains("line2"));
assert!(actual.out.contains("SPAM"));
assert!(actual.out.contains("print 'spam'"));
})
}
#[test]
fn help_module_description_1() {
Playground::setup("help_module_description", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
# line1
module SPAM {
# line2
} #line3
"#,
)]);
let code = &[
"source spam.nu",
"help modules | where name == SPAM | get 0.description",
];
let actual = nu!(cwd: dirs.test(), nu_repl_code(code));
assert!(actual.out.contains("line1"));
assert!(actual.out.contains("line2"));
assert!(actual.out.contains("line3"));
})
}
#[test]
fn help_module_name() {
Playground::setup("help_module_name", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
# line1
module SPAM {
# line2
} #line3
"#,
)]);
let code = &["source spam.nu", "help modules SPAM"];
let actual = nu!(cwd: dirs.test(), nu_repl_code(code));
assert!(actual.out.contains("line1"));
assert!(actual.out.contains("line2"));
assert!(actual.out.contains("line3"));
assert!(actual.out.contains("SPAM"));
})
}
#[test]
fn help_module_sorted_decls() {
Playground::setup("help_module_sorted_decls", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
module SPAM {
export def z [] {}
export def a [] {}
}
"#,
)]);
let code = &["source spam.nu", "help modules SPAM"];
let actual = nu!(cwd: dirs.test(), nu_repl_code(code));
assert!(actual.out.contains("a, z"));
})
}
#[test]
fn help_module_sorted_aliases() {
Playground::setup("help_module_sorted_aliases", |dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
module SPAM {
export alias z = echo 'z'
export alias a = echo 'a'
}
"#,
)]);
let code = &["source spam.nu", "help modules SPAM"];
let actual = nu!(cwd: dirs.test(), nu_repl_code(code));
assert!(actual.out.contains("a, z"));
})
}
#[test]
fn help_description_extra_description_command() {
Playground::setup(
"help_description_extra_description_command",
|dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
# module_line1
#
# module_line2
# def_line1
#
# def_line2
export def foo [] {}
"#,
)]);
let actual = nu!(cwd: dirs.test(), "use spam.nu *; help modules spam");
assert!(actual.out.contains("module_line1"));
assert!(actual.out.contains("module_line2"));
let actual = nu!(cwd: dirs.test(),
"use spam.nu *; help modules | where name == spam | get 0.description");
assert!(actual.out.contains("module_line1"));
assert!(!actual.out.contains("module_line2"));
let actual = nu!(cwd: dirs.test(), "use spam.nu *; help commands foo");
assert!(actual.out.contains("def_line1"));
assert!(actual.out.contains("def_line2"));
let actual = nu!(cwd: dirs.test(),
"use spam.nu *; help commands | where name == foo | get 0.description");
assert!(actual.out.contains("def_line1"));
assert!(!actual.out.contains("def_line2"));
},
)
}
#[test]
fn help_description_extra_description_alias() {
Playground::setup(
"help_description_extra_description_alias",
|dirs, sandbox| {
sandbox.with_files(&[FileWithContent(
"spam.nu",
r#"
# module_line1
#
# module_line2
# alias_line1
#
# alias_line2
export alias bar = echo 'bar'
"#,
)]);
let actual = nu!(cwd: dirs.test(), "use spam.nu *; help modules spam");
assert!(actual.out.contains("module_line1"));
assert!(actual.out.contains("module_line2"));
let actual = nu!(cwd: dirs.test(),
"use spam.nu *; help modules | where name == spam | get 0.description");
assert!(actual.out.contains("module_line1"));
assert!(!actual.out.contains("module_line2"));
let actual = nu!(cwd: dirs.test(), "use spam.nu *; help aliases bar");
assert!(actual.out.contains("alias_line1"));
assert!(actual.out.contains("alias_line2"));
let actual = nu!(cwd: dirs.test(),
"use spam.nu *; help aliases | where name == bar | get 0.description");
assert!(actual.out.contains("alias_line1"));
assert!(!actual.out.contains("alias_line2"));
},
)
}
#[test]
fn help_modules_main_1() {
let inp = &[
r#"module spam {
export def main [] { 'foo' };
}"#,
"help spam",
];
let actual = nu!(&inp.join("; "));
assert!(actual.out.contains(" spam"));
}
#[test]
fn help_modules_main_2() {
let inp = &[
r#"module spam {
export def main [] { 'foo' };
}"#,
"help modules | where name == spam | get 0.commands.0.name",
];
let actual = nu!(&inp.join("; "));
assert_eq!(actual.out, "spam");
}
#[test]
fn nothing_type_annotation() {
let actual = nu!("
def foo []: nothing -> nothing {};
help commands | where name == foo | get input_output.0.output.0
");
assert_eq!(actual.out, "nothing");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/flatten.rs | crates/nu-command/tests/commands/flatten.rs | use nu_test_support::nu;
#[test]
fn flatten_nested_tables_with_columns() {
let actual = nu!(r#"
[
[[origin, people]; [Ecuador, ('Andres' | wrap name)]]
[[origin, people]; [Nu, ('nuno' | wrap name)]]
]
| flatten --all
| flatten --all
| get name
| str join ','
"#);
assert_eq!(actual.out, "Andres,nuno");
}
#[test]
fn flatten_nested_tables_that_have_many_columns() {
let actual = nu!(r#"
(
echo [
[origin, people];
[
Ecuador,
(echo [
[name, meal];
['Andres', 'arepa']
])
]
]
[
[origin, people];
[
USA,
(echo [
[name, meal];
['Katz', 'nurepa']
])
]
]
)
| flatten --all
| flatten --all
| get meal
| str join ','
"#);
assert_eq!(actual.out, "arepa,nurepa");
}
#[test]
fn flatten_nested_tables() {
let actual = nu!("echo [[Andrés, Nicolás, Robalino]] | flatten | get 1");
assert_eq!(actual.out, "Nicolás");
}
#[test]
fn flatten_row_column_explicitly() {
let sample = r#"
[
{
"people": {
"name": "Andres",
"meal": "arepa"
}
},
{
"people": {
"name": "Katz",
"meal": "nurepa"
}
}
]
"#;
let actual = nu!(format!(
"{sample} | flatten people --all | where name == Andres | length"
));
assert_eq!(actual.out, "1");
}
#[test]
fn flatten_row_columns_having_same_column_names_flats_separately() {
let sample = r#"
[
{
"people": {
"name": "Andres",
"meal": "arepa"
},
"city": [{"name": "Guayaquil"}, {"name": "Samborondón"}]
},
{
"people": {
"name": "Katz",
"meal": "nurepa"
},
"city": [{"name": "Oregon"}, {"name": "Brooklin"}]
}
]
"#;
let actual = nu!(format!(
"{sample} | flatten --all | flatten people city | get city_name | length"
));
assert_eq!(actual.out, "4");
}
#[test]
fn flatten_table_columns_explicitly() {
let sample = r#"
[
{
"people": {
"name": "Andres",
"meal": "arepa"
},
"city": ["Guayaquil", "Samborondón"]
},
{
"people": {
"name": "Katz",
"meal": "nurepa"
},
"city": ["Oregon", "Brooklin"]
}
]
"#;
let actual = nu!(format!(
"{sample} | flatten city --all | where people.name == Katz | length",
));
assert_eq!(actual.out, "2");
}
#[test]
fn flatten_more_than_one_column_that_are_subtables_not_supported() {
let sample = r#"
[
{
"people": {
"name": "Andres",
"meal": "arepa"
}
"tags": ["carbohydrate", "corn", "maiz"],
"city": ["Guayaquil", "Samborondón"]
},
{
"people": {
"name": "Katz",
"meal": "nurepa"
},
"tags": ["carbohydrate", "shell food", "amigos flavor"],
"city": ["Oregon", "Brooklin"]
}
]
"#;
let actual = nu!(format!("{sample} | flatten tags city --all"));
assert!(actual.err.contains("tried flattening"));
assert!(actual.err.contains("but is flattened already"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/redirection.rs | crates/nu-command/tests/commands/redirection.rs | use nu_test_support::fs::{Stub::FileWithContent, file_contents};
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn redirect_err() {
Playground::setup("redirect_err_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
r#"$env.BAZ = "asdfasdfasdf.txt"; nu --testbin echo_env_stderr BAZ err> a.txt; open a.txt"#
);
assert!(output.out.contains("asdfasdfasdf.txt"));
// check append mode
let output = nu!(
cwd: dirs.test(),
r#"$env.BAZ = "asdfasdfasdf.txt"; nu --testbin echo_env_stderr BAZ err>> a.txt; open a.txt"#
);
let v: Vec<_> = output.out.match_indices("asdfasdfasdf.txt").collect();
assert_eq!(v.len(), 2);
})
}
#[test]
fn redirect_outerr() {
Playground::setup("redirect_outerr_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
r#"$env.BAZ = "asdfasdfasdf.txt"; nu --testbin echo_env_stderr BAZ out+err> a.txt; open a.txt"#
);
assert!(output.out.contains("asdfasdfasdf.txt"));
let output = nu!(
cwd: dirs.test(),
r#"$env.BAZ = "asdfasdfasdf.txt"; nu --testbin echo_env_stderr BAZ o+e>> a.txt; open a.txt"#
);
let v: Vec<_> = output.out.match_indices("asdfasdfasdf.txt").collect();
assert_eq!(v.len(), 2);
})
}
#[test]
fn redirect_out() {
Playground::setup("redirect_out_test", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
"echo 'hello' out> a; open a"
);
assert!(output.out.contains("hello"));
let output = nu!(
cwd: dirs.test(),
"echo 'hello' out>> a; open a"
);
assert!(output.out.contains("hellohello"));
})
}
#[test]
fn two_lines_redirection() {
Playground::setup("redirections with two lines commands", |dirs, _| {
nu!(
cwd: dirs.test(),
r#"
def foobar [] {
'hello' out> output1.txt
'world' out> output2.txt
}
foobar"#);
let file_out1 = dirs.test().join("output1.txt");
let actual = file_contents(file_out1);
assert!(actual.contains("hello"));
let file_out2 = dirs.test().join("output2.txt");
let actual = file_contents(file_out2);
assert!(actual.contains("world"));
})
}
#[test]
fn separate_redirection() {
Playground::setup(
"external with both stdout and stderr messages, to different file",
|dirs, _| {
let expect_body = "message";
nu!(
cwd: dirs.test(),
r#"$env.BAZ = "message"; nu --testbin echo_env_mixed out-err BAZ BAZ o> out.txt e> err.txt"#,
);
// check for stdout redirection file.
let expected_out_file = dirs.test().join("out.txt");
let actual = file_contents(expected_out_file);
assert!(actual.contains(expect_body));
// check for stderr redirection file.
let expected_err_file = dirs.test().join("err.txt");
let actual = file_contents(expected_err_file);
assert!(actual.contains(expect_body));
nu!(
cwd: dirs.test(),
r#"$env.BAZ = "message"; nu --testbin echo_env_mixed out-err BAZ BAZ o>> out.txt e>> err.txt"#,
);
// check for stdout redirection file.
let expected_out_file = dirs.test().join("out.txt");
let actual = file_contents(expected_out_file);
let v: Vec<_> = actual.match_indices("message").collect();
assert_eq!(v.len(), 2);
// check for stderr redirection file.
let expected_err_file = dirs.test().join("err.txt");
let actual = file_contents(expected_err_file);
let v: Vec<_> = actual.match_indices("message").collect();
assert_eq!(v.len(), 2);
},
)
}
#[test]
fn same_target_redirection_with_too_much_stderr_not_hang_nushell() {
use nu_test_support::playground::Playground;
Playground::setup("external with many stderr message", |dirs, sandbox| {
let bytes: usize = 81920;
let mut large_file_body = String::with_capacity(bytes);
for _ in 0..bytes {
large_file_body.push('a');
}
sandbox.with_files(&[FileWithContent("a_large_file.txt", &large_file_body)]);
nu!(cwd: dirs.test(), "
$env.LARGE = (open --raw a_large_file.txt);
nu --testbin echo_env_stderr LARGE out+err> another_large_file.txt
");
let expected_file = dirs.test().join("another_large_file.txt");
let actual = file_contents(expected_file);
assert_eq!(actual, format!("{large_file_body}\n"));
// not hangs in append mode either.
let cloned_body = large_file_body.clone();
large_file_body.push_str(&format!("\n{cloned_body}"));
nu!(cwd: dirs.test(), "
$env.LARGE = (open --raw a_large_file.txt);
nu --testbin echo_env_stderr LARGE out+err>> another_large_file.txt
");
let expected_file = dirs.test().join("another_large_file.txt");
let actual = file_contents(expected_file);
assert_eq!(actual, format!("{large_file_body}\n"));
})
}
#[test]
fn redirection_keep_exit_codes() {
Playground::setup("redirection preserves exit code", |dirs, _| {
let out = nu!(
cwd: dirs.test(),
"nu --testbin fail e> a.txt | complete | get exit_code"
);
// needs to use contains "1", because it complete will output `Some(RawStream)`.
assert!(out.out.contains('1'));
});
}
#[test]
fn redirection_stderr_with_failed_program() {
Playground::setup("redirection stderr with failed program", |dirs, _| {
let out = nu!(
cwd: dirs.test(),
r#"$env.FOO = "bar"; nu --testbin echo_env_stderr_fail FOO e> file.txt; echo 3"#
);
// firstly echo 3 shouldn't run, because previous command runs to failed.
// second `file.txt` should contain "bar".
assert!(!out.out.contains('3'));
let expected_file = dirs.test().join("file.txt");
let actual = file_contents(expected_file);
assert_eq!(actual, "bar\n");
});
}
#[test]
fn redirection_with_non_zero_exit_code_should_stop_from_running() {
Playground::setup("redirection with non zero exit code", |dirs, _| {
for redirection in ["o>", "o>>", "e>", "e>>", "o+e>", "o+e>>"] {
let output = nu!(
cwd: dirs.test(),
&format!("nu --testbin fail {redirection} log.txt; echo 3")
);
assert!(!output.out.contains('3'));
}
});
Playground::setup("redirection with non zero exit code", |dirs, _| {
for (out, err) in [("o>", "e>"), ("o>>", "e>"), ("o>", "e>>"), ("o>>", "e>>")] {
let output = nu!(
cwd: dirs.test(),
&format!("nu --testbin fail {out} log.txt {err} err_log.txt; echo 3")
);
assert!(!output.out.contains('3'));
}
})
}
#[test]
fn redirection_with_pipeline_works() {
use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::playground::Playground;
Playground::setup(
"external with stdout message with pipeline should write data",
|dirs, sandbox| {
let script_body = r"echo message";
let expect_body = "message";
sandbox.with_files(&[FileWithContent("test.sh", script_body)]);
let actual = nu!(
cwd: dirs.test(),
r#"$env.BAZ = "message"; nu --testbin echo_env BAZ out> out.txt | describe; open out.txt"#,
);
assert!(actual.out.contains(expect_body));
// check append mode works
let actual = nu!(
cwd: dirs.test(),
r#"$env.BAZ = "message"; nu --testbin echo_env BAZ out>> out.txt | describe; open out.txt"#,
);
let v: Vec<_> = actual.out.match_indices("message").collect();
assert_eq!(v.len(), 2);
},
)
}
#[test]
fn redirect_support_variable() {
Playground::setup("redirect_out_support_variable", |dirs, _sandbox| {
let output = nu!(
cwd: dirs.test(),
"let x = 'tmp_file'; echo 'hello' out> $x; open tmp_file"
);
assert!(output.out.contains("hello"));
nu!(
cwd: dirs.test(),
"let x = 'tmp_file'; echo 'hello there' out+err> $x; open tmp_file"
);
// check for stdout redirection file.
let expected_out_file = dirs.test().join("tmp_file");
let actual = file_contents(expected_out_file);
assert!(actual.contains("hello there"));
// append mode support variable too.
let output = nu!(
cwd: dirs.test(),
"let x = 'tmp_file'; echo 'hello' out>> $x; open tmp_file"
);
let v: Vec<_> = output.out.match_indices("hello").collect();
assert_eq!(v.len(), 2);
let output = nu!(
cwd: dirs.test(),
"let x = 'tmp_file'; echo 'hello' out+err>> $x; open tmp_file"
);
// check for stdout redirection file.
let v: Vec<_> = output.out.match_indices("hello").collect();
assert_eq!(v.len(), 3);
})
}
#[test]
fn separate_redirection_support_variable() {
Playground::setup(
"external with both stdout and stderr messages, to different file",
|dirs, _| {
let expect_body = "message";
nu!(
cwd: dirs.test(),
r#"
let o_f = "out2.txt"
let e_f = "err2.txt"
$env.BAZ = "message"; nu --testbin echo_env_mixed out-err BAZ BAZ o> $o_f e> $e_f"#,
);
// check for stdout redirection file.
let expected_out_file = dirs.test().join("out2.txt");
let actual = file_contents(expected_out_file);
assert!(actual.contains(expect_body));
// check for stderr redirection file.
let expected_err_file = dirs.test().join("err2.txt");
let actual = file_contents(expected_err_file);
assert!(actual.contains(expect_body));
nu!(
cwd: dirs.test(),
r#"
let o_f = "out2.txt"
let e_f = "err2.txt"
$env.BAZ = "message"; nu --testbin echo_env_mixed out-err BAZ BAZ out>> $o_f err>> $e_f"#,
);
// check for stdout redirection file.
let expected_out_file = dirs.test().join("out2.txt");
let actual = file_contents(expected_out_file);
let v: Vec<_> = actual.match_indices("message").collect();
assert_eq!(v.len(), 2);
// check for stderr redirection file.
let expected_err_file = dirs.test().join("err2.txt");
let actual = file_contents(expected_err_file);
let v: Vec<_> = actual.match_indices("message").collect();
assert_eq!(v.len(), 2);
},
)
}
#[test]
fn redirection_should_have_a_target() {
Playground::setup("redirection_should_have_a_target", |dirs, _| {
let scripts = [
"echo asdf o+e>",
"echo asdf o>",
"echo asdf e>",
"echo asdf o> e>",
"echo asdf o> tmp.txt e>",
"echo asdf o> e> tmp.txt",
"echo asdf o> | ignore",
"echo asdf o>; echo asdf",
];
for code in scripts {
let actual = nu!(cwd: dirs.test(), code);
assert!(
actual.err.contains("expected redirection target",),
"should be error, code: {code}",
);
assert!(
!dirs.test().join("tmp.txt").exists(),
"No file should be created on error: {code}",
);
}
});
}
#[test]
fn redirection_with_out_pipe() {
use nu_test_support::playground::Playground;
Playground::setup("redirection with out pipes", |dirs, _| {
// check for stdout
let actual = nu!(
cwd: dirs.test(),
r#"$env.BAZ = "message"; nu --testbin echo_env_mixed out-err BAZ BAZ err> tmp_file | str length"#,
);
assert_eq!(actual.out, "7");
// check for stderr redirection file.
let expected_out_file = dirs.test().join("tmp_file");
let actual_len = file_contents(expected_out_file).len();
assert_eq!(actual_len, 8);
})
}
#[test]
fn redirection_with_err_pipe() {
use nu_test_support::playground::Playground;
Playground::setup("redirection with err pipe", |dirs, _| {
// check for stdout
let actual = nu!(
cwd: dirs.test(),
r#"$env.BAZ = "message"; nu --testbin echo_env_mixed out-err BAZ BAZ out> tmp_file e>| str length"#,
);
assert_eq!(actual.out, "7");
// check for stdout redirection file.
let expected_out_file = dirs.test().join("tmp_file");
let actual_len = file_contents(expected_out_file).len();
assert_eq!(actual_len, 8);
})
}
#[test]
fn no_redirection_with_outerr_pipe() {
Playground::setup("redirection does not accept outerr pipe", |dirs, _| {
for redirect_type in ["o>", "e>", "o+e>"] {
let actual = nu!(
cwd: dirs.test(),
&format!("echo 3 {redirect_type} a.txt o+e>| str length")
);
assert!(actual.err.contains("Multiple redirections provided"));
assert!(
!dirs.test().join("a.txt").exists(),
"No file should be created on error"
);
}
// test for separate redirection
let actual = nu!(
cwd: dirs.test(),
"echo 3 o> a.txt e> b.txt o+e>| str length"
);
assert!(actual.err.contains("Multiple redirections provided"));
assert!(
!dirs.test().join("a.txt").exists(),
"No file should be created on error"
);
assert!(
!dirs.test().join("b.txt").exists(),
"No file should be created on error"
);
});
}
#[test]
fn no_duplicate_redirection() {
Playground::setup("redirection does not accept duplicate", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"echo 3 o> a.txt o> a.txt"
);
assert!(actual.err.contains("Multiple redirections provided"));
assert!(
!dirs.test().join("a.txt").exists(),
"No file should be created on error"
);
let actual = nu!(
cwd: dirs.test(),
"echo 3 e> a.txt e> a.txt"
);
assert!(actual.err.contains("Multiple redirections provided"));
assert!(
!dirs.test().join("a.txt").exists(),
"No file should be created on error"
);
});
}
#[rstest::rstest]
#[case("let", "out>")]
#[case("let", "err>")]
#[case("let", "out+err>")]
#[case("mut", "out>")]
#[case("mut", "err>")]
#[case("mut", "out+err>")]
fn file_redirection_in_let_and_mut(#[case] keyword: &str, #[case] redir: &str) {
Playground::setup("file redirection in let and mut", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("$env.BAZ = 'foo'; {keyword} v = nu --testbin echo_env_mixed out-err BAZ BAZ {redir} result.txt")
);
assert!(actual.status.success());
assert!(file_contents(dirs.test().join("result.txt")).contains("foo"));
})
}
#[rstest::rstest]
#[case("let", "err>|", "foo3")]
#[case("let", "out+err>|", "7")]
#[case("mut", "err>|", "foo3")]
#[case("mut", "out+err>|", "7")]
fn pipe_redirection_in_let_and_mut(
#[case] keyword: &str,
#[case] redir: &str,
#[case] output: &str,
) {
let actual = nu!(format!(
"$env.BAZ = 'foo'; {keyword} v = nu --testbin echo_env_mixed out-err BAZ BAZ {redir} str length; $v"
));
assert_eq!(actual.out, output);
}
#[rstest::rstest]
#[case("o>", "bar")]
#[case("e>", "baz")]
#[case("o+e>", "bar\nbaz")] // in subexpression, the stderr is go to the terminal
fn subexpression_redirection(#[case] redir: &str, #[case] stdout_file_body: &str) {
Playground::setup("file redirection with subexpression", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("$env.BAR = 'bar'; $env.BAZ = 'baz'; (nu --testbin echo_env_mixed out-err BAR BAZ) {redir} result.txt")
);
assert!(actual.status.success());
assert_eq!(
file_contents(dirs.test().join("result.txt")).trim(),
stdout_file_body
);
})
}
#[rstest::rstest]
#[case("o>", "bar")]
#[case("e>", "baz")]
#[case("o+e>", "bar\nbaz")]
fn file_redirection_in_if_true(#[case] redir: &str, #[case] stdout_file_body: &str) {
Playground::setup("file redirection if true block", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("$env.BAR = 'bar'; $env.BAZ = 'baz'; if true {{ nu --testbin echo_env_mixed out-err BAR BAZ }} {redir} result.txt")
);
assert!(actual.status.success());
assert_eq!(
file_contents(dirs.test().join("result.txt")).trim(),
stdout_file_body
);
})
}
#[rstest::rstest]
#[case(true, "hey")]
#[case(false, "ho")]
fn file_redirection_in_if_else(#[case] cond: bool, #[case] stdout_file_body: &str) {
Playground::setup("file redirection if-else block", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("if {cond} {{ echo 'hey' }} else {{ echo 'ho' }} out> result.txt")
);
assert!(actual.status.success());
assert_eq!(
file_contents(dirs.test().join("result.txt")).trim(),
stdout_file_body
);
})
}
#[rstest::rstest]
#[case("o>", "bar")]
#[case("e>", "baz")]
#[case("o+e>", "bar\nbaz")]
fn file_redirection_in_try_catch(#[case] redir: &str, #[case] stdout_file_body: &str) {
Playground::setup("file redirection try-catch block", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("$env.BAR = 'bar'; $env.BAZ = 'baz'; try {{ 1/0 }} catch {{ nu --testbin echo_env_mixed out-err BAR BAZ }} {redir} result.txt")
);
assert!(actual.status.success());
assert_eq!(
file_contents(dirs.test().join("result.txt")).trim(),
stdout_file_body
);
})
}
#[rstest::rstest]
fn file_redirection_where_closure() {
Playground::setup("file redirection where closure", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("echo foo bar | where {{|x| $x | str contains 'f'}} out> result.txt")
);
assert!(actual.status.success());
assert_eq!(file_contents(dirs.test().join("result.txt")).trim(), "foo");
})
}
#[rstest::rstest]
fn file_redirection_match_block() {
Playground::setup("file redirection match block", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("match 3 {{ 1 => 'foo', 3 => 'bar' }} out> result.txt")
);
assert!(actual.status.success());
assert_eq!(file_contents(dirs.test().join("result.txt")).trim(), "bar");
})
}
#[rstest::rstest]
fn file_redirection_pattern_match_block() {
Playground::setup("file redirection pattern match block", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("let foo = {{ name: 'bar' }}; match $foo {{ {{ name: 'bar' }} => 'baz' }} out> result.txt")
);
assert!(actual.status.success());
assert_eq!(file_contents(dirs.test().join("result.txt")).trim(), "baz");
})
}
#[rstest::rstest]
fn file_redirection_each_block() {
Playground::setup("file redirection each block", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("[1 2 3] | each {{ $in + 1 }} out> result.txt")
);
assert!(actual.status.success());
assert_eq!(
file_contents(dirs.test().join("result.txt")).trim(),
"2\n3\n4"
);
})
}
#[rstest::rstest]
fn file_redirection_do_block_with_return() {
Playground::setup("file redirection do block with return", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("do {{|x| return ($x + 1); return $x}} 4 out> result.txt")
);
assert!(actual.status.success());
assert_eq!(file_contents(dirs.test().join("result.txt")).trim(), "5");
})
}
#[rstest::rstest]
fn file_redirection_while_block() {
Playground::setup("file redirection on while", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("mut x = 0; while $x < 3 {{ $x = $x + 1; echo $x }} o> result.txt")
);
// Why the discrepancy to `for` behaviour?
assert!(actual.status.success());
assert_eq!(file_contents(dirs.test().join("result.txt")), "");
})
}
#[rstest::rstest]
fn file_redirection_not_allowed_on_for() {
Playground::setup("file redirection disallowed on for", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
format!("for $it in [1 2 3] {{ echo $in + 1 }} out> result.txt")
);
assert!(!actual.status.success());
assert!(
actual.err.contains("Redirection can not be used with for"),
"Should fail"
);
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/interleave.rs | crates/nu-command/tests/commands/interleave.rs | use nu_test_support::nu;
#[test]
fn interleave_external_commands() {
let result = nu!("interleave \
{ nu -n -c 'print hello; print world' | lines | each { 'greeter: ' ++ $in } } \
{ nu -n -c 'print nushell; print rocks' | lines | each { 'evangelist: ' ++ $in } } | \
each { print }; null");
assert!(result.out.contains("greeter: hello"), "{}", result.out);
assert!(result.out.contains("greeter: world"), "{}", result.out);
assert!(result.out.contains("evangelist: nushell"), "{}", result.out);
assert!(result.out.contains("evangelist: rocks"), "{}", result.out);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/table.rs | crates/nu-command/tests/commands/table.rs | use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::playground::Playground;
use nu_test_support::{nu, nu_repl_code};
#[test]
fn table_0() {
let actual = nu!("[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80");
assert_eq!(
actual.out,
"╭───┬───┬───┬────────────────╮\
│ # │ a │ b │ c │\
├───┼───┼───┼────────────────┤\
│ 0 │ 1 │ 2 │ 3 │\
│ 1 │ 4 │ 5 │ [list 3 items] │\
╰───┴───┴───┴────────────────╯"
);
}
#[test]
fn table_collapse_0() {
let actual = nu!("[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --collapse");
assert_eq!(
actual.out,
"╭───┬───┬───╮\
│ a │ b │ c │\
├───┼───┼───┤\
│ 1 │ 2 │ 3 │\
├───┼───┼───┤\
│ 4 │ 5 │ 1 │\
│ │ ├───┤\
│ │ │ 2 │\
│ │ ├───┤\
│ │ │ 3 │\
╰───┴───┴───╯"
);
}
#[test]
fn table_collapse_basic() {
let actual = nu!(nu_repl_code(&[
"$env.config = { table: { mode: basic }};",
"[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --collapse"
]));
assert_eq!(
actual.out,
"+---+---+---+\
| a | b | c |\
+---+---+---+\
| 1 | 2 | 3 |\
+---+---+---+\
| 4 | 5 | 1 |\
| | +---+\
| | | 2 |\
| | +---+\
| | | 3 |\
+---+---+---+"
);
}
#[test]
fn table_collapse_heavy() {
let actual = nu!(nu_repl_code(&[
"$env.config = { table: { mode: heavy }};",
"[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --collapse"
]));
assert_eq!(
actual.out,
"┏━━━┳━━━┳━━━┓\
┃ a ┃ b ┃ c ┃\
┣━━━╋━━━╋━━━┫\
┃ 1 ┃ 2 ┃ 3 ┃\
┣━━━╋━━━╋━━━┫\
┃ 4 ┃ 5 ┃ 1 ┃\
┃ ┃ ┣━━━┫\
┃ ┃ ┃ 2 ┃\
┃ ┃ ┣━━━┫\
┃ ┃ ┃ 3 ┃\
┗━━━┻━━━┻━━━┛"
);
}
#[test]
fn table_collapse_compact() {
let actual = nu!(nu_repl_code(&[
"$env.config = { table: { mode: compact }};",
"[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --collapse"
]));
assert_eq!(
actual.out,
"┌───┬───┬───┐\
│ a │ b │ c │\
├───┼───┼───┤\
│ 1 │ 2 │ 3 │\
├───┼───┼───┤\
│ 4 │ 5 │ 1 │\
│ │ ├───┤\
│ │ │ 2 │\
│ │ ├───┤\
│ │ │ 3 │\
└───┴───┴───┘"
);
}
#[test]
fn table_collapse_compact_double() {
let actual = nu!(nu_repl_code(&[
"$env.config = { table: { mode: compact_double }};",
"[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --collapse"
]));
assert_eq!(
actual.out,
"╔═══╦═══╦═══╗\
║ a ║ b ║ c ║\
╠═══╬═══╬═══╣\
║ 1 ║ 2 ║ 3 ║\
╠═══╬═══╬═══╣\
║ 4 ║ 5 ║ 1 ║\
║ ║ ╠═══╣\
║ ║ ║ 2 ║\
║ ║ ╠═══╣\
║ ║ ║ 3 ║\
╚═══╩═══╩═══╝"
);
}
#[test]
fn table_collapse_compact_light() {
let actual = nu!(nu_repl_code(&[
"$env.config = { table: { mode: light }};",
"[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --collapse"
]));
assert_eq!(
actual.out,
"┌───┬───┬───┐\
│ a │ b │ c │\
├───┼───┼───┤\
│ 1 │ 2 │ 3 │\
├───┼───┼───┤\
│ 4 │ 5 │ 1 │\
│ │ ├───┤\
│ │ │ 2 │\
│ │ ├───┤\
│ │ │ 3 │\
└───┴───┴───┘"
);
}
#[test]
fn table_collapse_none() {
let actual = nu!(nu_repl_code(&[
"$env.config = { table: { mode: none }};",
"[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --collapse"
]));
assert_eq!(
actual.out,
concat!(
" a b c ",
" 1 2 3 ",
" 4 5 1 ",
" 2 ",
" 3 ",
)
);
}
#[test]
fn table_collapse_compact_reinforced() {
let actual = nu!(nu_repl_code(&[
"$env.config = { table: { mode: reinforced }};",
"[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --collapse"
]));
assert_eq!(
actual.out,
"┏───┬───┬───┓\
│ a │ b │ c │\
├───┼───┼───┤\
│ 1 │ 2 │ 3 │\
├───┼───┼───┤\
│ 4 │ 5 │ 1 │\
│ │ ├───┤\
│ │ │ 2 │\
│ │ ├───┤\
│ │ │ 3 │\
┗───┴───┴───┛"
);
}
#[test]
fn table_collapse_compact_thin() {
let actual = nu!(nu_repl_code(&[
"$env.config = { table: { mode: thin }};",
"[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --collapse"
]));
assert_eq!(
actual.out,
"┌───┬───┬───┐\
│ a │ b │ c │\
├───┼───┼───┤\
│ 1 │ 2 │ 3 │\
├───┼───┼───┤\
│ 4 │ 5 │ 1 │\
│ │ ├───┤\
│ │ │ 2 │\
│ │ ├───┤\
│ │ │ 3 │\
└───┴───┴───┘"
);
}
#[test]
fn table_collapse_hearts() {
let actual = nu!(nu_repl_code(&[
"$env.config = { table: { mode: with_love }};",
"[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --collapse"
]));
assert_eq!(
actual.out,
concat!(
"❤❤❤❤❤❤❤❤❤❤❤❤❤",
"❤ a ❤ b ❤ c ❤",
"❤❤❤❤❤❤❤❤❤❤❤❤❤",
"❤ 1 ❤ 2 ❤ 3 ❤",
"❤❤❤❤❤❤❤❤❤❤❤❤❤",
"❤ 4 ❤ 5 ❤ 1 ❤",
"❤ ❤ ❤❤❤❤❤",
"❤ ❤ ❤ 2 ❤",
"❤ ❤ ❤❤❤❤❤",
"❤ ❤ ❤ 3 ❤",
"❤❤❤❤❤❤❤❤❤❤❤❤❤",
)
);
}
#[test]
fn table_collapse_does_wrapping_for_long_strings() {
let actual = nu!(
"[[a]; [11111111111111111111111111111111111111111111111111111111111111111111111111111111]] | table --width=80 --collapse"
);
assert_eq!(
actual.out,
"╭────────────────────────────────╮\
│ a │\
├────────────────────────────────┤\
│ 111111111111111109312339230430 │\
│ 179149313814687359833671239329 │\
│ 01313323321729744896.00 │\
╰────────────────────────────────╯"
);
}
#[test]
fn table_expand_0() {
let actual = nu!("[[a b, c]; [1 2 3] [4 5 [1 2 3]]] | table --width=80 --expand");
assert_eq!(
actual.out,
"╭───┬───┬───┬───────────╮\
│ # │ a │ b │ c │\
├───┼───┼───┼───────────┤\
│ 0 │ 1 │ 2 │ 3 │\
│ 1 │ 4 │ 5 │ ╭───┬───╮ │\
│ │ │ │ │ 0 │ 1 │ │\
│ │ │ │ │ 1 │ 2 │ │\
│ │ │ │ │ 2 │ 3 │ │\
│ │ │ │ ╰───┴───╯ │\
╰───┴───┴───┴───────────╯"
);
}
// I am not sure whether the test is platform dependent, cause we don't set a term_width on our own
#[test]
fn table_expand_exceed_overlap_0() {
// no expand
let actual =
nu!("[[a b, c]; [xxxxxxxxxxxxxxxxxxxxxx 2 3] [4 5 [1 2 3]]] | table --width=80 --expand");
assert_eq!(
actual.out,
"╭───┬────────────────────────┬───┬───────────╮\
│ # │ a │ b │ c │\
├───┼────────────────────────┼───┼───────────┤\
│ 0 │ xxxxxxxxxxxxxxxxxxxxxx │ 2 │ 3 │\
│ 1 │ 4 │ 5 │ ╭───┬───╮ │\
│ │ │ │ │ 0 │ 1 │ │\
│ │ │ │ │ 1 │ 2 │ │\
│ │ │ │ │ 2 │ 3 │ │\
│ │ │ │ ╰───┴───╯ │\
╰───┴────────────────────────┴───┴───────────╯",
);
// expand
let actual = nu!(
"[[a b, c]; [xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 2 3] [4 5 [1 2 3]]] | table --width=80 --expand"
);
assert_eq!(
actual.out,
"╭──────┬───────────────────────────────────────────────────┬─────┬─────────────╮\
│ # │ a │ b │ c │\
├──────┼───────────────────────────────────────────────────┼─────┼─────────────┤\
│ 0 │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx │ 2 │ 3 │\
│ 1 │ 4 │ 5 │ ╭───┬───╮ │\
│ │ │ │ │ 0 │ 1 │ │\
│ │ │ │ │ 1 │ 2 │ │\
│ │ │ │ │ 2 │ 3 │ │\
│ │ │ │ ╰───┴───╯ │\
╰──────┴───────────────────────────────────────────────────┴─────┴─────────────╯"
);
}
#[test]
fn table_expand_deep_0() {
let actual =
nu!("[[a b, c]; [1 2 3] [4 5 [1 2 [1 2 3]]]] | table --width=80 --expand --expand-deep=1");
assert_eq!(
actual.out,
"╭───┬───┬───┬────────────────────────╮\
│ # │ a │ b │ c │\
├───┼───┼───┼────────────────────────┤\
│ 0 │ 1 │ 2 │ 3 │\
│ 1 │ 4 │ 5 │ ╭───┬────────────────╮ │\
│ │ │ │ │ 0 │ 1 │ │\
│ │ │ │ │ 1 │ 2 │ │\
│ │ │ │ │ 2 │ [list 3 items] │ │\
│ │ │ │ ╰───┴────────────────╯ │\
╰───┴───┴───┴────────────────────────╯"
);
}
#[test]
fn table_expand_deep_1() {
let actual =
nu!("[[a b, c]; [1 2 3] [4 5 [1 2 [1 2 3]]]] | table --width=80 --expand --expand-deep=0");
assert_eq!(
actual.out,
"╭───┬───┬───┬────────────────╮\
│ # │ a │ b │ c │\
├───┼───┼───┼────────────────┤\
│ 0 │ 1 │ 2 │ 3 │\
│ 1 │ 4 │ 5 │ [list 3 items] │\
╰───┴───┴───┴────────────────╯"
);
}
#[test]
fn table_expand_flatten_0() {
let actual =
nu!("[[a b, c]; [1 2 3] [4 5 [1 2 [1 1 1]]]] | table --width=80 --expand --flatten ");
assert_eq!(
actual.out,
"╭───┬───┬───┬───────────────╮\
│ # │ a │ b │ c │\
├───┼───┼───┼───────────────┤\
│ 0 │ 1 │ 2 │ 3 │\
│ 1 │ 4 │ 5 │ ╭───┬───────╮ │\
│ │ │ │ │ 0 │ 1 │ │\
│ │ │ │ │ 1 │ 2 │ │\
│ │ │ │ │ 2 │ 1 1 1 │ │\
│ │ │ │ ╰───┴───────╯ │\
╰───┴───┴───┴───────────────╯"
);
}
#[test]
fn table_expand_flatten_1() {
let actual = nu!(
"[[a b, c]; [1 2 3] [4 5 [1 2 [1 1 1]]]] | table --width=80 --expand --flatten --flatten-separator=,"
);
assert_eq!(
actual.out,
"╭───┬───┬───┬───────────────╮\
│ # │ a │ b │ c │\
├───┼───┼───┼───────────────┤\
│ 0 │ 1 │ 2 │ 3 │\
│ 1 │ 4 │ 5 │ ╭───┬───────╮ │\
│ │ │ │ │ 0 │ 1 │ │\
│ │ │ │ │ 1 │ 2 │ │\
│ │ │ │ │ 2 │ 1,1,1 │ │\
│ │ │ │ ╰───┴───────╯ │\
╰───┴───┴───┴───────────────╯"
);
}
#[test]
fn table_expand_flatten_and_deep_1() {
let actual = nu!(
"[[a b, c]; [1 2 3] [4 5 [1 2 [1 [1 1 1] 1]]]] | table --width=80 --expand --expand-deep=2 --flatten --flatten-separator=,"
);
assert_eq!(
actual.out,
"╭───┬───┬───┬────────────────────────────────╮\
│ # │ a │ b │ c │\
├───┼───┼───┼────────────────────────────────┤\
│ 0 │ 1 │ 2 │ 3 │\
│ 1 │ 4 │ 5 │ ╭───┬────────────────────────╮ │\
│ │ │ │ │ 0 │ 1 │ │\
│ │ │ │ │ 1 │ 2 │ │\
│ │ │ │ │ 2 │ ╭───┬────────────────╮ │ │\
│ │ │ │ │ │ │ 0 │ 1 │ │ │\
│ │ │ │ │ │ │ 1 │ [list 3 items] │ │ │\
│ │ │ │ │ │ │ 2 │ 1 │ │ │\
│ │ │ │ │ │ ╰───┴────────────────╯ │ │\
│ │ │ │ ╰───┴────────────────────────╯ │\
╰───┴───┴───┴────────────────────────────────╯"
);
}
#[test]
fn table_expand_record_0() {
let actual = nu!("[{c: {d: 1}}] | table --width=80 --expand");
assert_eq!(
actual.out,
"╭───┬───────────╮\
│ # │ c │\
├───┼───────────┤\
│ 0 │ ╭───┬───╮ │\
│ │ │ d │ 1 │ │\
│ │ ╰───┴───╯ │\
╰───┴───────────╯"
);
}
#[test]
fn table_expand_record_1() {
let actual =
nu!("[[a b, c]; [1 2 3] [4 5 [1 2 {a: 123, b: 234, c: 345}]]] | table --width=80 --expand");
assert_eq!(
actual.out,
"╭───┬───┬───┬─────────────────────╮\
│ # │ a │ b │ c │\
├───┼───┼───┼─────────────────────┤\
│ 0 │ 1 │ 2 │ 3 │\
│ 1 │ 4 │ 5 │ ╭───┬─────────────╮ │\
│ │ │ │ │ 0 │ 1 │ │\
│ │ │ │ │ 1 │ 2 │ │\
│ │ │ │ │ 2 │ ╭───┬─────╮ │ │\
│ │ │ │ │ │ │ a │ 123 │ │ │\
│ │ │ │ │ │ │ b │ 234 │ │ │\
│ │ │ │ │ │ │ c │ 345 │ │ │\
│ │ │ │ │ │ ╰───┴─────╯ │ │\
│ │ │ │ ╰───┴─────────────╯ │\
╰───┴───┴───┴─────────────────────╯"
);
}
#[test]
fn table_expand_record_2() {
let structure = "{
field1: [ a, b, c ],
field2: [ 123, 234, 345 ],
field3: [ [ head1, head2, head3 ]; [ 1 2 3 ] [ 79 79 79 ] [ { f1: 'a string', f2: 1000 }, 1, 2 ] ],
field4: { f1: 1, f2: 3, f3: { f1: f1, f2: f2, f3: f3 } }
}";
let actual = nu!(format!("{structure} | table --width=80 --expand"));
assert_eq!(
actual.out,
"╭────────┬───────────────────────────────────────────╮\
│ │ ╭───┬───╮ │\
│ field1 │ │ 0 │ a │ │\
│ │ │ 1 │ b │ │\
│ │ │ 2 │ c │ │\
│ │ ╰───┴───╯ │\
│ │ ╭───┬─────╮ │\
│ field2 │ │ 0 │ 123 │ │\
│ │ │ 1 │ 234 │ │\
│ │ │ 2 │ 345 │ │\
│ │ ╰───┴─────╯ │\
│ │ ╭───┬───────────────────┬───────┬───────╮ │\
│ field3 │ │ # │ head1 │ head2 │ head3 │ │\
│ │ ├───┼───────────────────┼───────┼───────┤ │\
│ │ │ 0 │ 1 │ 2 │ 3 │ │\
│ │ │ 1 │ 79 │ 79 │ 79 │ │\
│ │ │ 2 │ ╭────┬──────────╮ │ 1 │ 2 │ │\
│ │ │ │ │ f1 │ a string │ │ │ │ │\
│ │ │ │ │ f2 │ 1000 │ │ │ │ │\
│ │ │ │ ╰────┴──────────╯ │ │ │ │\
│ │ ╰───┴───────────────────┴───────┴───────╯ │\
│ │ ╭────┬─────────────╮ │\
│ field4 │ │ f1 │ 1 │ │\
│ │ │ f2 │ 3 │ │\
│ │ │ │ ╭────┬────╮ │ │\
│ │ │ f3 │ │ f1 │ f1 │ │ │\
│ │ │ │ │ f2 │ f2 │ │ │\
│ │ │ │ │ f3 │ f3 │ │ │\
│ │ │ │ ╰────┴────╯ │ │\
│ │ ╰────┴─────────────╯ │\
╰────────┴───────────────────────────────────────────╯"
);
}
#[test]
#[cfg(not(windows))]
fn external_with_too_much_stdout_should_not_hang_nu() {
use nu_test_support::fs::Stub::FileWithContent;
use nu_test_support::playground::Playground;
Playground::setup("external with too much stdout", |dirs, sandbox| {
let bytes: usize = 81920;
let mut large_file_body = String::with_capacity(bytes);
for _ in 0..bytes {
large_file_body.push('a');
}
sandbox.with_files(&[FileWithContent("a_large_file.txt", &large_file_body)]);
let actual = nu!(cwd: dirs.test(), "
cat a_large_file.txt | table --width=80
");
assert_eq!(actual.out, large_file_body);
})
}
#[test]
fn table_pagging_row_offset_overlap() {
let actual = nu!("0..1000");
assert_eq!(
actual.out,
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/error_make.rs | crates/nu-command/tests/commands/error_make.rs | use nu_test_support::nu;
// Required columns present
#[test]
fn error_make_empty() {
let actual = nu!("error make {}");
assert!(actual.err.contains("Cannot find column 'msg'"));
}
#[test]
fn error_make_no_label_text() {
let actual = nu!("error make {msg:no_label_text,label:{span:{start:1,end:1}}}");
assert!(actual.err.contains("Error: no_label_text"));
}
#[test]
fn error_label_works() {
let actual = nu!("error make {msg:foo,label:{text:unseen}}");
assert!(actual.err.contains(": unseen"));
}
#[test]
fn error_labels_list_works() {
// Intentionally no space so this gets the main label bits
let actual = nu!("error make {msg:foo,labels:[{text:unseen},{text:hidden}]}");
assert!(actual.err.contains(": unseen"));
assert!(actual.err.contains(": hidden"));
}
#[test]
fn no_span_if_unspanned() {
let actual = nu!("error make -u {msg:foo label:{text:unseen}}");
assert!(!actual.err.contains("unseen"));
}
#[test]
fn error_start_bigger_than_end_should_fail() {
let actual = nu!("
error make {
msg: foo
label: {
text: bar
span: {start: 456 end: 123}
}
}
");
assert!(actual.err.contains("Unable to parse Span."));
assert!(actual.err.contains("`end` must not be less than `start`"));
}
#[test]
fn error_url_works() {
let actual = nu!("error make {msg:bar,url:'https://example.com'}");
assert!(
actual
.err
.contains("For more details, see:\nhttps://example.com")
);
}
#[test]
fn error_code_works() {
let actual = nu!("error make {msg:bar,code:'foo::bar'}");
assert!(actual.err.contains("diagnostic code: foo::bar"));
}
#[test]
fn error_check_deep() {
let actual = nu!("error make {msg:foo,inner:[{msg:bar}]}");
assert!(actual.err.contains("Error: bar"));
assert!(actual.err.contains("Error: foo"));
}
#[test]
fn error_chained() {
let actual = nu!("try {
error make {msg:foo,inner:[{msg:bar}]}
} catch {
error make {msg:baz}
}");
assert!(actual.err.contains("Error: foo"));
assert!(actual.err.contains("Error: baz"));
assert!(actual.err.contains("Error: bar"));
}
#[test]
fn error_bad_label() {
let actual = nu!("
error make {
msg:foo
inner:[{msg:bar}]
labels:foobar
}
");
assert!(!actual.err.contains("Error: foo"));
assert!(
actual
.err
.contains("diagnostic code: nu::shell::cant_convert")
);
}
#[test]
fn check_help_line() {
let actual = nu!("error make {msg:foo help: `Custom help line`}");
assert!(actual.err.contains("Custom help line"));
}
#[test]
fn error_simple_chain() {
let actual = nu!("
try {
error make foo
} catch {
error make bar
}
");
assert!(actual.err.contains("Error: foo"));
assert!(actual.err.contains("Error: bar"));
}
#[test]
fn error_simple_string() {
let actual = nu!("error make foo");
assert!(actual.err.contains("Error: foo"));
}
#[test]
fn error_source() {
let actual = nu!("error make {
msg: foo
src: {text: 'foo bar'}
labels: [{text: bar span: {start: 0 end: 3} }]
}");
assert!(actual.err.contains("snippet line 1: foo bar"))
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/last.rs | crates/nu-command/tests/commands/last.rs | use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn gets_the_last_row() {
let actual = nu!(
cwd: "tests/fixtures/formats",
"ls | sort-by name | last 1 | get name.0 | str trim"
);
assert_eq!(actual.out, "utf16.ini");
}
#[test]
fn gets_last_rows_by_amount() {
Playground::setup("last_test_1", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("los.txt"),
EmptyFile("tres.txt"),
EmptyFile("amigos.txt"),
EmptyFile("arepas.clu"),
]);
let actual = nu!(cwd: dirs.test(), "ls | last 3 | length");
assert_eq!(actual.out, "3");
})
}
#[test]
fn gets_last_row_when_no_amount_given() {
Playground::setup("last_test_2", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("caballeros.txt"), EmptyFile("arepas.clu")]);
// FIXME: We should probably change last to return a one row table instead of a record here
let actual = nu!(cwd: dirs.test(), "ls | last | values | length");
assert_eq!(actual.out, "4");
})
}
#[test]
fn requests_more_rows_than_table_has() {
let actual = nu!("[date] | last 50 | length");
assert_eq!(actual.out, "1");
}
#[test]
fn gets_last_row_as_list_when_amount_given() {
let actual = nu!("[1, 2, 3] | last 1 | describe");
assert_eq!(actual.out, "list<int>");
}
#[test]
fn gets_last_bytes() {
let actual = nu!("(0x[aa bb cc] | last 2) == 0x[bb cc]");
assert_eq!(actual.out, "true");
}
#[test]
fn gets_last_byte() {
let actual = nu!("0x[aa bb cc] | last");
assert_eq!(actual.out, "204");
}
#[test]
fn gets_last_bytes_from_stream() {
let actual = nu!("(1..10 | each { 0x[aa bb cc] } | bytes collect | last 2) == 0x[bb cc]");
assert_eq!(actual.out, "true");
}
#[test]
fn gets_last_byte_from_stream() {
let actual = nu!("1..10 | each { 0x[aa bb cc] } | bytes collect | last");
assert_eq!(actual.out, "204");
}
#[test]
fn last_errors_on_negative_index() {
let actual = nu!("[1, 2, 3] | last -2");
assert!(actual.err.contains("use a positive value"));
}
#[test]
fn fail_on_non_iterator() {
let actual = nu!("1 | last");
assert!(actual.err.contains("command doesn't support"));
}
#[test]
fn errors_on_empty_list_when_no_rows_given_in_strict_mode() {
let actual = nu!("[] | last --strict");
assert!(actual.err.contains("index too large"));
}
#[test]
fn does_not_error_on_empty_list_when_no_rows_given() {
let actual = nu!("[] | last | describe");
assert!(actual.out.contains("nothing"));
}
#[test]
fn returns_nothing_on_empty_list_when_no_rows_given() {
let actual = nu!("[] | last");
assert_eq!(actual.out, "");
}
#[test]
fn returns_d_on_empty_list_when_no_rows_given_with_default() {
let actual = nu!("[a b] | where $it == 'c' | last | default 'd'");
assert_eq!(actual.out, "d");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/glob.rs | crates/nu-command/tests/commands/glob.rs | use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use rstest::rstest;
use std::path::{Path, PathBuf};
#[test]
fn empty_glob_pattern_triggers_error() {
Playground::setup("glob_test_1", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
]);
let actual = nu!(
cwd: dirs.test(),
"glob ''",
);
assert!(actual.err.contains("must not be empty"));
})
}
#[test]
fn nonempty_glob_lists_matching_paths() {
Playground::setup("glob_sanity_star", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
]);
let actual = nu!(
cwd: dirs.test(),
"glob '*' | length",
);
assert_eq!(actual.out, "3");
})
}
#[test]
fn glob_subdirs() {
Playground::setup("glob_subdirs", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
]);
sandbox.mkdir("children");
sandbox.within("children").with_files(&[
EmptyFile("timothy.txt"),
EmptyFile("tiffany.txt"),
EmptyFile("trish.txt"),
]);
let actual = nu!(
cwd: dirs.test(),
"glob '**/*' | length",
);
assert_eq!(
actual.out, "8",
"count must be 8 due to 6 files and 2 folders, including the cwd"
);
})
}
#[test]
fn glob_subdirs_ignore_dirs() {
Playground::setup("glob_subdirs_ignore_directories", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
]);
sandbox.mkdir("children");
sandbox.within("children").with_files(&[
EmptyFile("timothy.txt"),
EmptyFile("tiffany.txt"),
EmptyFile("trish.txt"),
]);
let actual = nu!(
cwd: dirs.test(),
"glob '**/*' -D | length",
);
assert_eq!(
actual.out, "6",
"directory count must be 6, ignoring the cwd and the children folders"
);
})
}
#[test]
fn glob_ignore_files() {
Playground::setup("glob_ignore_files", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
]);
sandbox.mkdir("children");
sandbox.within("children").with_files(&[
EmptyFile("timothy.txt"),
EmptyFile("tiffany.txt"),
EmptyFile("trish.txt"),
]);
let actual = nu!(
cwd: dirs.test(),
"glob '*' -F | length",
);
assert_eq!(
actual.out, "1",
"should only find one folder; ignoring cwd, files, subfolders"
);
})
}
// clone of fs::create_file_at removing the parent panic, whose purpose I do not grok.
pub fn create_file_at(full_path: impl AsRef<Path>) -> Result<(), std::io::Error> {
let full_path = full_path.as_ref();
std::fs::write(full_path, b"fake data")
}
// playground has root directory and subdirectories foo and foo/bar to play with
// specify all test files relative to root directory.
// OK to use fwd slash in paths, they're hacked to OS dir separator when needed (windows)
#[rstest]
#[case(".", r#"'*z'"#, &["ablez", "baker", "charliez"], &["ablez", "charliez"], "simple glob")]
#[case(".", r#"'qqq'"#, &["ablez", "baker", "charliez"], &[], "glob matches none")]
#[case("foo/bar", r"'*[\]}]*'", &[r#"foo/bar/ab}le"#, "foo/bar/baker", r#"foo/bar/cha]rlie"#], &[r#"foo/bar/ab}le"#, r#"foo/bar/cha]rlie"#], "glob has quoted metachars")]
#[case("foo/bar", r#"'../*'"#, &["foo/able", "foo/bar/baker", "foo/charlie"], &["foo/able", "foo/bar", "foo/charlie"], "glob matches files in parent")]
#[case("foo", r#"'./{a,b}*'"#, &["foo/able", "foo/bar/baker", "foo/charlie"], &["foo/able", "foo/bar"], "glob with leading ./ matches peer files")]
fn glob_files_in_parent(
#[case] wd: &str,
#[case] glob: &str,
#[case] ini: &[&str],
#[case] exp: &[&str],
#[case] tag: &str,
) {
Playground::setup("glob_test", |dirs, sandbox| {
sandbox.within("foo").within("bar");
let working_directory = &dirs.test().join(wd);
for f in ini {
create_file_at(dirs.test().join(f)).expect("couldn't create file");
}
let actual = nu!(
cwd: working_directory,
format!(r#"glob {glob} | sort | str join " ""#)
);
let mut expected: Vec<String> = vec![];
for e in exp {
expected.push(
dirs.test()
.join(PathBuf::from(e)) // sadly, does *not" convert "foo/bar" to "foo\\bar" on Windows.
.to_string_lossy()
.to_string(),
);
}
let expected = expected
.join(" ")
.replace('/', std::path::MAIN_SEPARATOR_STR);
assert_eq!(actual.out, expected, "\n test: {tag}");
});
}
#[test]
fn glob_follow_symlinks() {
Playground::setup("glob_follow_symlinks", |dirs, sandbox| {
// Create a directory with some files
sandbox.mkdir("target_dir");
sandbox
.within("target_dir")
.with_files(&[EmptyFile("target_file.txt")]);
let target_dir = dirs.test().join("target_dir");
let symlink_path = dirs.test().join("symlink_dir");
#[cfg(unix)]
std::os::unix::fs::symlink(target_dir, &symlink_path).expect("Failed to create symlink");
#[cfg(windows)]
std::os::windows::fs::symlink_dir(target_dir, &symlink_path)
.expect("Failed to create symlink");
// on some systems/filesystems, symlinks are followed by default
// on others (like Linux /sys), they aren't
// Test that with the --follow-symlinks flag, files are found for sure
let with_flag = nu!(
cwd: dirs.test(),
"glob 'symlink_dir/*.txt' --follow-symlinks | length",
);
assert_eq!(
with_flag.out, "1",
"Should find file with --follow-symlinks flag"
);
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/default.rs | crates/nu-command/tests/commands/default.rs | use nu_test_support::{fs::Stub::EmptyFile, nu, playground::Playground};
#[test]
fn adds_row_data_if_column_missing() {
let sample = r#"{
"amigos": [
{"name": "Yehuda"},
{"name": "JT", "rusty_luck": 0},
{"name": "Andres", "rusty_luck": 0},
{"name": "Michael", "rusty_luck": []},
{"name": "Darren", "rusty_luck": {}},
{"name": "Stefan", "rusty_luck": ""},
{"name": "GorbyPuff"}
]
}"#;
let actual = nu!(format!(
"
{sample}
| get amigos
| default 1 rusty_luck
| where rusty_luck == 1
| length
"
));
assert_eq!(actual.out, "2");
}
#[test]
fn default_after_empty_filter() {
let actual = nu!("[a b] | where $it == 'c' | get -o 0 | default 'd'");
assert_eq!(actual.out, "d");
}
#[test]
fn keeps_nulls_in_lists() {
let actual = nu!(r#"[null, 2, 3] | default [] | to json -r"#);
assert_eq!(actual.out, "[null,2,3]");
}
#[test]
fn replaces_null() {
let actual = nu!(r#"null | default 1"#);
assert_eq!(actual.out, "1");
}
#[test]
fn adds_row_data_if_column_missing_or_empty() {
let sample = r#"{
"amigos": [
{"name": "Yehuda"},
{"name": "JT", "rusty_luck": 0},
{"name": "Andres", "rusty_luck": 0},
{"name": "Michael", "rusty_luck": []},
{"name": "Darren", "rusty_luck": {}},
{"name": "Stefan", "rusty_luck": ""},
{"name": "GorbyPuff"}
]
}"#;
let actual = nu!(format!(
"
{sample}
| get amigos
| default -e 1 rusty_luck
| where rusty_luck == 1
| length
"
));
assert_eq!(actual.out, "5");
}
#[test]
fn replace_empty_string() {
let actual = nu!(r#"'' | default -e foo"#);
assert_eq!(actual.out, "foo");
}
#[test]
fn do_not_replace_empty_string() {
let actual = nu!(r#"'' | default 1"#);
assert_eq!(actual.out, "");
}
#[test]
fn replace_empty_list() {
let actual = nu!(r#"[] | default -e foo"#);
assert_eq!(actual.out, "foo");
}
#[test]
fn do_not_replace_empty_list() {
let actual = nu!(r#"[] | default 1 | length"#);
assert_eq!(actual.out, "0");
}
#[test]
fn replace_empty_record() {
let actual = nu!(r#"{} | default -e foo"#);
assert_eq!(actual.out, "foo");
}
#[test]
fn do_not_replace_empty_record() {
let actual = nu!(r#"{} | default {a:5} | columns | length"#);
assert_eq!(actual.out, "0");
}
#[test]
fn replace_empty_list_stream() {
// This is specific for testing ListStreams when empty behave like other empty values
Playground::setup("glob_empty_list", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
]);
let actual = nu!(
cwd: dirs.test(),
"glob ? | default -e void",
);
assert_eq!(actual.out, "void");
})
}
#[test]
fn do_not_replace_non_empty_list_stream() {
// This is specific for testing ListStreams when empty behave like other empty values
Playground::setup("glob_non_empty_list", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jt.rs"),
EmptyFile("andres.txt"),
]);
let actual = nu!(
cwd: dirs.test(),
"glob '*.txt' | default -e void | length",
);
assert_eq!(actual.out, "2");
})
}
#[test]
fn closure_eval_simple() {
let actual = nu!(r#"null | default { 1 }"#);
assert_eq!(actual.out, "1");
}
#[test]
fn closure_eval_complex() {
let actual = nu!(r#"null | default { seq 1 5 | math sum }"#);
assert_eq!(actual.out, "15");
}
#[test]
fn closure_eval_is_lazy() {
let actual = nu!(r#"1 | default { error make -u {msg: foo} }"#);
assert_eq!(actual.out, "1");
}
#[test]
fn column_closure_eval_is_lazy() {
let actual = nu!(r#"{a: 1} | default { error make -u {msg: foo} } a | get a"#);
assert_eq!(actual.out, "1");
}
#[test]
fn closure_eval_replace_empty_string() {
let actual = nu!(r#"'' | default --empty { 1 }"#);
assert_eq!(actual.out, "1");
}
#[test]
fn closure_eval_do_not_replace_empty_string() {
let actual = nu!(r#"'' | default { 1 }"#);
assert_eq!(actual.out, "");
}
#[test]
fn closure_eval_replace_empty_list() {
let actual = nu!(r#"[] | default --empty { 1 }"#);
assert_eq!(actual.out, "1");
}
#[test]
fn closure_eval_do_not_replace_empty_list() {
let actual = nu!(r#"[] | default { 1 } | length"#);
assert_eq!(actual.out, "0");
}
#[test]
fn closure_eval_replace_empty_record() {
let actual = nu!(r#"{} | default --empty { 1 }"#);
assert_eq!(actual.out, "1");
}
#[test]
fn closure_eval_do_not_replace_empty_record() {
let actual = nu!(r#"{} | default { 1 } | columns | length"#);
assert_eq!(actual.out, "0");
}
#[test]
fn closure_eval_add_missing_column_record() {
let actual = nu!(r#"
{a: 1} | default { 2 } b | get b
"#);
assert_eq!(actual.out, "2");
}
#[test]
fn closure_eval_add_missing_column_table() {
let actual = nu!(r#"
[{a: 1, b: 2}, {b: 4}] | default { 3 } a | get a | to json -r
"#);
assert_eq!(actual.out, "[1,3]");
}
#[test]
fn closure_eval_replace_empty_column() {
let actual = nu!(r#"{a: ''} | default -e { 1 } a | get a"#);
assert_eq!(actual.out, "1");
}
#[test]
fn replace_multiple_columns() {
let actual = nu!(r#"{a: ''} | default -e 1 a b | values | to json -r"#);
assert_eq!(actual.out, "[1,1]");
}
#[test]
fn return_closure_value() {
let actual = nu!(r#"null | default { {||} }"#);
assert!(actual.out.starts_with("closure"));
}
#[test]
fn lazy_output_streams() {
let actual = nu!(r#"default { nu --testbin cococo 'hello' } | describe"#);
assert!(actual.out.contains("byte stream"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/seq_char.rs | crates/nu-command/tests/commands/seq_char.rs | use nu_test_support::nu;
#[test]
fn fails_when_first_arg_is_multiple_chars() {
let actual = nu!("seq char aa z");
assert!(
actual
.err
.contains("input should be a single ASCII character")
);
}
#[test]
fn fails_when_second_arg_is_multiple_chars() {
let actual = nu!("seq char a zz");
assert!(
actual
.err
.contains("input should be a single ASCII character")
);
}
#[test]
fn generates_sequence_from_a_to_e() {
let actual = nu!("seq char a e | str join ''");
assert_eq!(actual.out, "abcde");
}
#[test]
fn generates_sequence_from_e_to_a() {
let actual = nu!("seq char e a | str join ''");
assert_eq!(actual.out, "edcba");
}
#[test]
fn fails_when_non_ascii_character_is_used_in_first_arg() {
let actual = nu!("seq char ñ z");
assert!(
actual
.err
.contains("input should be a single ASCII character")
);
}
#[test]
fn fails_when_non_ascii_character_is_used_in_second_arg() {
let actual = nu!("seq char a ñ");
assert!(
actual
.err
.contains("input should be a single ASCII character")
);
}
#[test]
fn joins_sequence_with_pipe() {
let actual = nu!("seq char a e | str join '|'");
assert_eq!(actual.out, "a|b|c|d|e");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/into_datetime.rs | crates/nu-command/tests/commands/into_datetime.rs | use nu_test_support::nu;
// Tests happy paths
#[test]
fn into_datetime_from_record_cell_path() {
let actual = nu!(r#"{d: '2021'} | into datetime d"#);
assert!(actual.out.contains("years ago"));
}
#[test]
fn into_datetime_from_record() {
let actual = nu!(
r#"{year: 2023, month: 1, day: 2, hour: 3, minute: 4, second: 5, millisecond: 6, microsecond: 7, nanosecond: 8, timezone: '+01:00'} | into datetime | into record"#
);
let expected = nu!(
r#"{year: 2023, month: 1, day: 2, hour: 3, minute: 4, second: 5, millisecond: 6, microsecond: 7, nanosecond: 8, timezone: '+01:00'}"#
);
assert_eq!(expected.out, actual.out);
}
#[test]
fn into_datetime_from_record_very_old() {
let actual = nu!(r#"{year: -100, timezone: '+02:00'} | into datetime | into record"#);
let expected = nu!(
r#"{year: -100, month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0, microsecond: 0, nanosecond: 0, timezone: '+02:00'}"#
);
assert_eq!(expected.out, actual.out);
}
#[test]
fn into_datetime_from_record_defaults() {
let actual = nu!(r#"{year: 2025, timezone: '+02:00'} | into datetime | into record"#);
let expected = nu!(
r#"{year: 2025, month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0, microsecond: 0, nanosecond: 0, timezone: '+02:00'}"#
);
assert_eq!(expected.out, actual.out);
}
#[test]
fn into_datetime_from_record_round_trip() {
let actual = nu!(
r#"(1743348798 | into datetime | into record | into datetime | into int) == 1743348798"#
);
assert!(actual.out.contains("true"));
}
#[test]
fn into_datetime_table_column() {
let actual = nu!(r#"[[date]; ["2022-01-01"] ["2023-01-01"]] | into datetime date"#);
assert!(actual.out.contains(" ago"));
}
// Tests error paths
#[test]
fn into_datetime_from_record_fails_with_wrong_type() {
let actual = nu!(r#"{year: '2023'} | into datetime"#);
assert!(
actual
.err
.contains("nu::shell::only_supports_this_input_type")
);
}
#[test]
fn into_datetime_from_record_fails_with_invalid_date_time_values() {
let actual = nu!(r#"{year: 2023, month: 13} | into datetime"#);
assert!(actual.err.contains("nu::shell::incorrect_value"));
}
#[test]
fn into_datetime_from_record_fails_with_invalid_timezone() {
let actual = nu!(r#"{year: 2023, timezone: '+100:00'} | into datetime"#);
assert!(actual.err.contains("nu::shell::incorrect_value"));
}
// Tests invalid usage
#[test]
fn into_datetime_from_record_fails_with_unknown_key() {
let actual = nu!(r#"{year: 2023, unknown: 1} | into datetime"#);
assert!(actual.err.contains("nu::shell::unsupported_input"));
}
#[test]
fn into_datetime_from_record_incompatible_with_format_flag() {
let actual = nu!(
r#"{year: 2023, month: 1, day: 2, hour: 3, minute: 4, second: 5} | into datetime --format ''"#
);
assert!(actual.err.contains("nu::shell::incompatible_parameters"));
}
#[test]
fn into_datetime_from_record_incompatible_with_timezone_flag() {
let actual = nu!(
r#"{year: 2023, month: 1, day: 2, hour: 3, minute: 4, second: 5} | into datetime --timezone UTC"#
);
assert!(actual.err.contains("nu::shell::incompatible_parameters"));
}
#[test]
fn into_datetime_from_record_incompatible_with_offset_flag() {
let actual = nu!(
r#"{year: 2023, month: 1, day: 2, hour: 3, minute: 4, second: 5} | into datetime --offset 1"#
);
assert!(actual.err.contains("nu::shell::incompatible_parameters"));
}
#[test]
fn test_j_q_format_specifiers_into_datetime() {
let actual = nu!(r#"
"20211022_200012" | into datetime --format '%J_%Q'
"#);
// Check for the date components - the exact output format may vary
assert!(actual.out.contains("22 Oct 2021") || actual.out.contains("2021-10-22"));
assert!(actual.out.contains("20:00:12"));
}
#[test]
fn test_j_q_format_specifiers_round_trip() {
let actual = nu!(r#"
"2021-10-22 20:00:12 +01:00" | format date '%J_%Q' | into datetime --format '%J_%Q' | format date '%J_%Q'
"#);
assert_eq!(actual.out, "20211022_200012");
}
#[test]
fn test_j_format_specifier_date_only() {
let actual = nu!(r#"
"20211022" | into datetime --format '%J'
"#);
// Check for the date components - time should default to midnight
assert!(actual.out.contains("22 Oct 2021") || actual.out.contains("2021-10-22"));
assert!(actual.out.contains("00:00:00"));
}
#[test]
fn test_q_format_specifier_time_only() {
let actual = nu!(r#"
"200012" | into datetime --format '%Q'
"#);
// Check for the time components - should parse as time with default date
assert!(actual.out.contains("20:00:12"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/find.rs | crates/nu-command/tests/commands/find.rs | use nu_test_support::nu;
#[test]
fn find_with_list_search_with_string() {
let actual = nu!("[moe larry curly] | find moe | get 0");
let actual_no_highlight = nu!("[moe larry curly] | find --no-highlight moe | get 0");
assert_eq!(
actual.out,
"\u{1b}[39m\u{1b}[0m\u{1b}[41;39mmoe\u{1b}[0m\u{1b}[39m\u{1b}[0m"
);
assert_eq!(actual_no_highlight.out, "moe");
}
#[test]
fn find_with_list_search_with_char() {
let actual = nu!("[moe larry curly] | find l | to json -r");
let actual_no_highlight = nu!("[moe larry curly] | find --no-highlight l | to json -r");
assert_eq!(
actual.out,
"[\"\\u001b[39m\\u001b[0m\\u001b[41;39ml\\u001b[0m\\u001b[39marry\\u001b[0m\",\"\\u001b[39mcur\\u001b[0m\\u001b[41;39ml\\u001b[0m\\u001b[39my\\u001b[0m\"]"
);
assert_eq!(actual_no_highlight.out, "[\"larry\",\"curly\"]");
}
#[test]
fn find_with_bytestream_search_with_char() {
let actual = nu!(
"\"ABC\" | save foo.txt; let res = open foo.txt | find -i abc; rm foo.txt; $res | get 0"
);
let actual_no_highlight = nu!(
"\"ABC\" | save foo.txt; let res = open foo.txt | find -i --no-highlight abc; rm foo.txt; $res | get 0"
);
assert_eq!(
actual.out,
"\u{1b}[39m\u{1b}[0m\u{1b}[41;39mABC\u{1b}[0m\u{1b}[39m\u{1b}[0m"
);
assert_eq!(actual_no_highlight.out, "ABC");
}
#[test]
fn find_with_list_search_with_number() {
let actual = nu!("[1 2 3 4 5] | find 3 | get 0");
let actual_no_highlight = nu!("[1 2 3 4 5] | find --no-highlight 3 | get 0");
assert_eq!(actual.out, "3");
assert_eq!(actual_no_highlight.out, "3");
}
#[test]
fn find_with_string_search_with_string() {
let actual = nu!("echo Cargo.toml | find toml");
let actual_no_highlight = nu!("echo Cargo.toml | find --no-highlight toml");
assert_eq!(
actual.out,
"\u{1b}[39mCargo.\u{1b}[0m\u{1b}[41;39mtoml\u{1b}[0m\u{1b}[39m\u{1b}[0m"
);
assert_eq!(actual_no_highlight.out, "Cargo.toml");
}
#[test]
fn find_with_string_search_with_string_not_found() {
let actual = nu!("[moe larry curly] | find shemp | is-empty");
let actual_no_highlight = nu!("[moe larry curly] | find --no-highlight shemp | is-empty");
assert_eq!(actual.out, "true");
assert_eq!(actual_no_highlight.out, "true");
}
#[test]
fn find_with_filepath_search_with_string() {
let actual =
nu!(r#"["amigos.txt","arepas.clu","los.txt","tres.txt"] | find arep | to json -r"#);
let actual_no_highlight = nu!(
r#"["amigos.txt","arepas.clu","los.txt","tres.txt"] | find --no-highlight arep | to json -r"#
);
assert_eq!(
actual.out,
"[\"\\u001b[39m\\u001b[0m\\u001b[41;39marep\\u001b[0m\\u001b[39mas.clu\\u001b[0m\"]"
);
assert_eq!(actual_no_highlight.out, "[\"arepas.clu\"]");
}
#[test]
fn find_with_filepath_search_with_multiple_patterns() {
let actual =
nu!(r#"["amigos.txt","arepas.clu","los.txt","tres.txt"] | find arep ami | to json -r"#);
let actual_no_highlight = nu!(
r#"["amigos.txt","arepas.clu","los.txt","tres.txt"] | find --no-highlight arep ami | to json -r"#
);
assert_eq!(
actual.out,
"[\"\\u001b[39m\\u001b[0m\\u001b[41;39mami\\u001b[0m\\u001b[39mgos.txt\\u001b[0m\",\"\\u001b[39m\\u001b[0m\\u001b[41;39marep\\u001b[0m\\u001b[39mas.clu\\u001b[0m\"]"
);
assert_eq!(actual_no_highlight.out, "[\"amigos.txt\",\"arepas.clu\"]");
}
#[test]
fn find_takes_into_account_linebreaks_in_string() {
let actual = nu!(r#""atest\nanothertest\nnohit\n" | find a | length"#);
let actual_no_highlight =
nu!(r#""atest\nanothertest\nnohit\n" | find --no-highlight a | length"#);
assert_eq!(actual.out, "2");
assert_eq!(actual_no_highlight.out, "2");
}
#[test]
fn find_with_regex_in_table_keeps_row_if_one_column_matches() {
let actual = nu!(
"[[name nickname]; [Maurice moe] [Laurence larry]] | find --regex ce | get name | to json -r"
);
let actual_no_highlight = nu!(
"[[name nickname]; [Maurice moe] [Laurence larry]] | find --no-highlight --regex ce | get name | to json -r"
);
assert_eq!(
actual.out,
r#"["\u001b[39mMauri\u001b[0m\u001b[41;39mce\u001b[0m\u001b[39m\u001b[0m","\u001b[39mLauren\u001b[0m\u001b[41;39mce\u001b[0m\u001b[39m\u001b[0m"]"#
);
assert_eq!(actual_no_highlight.out, r#"["Maurice","Laurence"]"#);
}
#[test]
fn inverted_find_with_regex_in_table_keeps_row_if_none_of_the_columns_matches() {
let actual = nu!(
"[[name nickname]; [Maurice moe] [Laurence larry]] | find --regex moe --invert | get name | to json -r"
);
let actual_no_highlight = nu!(
"[[name nickname]; [Maurice moe] [Laurence larry]] | find --no-highlight --regex moe --invert | get name | to json -r"
);
assert_eq!(actual.out, r#"["Laurence"]"#);
assert_eq!(actual_no_highlight.out, r#"["Laurence"]"#);
}
#[test]
fn find_in_table_only_keep_rows_with_matches_on_selected_columns() {
let actual = nu!(
"[[name nickname]; [Maurice moe] [Laurence larry]] | find r --columns [nickname] | get name | to json -r"
);
let actual_no_highlight = nu!(
"[[name nickname]; [Maurice moe] [Laurence larry]] | find r --no-highlight --columns [nickname] | get name | to json -r"
);
assert!(actual.out.contains("Laurence"));
assert!(!actual.out.contains("Maurice"));
assert!(actual_no_highlight.out.contains("Laurence"));
assert!(!actual_no_highlight.out.contains("Maurice"));
}
#[test]
fn inverted_find_in_table_keeps_row_if_none_of_the_selected_columns_matches() {
let actual = nu!(
"[[name nickname]; [Maurice moe] [Laurence larry]] | find r --columns [nickname] --invert | get name | to json -r"
);
let actual_no_highlight = nu!(
"[[name nickname]; [Maurice moe] [Laurence larry]] | find r --no-highlight --columns [nickname] --invert | get name | to json -r"
);
assert_eq!(actual.out, r#"["Maurice"]"#);
assert_eq!(actual_no_highlight.out, r#"["Maurice"]"#);
}
#[test]
fn find_in_table_keeps_row_with_single_matched_and_keeps_other_columns() {
let actual = nu!(
"[[name nickname Age]; [Maurice moe 23] [Laurence larry 67] [William will 18]] | find Maurice"
);
let actual_no_highlight = nu!(
"[[name nickname Age]; [Maurice moe 23] [Laurence larry 67] [William will 18]] | find --no-highlight Maurice"
);
println!("{:?}", actual.out);
assert!(actual.out.contains("moe"));
assert!(actual.out.contains("Maurice"));
assert!(actual.out.contains("23"));
println!("{:?}", actual_no_highlight.out);
assert!(actual_no_highlight.out.contains("moe"));
assert!(actual_no_highlight.out.contains("Maurice"));
assert!(actual_no_highlight.out.contains("23"));
}
#[test]
fn find_in_table_keeps_row_with_multiple_matched_and_keeps_other_columns() {
let actual = nu!(
"[[name nickname Age]; [Maurice moe 23] [Laurence larry 67] [William will 18] [William bill 60]] | find moe William"
);
let actual_no_highlight = nu!(
"[[name nickname Age]; [Maurice moe 23] [Laurence larry 67] [William will 18] [William bill 60]] | find --no-highlight moe William"
);
println!("{:?}", actual.out);
assert!(actual.out.contains("moe"));
assert!(actual.out.contains("Maurice"));
assert!(actual.out.contains("23"));
assert!(actual.out.contains("William"));
assert!(actual.out.contains("will"));
assert!(actual.out.contains("18"));
assert!(actual.out.contains("bill"));
assert!(actual.out.contains("60"));
println!("{:?}", actual_no_highlight.out);
assert!(actual_no_highlight.out.contains("moe"));
assert!(actual_no_highlight.out.contains("Maurice"));
assert!(actual_no_highlight.out.contains("23"));
assert!(actual_no_highlight.out.contains("William"));
assert!(actual_no_highlight.out.contains("will"));
assert!(actual_no_highlight.out.contains("18"));
assert!(actual_no_highlight.out.contains("bill"));
assert!(actual_no_highlight.out.contains("60"));
}
#[test]
fn find_with_string_search_with_special_char_1() {
let actual = nu!("[[d]; [a?b] [a*b] [a{1}b] ] | find '?' | to json -r");
let actual_no_highlight =
nu!("[[d]; [a?b] [a*b] [a{1}b] ] | find --no-highlight '?' | to json -r");
assert_eq!(
actual.out,
"[{\"d\":\"\\u001b[39ma\\u001b[0m\\u001b[41;39m?\\u001b[0m\\u001b[39mb\\u001b[0m\"}]"
);
assert_eq!(actual_no_highlight.out, "[{\"d\":\"a?b\"}]");
}
#[test]
fn find_with_string_search_with_special_char_2() {
let actual = nu!("[[d]; [a?b] [a*b] [a{1}b]] | find '*' | to json -r");
let actual_no_highlight =
nu!("[[d]; [a?b] [a*b] [a{1}b]] | find --no-highlight '*' | to json -r");
assert_eq!(
actual.out,
"[{\"d\":\"\\u001b[39ma\\u001b[0m\\u001b[41;39m*\\u001b[0m\\u001b[39mb\\u001b[0m\"}]"
);
assert_eq!(actual_no_highlight.out, "[{\"d\":\"a*b\"}]");
}
#[test]
fn find_with_string_search_with_special_char_3() {
let actual = nu!("[[d]; [a?b] [a*b] [a{1}b] ] | find '{1}' | to json -r");
let actual_no_highlight =
nu!("[[d]; [a?b] [a*b] [a{1}b] ] | find --no-highlight '{1}' | to json -r");
assert_eq!(
actual.out,
"[{\"d\":\"\\u001b[39ma\\u001b[0m\\u001b[41;39m{1}\\u001b[0m\\u001b[39mb\\u001b[0m\"}]"
);
assert_eq!(actual_no_highlight.out, "[{\"d\":\"a{1}b\"}]");
}
#[test]
fn find_with_string_search_with_special_char_4() {
let actual = nu!("[{d: a?b} {d: a*b} {d: a{1}b} {d: a[]b}] | find '[' | to json -r");
let actual_no_highlight =
nu!("[{d: a?b} {d: a*b} {d: a{1}b} {d: a[]b}] | find --no-highlight '[' | to json -r");
assert_eq!(
actual.out,
"[{\"d\":\"\\u001b[39ma\\u001b[0m\\u001b[41;39m[\\u001b[0m\\u001b[39m]b\\u001b[0m\"}]"
);
assert_eq!(actual_no_highlight.out, "[{\"d\":\"a[]b\"}]");
}
#[test]
fn find_with_string_search_with_special_char_5() {
let actual = nu!("[{d: a?b} {d: a*b} {d: a{1}b} {d: a[]b}] | find ']' | to json -r");
let actual_no_highlight =
nu!("[{d: a?b} {d: a*b} {d: a{1}b} {d: a[]b}] | find --no-highlight ']' | to json -r");
assert_eq!(
actual.out,
"[{\"d\":\"\\u001b[39ma[\\u001b[0m\\u001b[41;39m]\\u001b[0m\\u001b[39mb\\u001b[0m\"}]"
);
assert_eq!(actual_no_highlight.out, "[{\"d\":\"a[]b\"}]");
}
#[test]
fn find_with_string_search_with_special_char_6() {
let actual = nu!("[{d: a?b} {d: a*b} {d: a{1}b} {d: a[]b}] | find '[]' | to json -r");
let actual_no_highlight =
nu!("[{d: a?b} {d: a*b} {d: a{1}b} {d: a[]b}] | find --no-highlight '[]' | to json -r");
assert_eq!(
actual.out,
"[{\"d\":\"\\u001b[39ma\\u001b[0m\\u001b[41;39m[]\\u001b[0m\\u001b[39mb\\u001b[0m\"}]"
);
assert_eq!(actual_no_highlight.out, "[{\"d\":\"a[]b\"}]");
}
#[test]
fn find_in_nested_list_dont_match_bracket() {
let actual = nu!(r#"[ [foo bar] [foo baz] ] | find "[" | to json -r"#);
assert_eq!(actual.out, "[]");
}
#[test]
fn find_and_highlight_in_nested_list() {
let actual = nu!(r#"[ [foo bar] [foo baz] ] | find "foo" | to json -r"#);
assert_eq!(
actual.out,
r#"[["\u001b[39m\u001b[0m\u001b[41;39mfoo\u001b[0m\u001b[39m\u001b[0m","bar"],["\u001b[39m\u001b[0m\u001b[41;39mfoo\u001b[0m\u001b[39m\u001b[0m","baz"]]"#
);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/which.rs | crates/nu-command/tests/commands/which.rs | use nu_test_support::nu;
#[test]
fn which_ls() {
let actual = nu!("which ls | get type.0");
assert_eq!(actual.out, "built-in");
}
#[ignore = "TODO: Can't have alias recursion"]
#[test]
fn which_alias_ls() {
let actual = nu!("alias ls = ls -a; which ls | get path.0 | str trim");
assert_eq!(actual.out, "Nushell alias: ls -a");
}
#[test]
fn which_custom_alias() {
let actual = nu!(r#"alias foo = print "foo!"; which foo | to nuon"#);
assert_eq!(actual.out, r#"[[command, path, type]; [foo, "", alias]]"#);
}
#[test]
fn which_def_ls() {
let actual = nu!("def ls [] {echo def}; which ls | get type.0");
assert_eq!(actual.out, "custom");
}
#[ignore = "TODO: Can't have alias with the same name as command"]
#[test]
fn correct_precedence_alias_def_custom() {
let actual =
nu!("def ls [] {echo def}; alias ls = echo alias; which ls | get path.0 | str trim");
assert_eq!(actual.out, "Nushell alias: echo alias");
}
#[ignore = "TODO: Can't have alias with the same name as command"]
#[test]
fn multiple_reports_for_alias_def_custom() {
let actual = nu!("def ls [] {echo def}; alias ls = echo alias; which -a ls | length");
let length: i32 = actual.out.parse().unwrap();
assert!(length >= 2);
}
// `get_aliases_with_name` and `get_custom_commands_with_name` don't return the correct count of
// values
// I suspect this is due to the ScopeFrame getting discarded at '}' and the command is then
// executed in the parent scope
// See: parse_definition, line 2187 for reference.
#[ignore]
#[test]
fn correctly_report_of_shadowed_alias() {
let actual = nu!("alias xaz = echo alias1
def helper [] {
alias xaz = echo alias2
which -a xaz
}
helper | get path | str contains alias2");
assert_eq!(actual.out, "true");
}
#[test]
fn one_report_of_multiple_defs() {
let actual = nu!("def xaz [] { echo def1 }
def helper [] {
def xaz [] { echo def2 }
which -a xaz
}
helper | length");
let length: i32 = actual.out.parse().unwrap();
assert_eq!(length, 1);
}
#[test]
fn def_only_seen_once() {
let actual = nu!("def xaz [] {echo def1}; which -a xaz | length");
let length: i32 = actual.out.parse().unwrap();
assert_eq!(length, 1);
}
#[test]
fn do_not_show_hidden_aliases() {
let actual = nu!("alias foo = echo foo
hide foo
which foo | length");
let length: i32 = actual.out.parse().unwrap();
assert_eq!(length, 0);
}
#[test]
fn do_not_show_hidden_commands() {
let actual = nu!("def foo [] { echo foo }
hide foo
which foo | length");
let length: i32 = actual.out.parse().unwrap();
assert_eq!(length, 0);
}
#[test]
fn which_accepts_spread_list() {
let actual = nu!(r#"
let apps = [ls];
$apps | which ...$in | get command.0
"#);
assert_eq!(actual.out, "ls");
}
#[test]
fn which_dedup_is_less_than_all() {
let all: i32 = nu!("which -a | length").out.parse().unwrap();
let dedup: i32 = nu!("which | length").out.parse().unwrap();
assert!(all >= dedup);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/uname.rs | crates/nu-command/tests/commands/uname.rs | use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn test_uname_all() {
Playground::setup("uname_test_1", |dirs, _| {
let actual = nu!(
cwd: dirs.test(),
"uname"
);
assert!(actual.status.success())
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/split_column.rs | crates/nu-command/tests/commands/split_column.rs | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn to_column() {
Playground::setup("split_column_test_1", |dirs, sandbox| {
sandbox.with_files(&[
FileWithContentToBeTrimmed(
"sample.txt",
r#"
importer,shipper,tariff_item,name,origin
"#,
),
FileWithContentToBeTrimmed(
"sample2.txt",
r#"
importer , shipper , tariff_item , name , origin
"#,
),
]);
let actual = nu!(cwd: dirs.test(), r#"
open sample.txt
| lines
| str trim
| split column ","
| get column1
"#);
assert!(actual.out.contains("shipper"));
let actual = nu!(cwd: dirs.test(), r#"
open sample.txt
| lines
| str trim
| split column -n 3 ","
| get column2
"#);
assert!(actual.out.contains("tariff_item,name,origin"));
let actual = nu!(cwd: dirs.test(), r"
open sample2.txt
| lines
| str trim
| split column --regex '\s*,\s*'
| get column1
");
assert!(actual.out.contains("shipper"));
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/echo.rs | crates/nu-command/tests/commands/echo.rs | use nu_test_support::nu;
#[test]
fn echo_range_is_lazy() {
let actual = nu!("echo 1..10000000000 | first 3 | to json --raw");
assert_eq!(actual.out, "[1,2,3]");
}
#[test]
fn echo_range_handles_inclusive() {
let actual = nu!("echo 1..3 | each { |x| $x } | to json --raw");
assert_eq!(actual.out, "[1,2,3]");
}
#[test]
fn echo_range_handles_exclusive() {
let actual = nu!("echo 1..<3 | each { |x| $x } | to json --raw");
assert_eq!(actual.out, "[1,2]");
}
#[test]
fn echo_range_handles_inclusive_down() {
let actual = nu!("echo 3..1 | each { |it| $it } | to json --raw");
assert_eq!(actual.out, "[3,2,1]");
}
#[test]
fn echo_range_handles_exclusive_down() {
let actual = nu!("echo 3..<1 | each { |it| $it } | to json --raw");
assert_eq!(actual.out, "[3,2]");
}
#[test]
fn echo_is_const() {
let actual = nu!(r#"const val = echo 1..3; $val | to json --raw"#);
assert_eq!(actual.out, "[1,2,3]");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/umkdir.rs | crates/nu-command/tests/commands/umkdir.rs | use nu_test_support::fs::files_exist_at;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[cfg(not(windows))]
use uucore::mode;
#[test]
fn creates_directory() {
Playground::setup("mkdir_test_1", |dirs, _| {
nu!(
cwd: dirs.test(),
"mkdir my_new_directory"
);
let expected = dirs.test().join("my_new_directory");
assert!(expected.exists());
})
}
#[test]
fn accepts_and_creates_directories() {
Playground::setup("mkdir_test_2", |dirs, _| {
nu!(
cwd: dirs.test(),
"mkdir dir_1 dir_2 dir_3"
);
assert!(files_exist_at(&["dir_1", "dir_2", "dir_3"], dirs.test()));
})
}
#[test]
fn creates_intermediary_directories() {
Playground::setup("mkdir_test_3", |dirs, _| {
nu!(
cwd: dirs.test(),
"mkdir some_folder/another/deeper_one"
);
let expected = dirs.test().join("some_folder/another/deeper_one");
assert!(expected.exists());
})
}
#[test]
fn create_directory_two_parents_up_using_multiple_dots() {
Playground::setup("mkdir_test_4", |dirs, sandbox| {
sandbox.within("foo").mkdir("bar");
nu!(
cwd: dirs.test().join("foo/bar"),
"mkdir .../boo"
);
let expected = dirs.test().join("boo");
assert!(expected.exists());
})
}
#[test]
fn print_created_paths() {
Playground::setup("mkdir_test_2", |dirs, _| {
let actual = nu!(cwd: dirs.test(), "mkdir -v dir_1 dir_2 dir_3");
assert!(files_exist_at(&["dir_1", "dir_2", "dir_3"], dirs.test()));
assert!(actual.out.contains("dir_1"));
assert!(actual.out.contains("dir_2"));
assert!(actual.out.contains("dir_3"));
})
}
#[test]
fn creates_directory_three_dots() {
Playground::setup("mkdir_test_1", |dirs, _| {
nu!(
cwd: dirs.test(),
"mkdir test..."
);
let expected = dirs.test().join("test...");
assert!(expected.exists());
})
}
#[test]
fn creates_directory_four_dots() {
Playground::setup("mkdir_test_1", |dirs, _| {
nu!(
cwd: dirs.test(),
"mkdir test...."
);
let expected = dirs.test().join("test....");
assert!(expected.exists());
})
}
#[test]
fn creates_directory_three_dots_quotation_marks() {
Playground::setup("mkdir_test_1", |dirs, _| {
nu!(
cwd: dirs.test(),
"mkdir 'test...'"
);
let expected = dirs.test().join("test...");
assert!(expected.exists());
})
}
#[test]
fn respects_cwd() {
Playground::setup("mkdir_respects_cwd", |dirs, _| {
nu!(
cwd: dirs.test(),
"mkdir 'some_folder'; cd 'some_folder'; mkdir 'another/deeper_one'"
);
let expected = dirs.test().join("some_folder/another/deeper_one");
assert!(expected.exists());
})
}
#[cfg(not(windows))]
#[test]
fn mkdir_umask_permission() {
use std::{fs, os::unix::fs::PermissionsExt};
Playground::setup("mkdir_umask_permission", |dirs, _| {
nu!(
cwd: dirs.test(),
"mkdir test_umask_permission"
);
let actual = fs::metadata(dirs.test().join("test_umask_permission"))
.unwrap()
.permissions()
.mode();
let umask = mode::get_umask();
let default_mode = 0o40777;
let expected: u32 = default_mode & !umask;
assert_eq!(
actual, expected,
"Umask should have been applied to created folder"
);
})
}
#[test]
fn mkdir_with_tilde() {
Playground::setup("mkdir with tilde", |dirs, _| {
let actual = nu!(cwd: dirs.test(), "mkdir '~tilde'");
assert!(actual.err.is_empty());
assert!(files_exist_at(&["~tilde"], dirs.test()));
// pass variable
let actual = nu!(cwd: dirs.test(), "let f = '~tilde2'; mkdir $f");
assert!(actual.err.is_empty());
assert!(files_exist_at(&["~tilde2"], dirs.test()));
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/cal.rs | crates/nu-command/tests/commands/cal.rs | use nu_test_support::nu;
// Tests against table/structured data
#[test]
fn cal_full_year() {
let actual = nu!("cal -t -y --full-year 2010 | first | to json -r");
let first_week_2010_json =
r#"{"year":2010,"su":null,"mo":null,"tu":null,"we":null,"th":null,"fr":1,"sa":2}"#;
assert_eq!(actual.out, first_week_2010_json);
}
#[test]
fn cal_february_2020_leap_year() {
let actual = nu!(r#"
cal --as-table -ym --full-year 2020 --month-names | where month == "february" | to json -r
"#);
let cal_february_json = r#"[{"year":2020,"month":"february","su":null,"mo":null,"tu":null,"we":null,"th":null,"fr":null,"sa":1},{"year":2020,"month":"february","su":2,"mo":3,"tu":4,"we":5,"th":6,"fr":7,"sa":8},{"year":2020,"month":"february","su":9,"mo":10,"tu":11,"we":12,"th":13,"fr":14,"sa":15},{"year":2020,"month":"february","su":16,"mo":17,"tu":18,"we":19,"th":20,"fr":21,"sa":22},{"year":2020,"month":"february","su":23,"mo":24,"tu":25,"we":26,"th":27,"fr":28,"sa":29}]"#;
assert_eq!(actual.out, cal_february_json);
}
#[test]
fn cal_fr_the_thirteenths_in_2015() {
let actual = nu!(r#"
cal --as-table --full-year 2015 | default 0 fr | where fr == 13 | length
"#);
assert!(actual.out.contains('3'));
}
#[test]
fn cal_rows_in_2020() {
let actual = nu!(r#"
cal --as-table --full-year 2020 | length
"#);
assert!(actual.out.contains("62"));
}
#[test]
fn cal_week_day_start_mo() {
let actual = nu!(r#"
cal --as-table --full-year 2020 -m --month-names --week-start mo | where month == january | to json -r
"#);
let cal_january_json = r#"[{"month":"january","mo":null,"tu":null,"we":1,"th":2,"fr":3,"sa":4,"su":5},{"month":"january","mo":6,"tu":7,"we":8,"th":9,"fr":10,"sa":11,"su":12},{"month":"january","mo":13,"tu":14,"we":15,"th":16,"fr":17,"sa":18,"su":19},{"month":"january","mo":20,"tu":21,"we":22,"th":23,"fr":24,"sa":25,"su":26},{"month":"january","mo":27,"tu":28,"we":29,"th":30,"fr":31,"sa":null,"su":null}]"#;
assert_eq!(actual.out, cal_january_json);
}
#[test]
fn cal_sees_pipeline_year() {
let actual = nu!(r#"
cal --as-table --full-year 1020 | get mo | first 4 | to json -r
"#);
assert_eq!(actual.out, "[null,3,10,17]");
}
// Tests against default string output
#[test]
fn cal_is_string() {
let actual = nu!(r#"
cal | describe
"#);
assert_eq!(actual.out, "string (stream)");
}
#[test]
fn cal_year_num_lines() {
let actual = nu!(r#"
cal --full-year 2024 | lines | length
"#);
assert_eq!(actual.out, "68");
}
#[test]
fn cal_week_start_string() {
let actual = nu!(r#"
cal --week-start fr | lines | get 1 | split row '│' | get 2 | ansi strip | str trim
"#);
assert_eq!(actual.out, "sa");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/reduce.rs | crates/nu-command/tests/commands/reduce.rs | use nu_test_support::nu;
#[test]
fn reduce_table_column() {
let actual = nu!(r#"
echo "[{month:2,total:30}, {month:3,total:10}, {month:4,total:3}, {month:5,total:60}]"
| from json
| get total
| reduce --fold 20 { |it, acc| $it + $acc ** 1.05}
| into string -d 1
"#);
assert_eq!(actual.out, "180.6");
}
#[test]
fn reduce_table_column_with_path() {
let actual = nu!("
[{month:2,total:30}, {month:3,total:10}, {month:4,total:3}, {month:5,total:60}]
| reduce --fold 20 { |it, acc| $it.total + $acc ** 1.05}
| into string -d 1
");
assert_eq!(actual.out, "180.6");
}
#[test]
fn reduce_rows_example() {
let actual = nu!("
[[a,b]; [1,2] [3,4]]
| reduce --fold 1.6 { |it, acc| $acc * ($it.a | into int) + ($it.b | into int) }
");
assert_eq!(actual.out, "14.8");
}
#[test]
fn reduce_with_return_in_closure() {
let actual = nu!("
[1, 2] | reduce --fold null { |it, state|
if $it == 1 {
return 10
};
return ($it * $state)
}
");
assert_eq!(actual.out, "20");
assert!(actual.err.is_empty());
}
#[test]
fn reduce_enumerate_example() {
let actual = nu!("
echo one longest three bar | enumerate
| reduce { |it, acc| if ($it.item | str length) > ($acc.item | str length) {echo $it} else {echo $acc}}
| get index
");
assert_eq!(actual.out, "1");
}
#[test]
fn reduce_enumerate_integer_addition_example() {
let actual = nu!("
echo [1 2 3 4]
| enumerate
| reduce { |it, acc| { index: ($it.index) item: ($acc.item + $it.item)} }
| get item
");
assert_eq!(actual.out, "10");
}
#[test]
fn folding_with_tables() {
let actual = nu!("
echo [10 20 30 40]
| reduce --fold [] { |it, acc|
with-env { value: $it } {
echo $acc | append (10 * ($env.value | into int))
}
}
| math sum
");
assert_eq!(actual.out, "1000");
}
#[test]
fn error_reduce_fold_type_mismatch() {
let actual = nu!("echo a b c | reduce --fold 0 { |it, acc| $acc + $it }");
assert!(
actual
.err
.contains("nu::shell::operator_incompatible_types")
);
}
#[test]
fn error_reduce_empty() {
let actual = nu!("reduce { |it, acc| $acc + $it }");
assert!(actual.err.contains("no input value was piped in"));
}
#[test]
fn enumerate_reduce_example() {
let actual = nu!(
"[one longest three bar] | enumerate | reduce {|it, acc| if ($it.item | str length) > ($acc.item | str length) { $it } else { $acc }} | get index"
);
assert_eq!(actual.out, "1");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/uniq_by.rs | crates/nu-command/tests/commands/uniq_by.rs | use nu_test_support::nu;
#[test]
fn removes_duplicate_rows() {
let sample = r#"[
[first_name , last_name, rusty_at, type];
[Andrés , Robalino, "10/11/2013", A],
[Afonso , Turner, "10/12/2013", B],
[Yehuda , Katz, "10/11/2013", A],
[JT , Turner, "11/12/2011", O]
]"#;
let actual = nu!(format!("{sample} | uniq-by last_name | length"));
assert_eq!(actual.out, "3");
}
#[test]
fn uniq_when_keys_out_of_order() {
let actual = nu!(r#"[{"a": "a", "b": [1,2,3]}, {"b": [1,2,3,4], "a": "a"}] | uniq-by a"#);
let expected = nu!(r#"[{"a": "a", "b": [1,2,3]}]"#);
assert_eq!(actual.out, expected.out);
}
#[test]
fn uniq_counting() {
let actual = nu!(r#"
["A", "B", "A"]
| wrap item
| uniq-by item --count
| flatten
| where item == A
| get count
| get 0
"#);
assert_eq!(actual.out, "2");
let actual = nu!(r#"
["A", "B", "A"]
| wrap item
| uniq-by item --count
| flatten
| where item == B
| get count
| get 0
"#);
assert_eq!(actual.out, "1");
}
#[test]
fn uniq_unique() {
let actual = nu!("
echo [1 2 3 4 1 5]
| wrap item
| uniq-by item --unique
| get item
");
let expected = nu!("[2 3 4 5]");
assert_eq!(actual.out, expected.out);
}
#[test]
fn table() {
let actual = nu!("
[[fruit day]; [apple monday] [apple friday] [Apple friday] [apple monday] [pear monday] [orange tuesday]]
| uniq-by fruit
");
let expected = nu!("
echo [[fruit day]; [apple monday] [Apple friday] [pear monday] [orange tuesday]]
");
print!("{}", actual.out);
print!("{}", expected.out);
assert_eq!(actual.out, expected.out);
}
#[test]
fn uniq_by_empty() {
let actual = nu!("[] | uniq-by foo | to nuon");
assert_eq!(actual.out, "[]");
}
#[test]
fn uniq_by_multiple_columns() {
let actual = nu!("
[[fruit day]; [apple monday] [apple friday] [Apple friday] [apple monday] [pear monday] [orange tuesday]]
| uniq-by fruit day
");
let expected = nu!("
echo [[fruit day]; [apple monday] [apple friday] [Apple friday] [pear monday] [orange tuesday]]
");
assert_eq!(actual.out, expected.out);
}
#[test]
fn table_with_ignore_case() {
let actual = nu!(r#"
[[origin, people];
[World, (
[[name, meal];
['Geremias', {plate: 'bitoque', carbs: 100}]
]
)],
[World, (
[[name, meal];
['Martin', {plate: 'bitoque', carbs: 100}]
]
)],
[World, (
[[name, meal];
['Geremias', {plate: 'Bitoque', carbs: 100}]
]
)],
] | uniq-by people -i
"#);
let expected = nu!(r#"
echo [[origin, people];
[World, (
[[name, meal];
['Geremias', {plate: 'bitoque', carbs: 100}]
]
)],
[World, (
[[name, meal];
['Martin', {plate: 'bitoque', carbs: 100}]
]
)],
]
"#);
assert_eq!(actual.out, expected.out);
}
#[test]
fn missing_parameter() {
let actual = nu!("[11 22 33] | uniq-by");
assert!(actual.err.contains("missing parameter"));
}
#[test]
fn wrong_column() {
let actual = nu!("[[fruit day]; [apple monday] [apple friday]] | uniq-by column1");
assert!(actual.err.contains("cannot find column 'column1'"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/stor.rs | crates/nu-command/tests/commands/stor.rs | use nu_test_support::nu;
#[test]
fn stor_insert() {
let actual = nu!(r#"
stor create --table-name test_table --columns { id: int, value: str };
stor insert -t test_table --data-record {
id: 1
value: "'Initial value'"
};
stor open | query db 'select value from test_table' | get 0.value
"#);
assert_eq!(actual.out, "'Initial value'");
}
#[test]
fn stor_update_with_quote() {
let actual = nu!(r#"
stor create --table-name test_table --columns { id: int, value: str };
stor insert -t test_table --data-record {
id: 1
value: "'Initial value'"
};
stor update -t test_table --where-clause 'id = 1' --update-record {
id: 1
value: "This didn't work, but should now."
};
stor open | query db 'select value from test_table' | get 0.value
"#);
assert_eq!(actual.out, "This didn't work, but should now.");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/let_.rs | crates/nu-command/tests/commands/let_.rs | use nu_test_support::nu;
use rstest::rstest;
#[rstest]
#[case("let in = 3")]
#[case("let in: int = 3")]
fn let_name_builtin_var(#[case] assignment: &str) {
assert!(
nu!(assignment)
.err
.contains("'in' is the name of a builtin Nushell variable")
);
}
#[test]
fn let_doesnt_mutate() {
let actual = nu!("let i = 3; $i = 4");
assert!(actual.err.contains("immutable"));
}
#[test]
fn let_takes_pipeline() {
let actual = nu!(r#"let x = "hello world" | str length; print $x"#);
assert_eq!(actual.out, "11");
}
#[test]
fn let_takes_pipeline_with_declared_type() {
let actual = nu!(r#"let x: list<string> = [] | append "hello world"; print $x.0"#);
assert_eq!(actual.out, "hello world");
}
#[test]
fn let_pipeline_allows_in() {
let actual =
nu!(r#"def foo [] { let x = $in | str length; print ($x + 10) }; "hello world" | foo"#);
assert_eq!(actual.out, "21");
}
#[test]
fn mut_takes_pipeline() {
let actual = nu!(r#"mut x = "hello world" | str length; print $x"#);
assert_eq!(actual.out, "11");
}
#[test]
fn mut_takes_pipeline_with_declared_type() {
let actual = nu!(r#"mut x: list<string> = [] | append "hello world"; print $x.0"#);
assert_eq!(actual.out, "hello world");
}
#[test]
fn mut_pipeline_allows_in() {
let actual =
nu!(r#"def foo [] { mut x = $in | str length; print ($x + 10) }; "hello world" | foo"#);
assert_eq!(actual.out, "21");
}
#[test]
fn let_pipeline_redirects_internals() {
let actual = nu!(r#"let x = echo 'bar'; $x | str length"#);
assert_eq!(actual.out, "3");
}
#[test]
fn let_pipeline_redirects_externals() {
let actual = nu!(r#"let x = nu --testbin cococo 'bar'; $x | str length"#);
assert_eq!(actual.out, "3");
}
#[test]
fn let_err_pipeline_redirects_externals() {
let actual = nu!(
r#"let x = with-env { FOO: "foo" } {nu --testbin echo_env_stderr FOO e>| str length}; $x"#
);
assert_eq!(actual.out, "3");
}
#[test]
fn let_outerr_pipeline_redirects_externals() {
let actual = nu!(
r#"let x = with-env { FOO: "foo" } {nu --testbin echo_env_stderr FOO o+e>| str length}; $x"#
);
assert_eq!(actual.out, "3");
}
#[ignore]
#[test]
fn let_with_external_failed() {
// FIXME: this test hasn't run successfully for a long time. We should
// bring it back to life at some point.
let actual = nu!(r#"let x = nu --testbin outcome_err "aa"; echo fail"#);
assert!(!actual.out.contains("fail"));
}
#[test]
fn let_glob_type() {
let actual = nu!("let x: glob = 'aa'; $x | describe");
assert_eq!(actual.out, "glob");
}
#[test]
fn let_raw_string() {
let actual = nu!(r#"let x = r#'abcde""fghi"''''jkl'#; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"''''jkl"#);
let actual = nu!(r#"let x = r##'abcde""fghi"''''#jkl'##; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"''''#jkl"#);
let actual = nu!(r#"let x = r###'abcde""fghi"'''##'#jkl'###; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"'''##'#jkl"#);
let actual = nu!(r#"let x = r#'abc'#; $x"#);
assert_eq!(actual.out, "abc");
}
#[test]
fn let_malformed_type() {
let actual = nu!("let foo: )a");
assert!(actual.err.contains("unbalanced ( and )"));
let actual = nu!("let foo: }a");
assert!(actual.err.contains("unbalanced { and }"));
let actual = nu!("mut : , a");
assert!(actual.err.contains("unknown type"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/uniq.rs | crates/nu-command/tests/commands/uniq.rs | use nu_test_support::nu;
const SAMPLE_CSV_CONTENT: &str = r#"
[[first_name, last_name, rusty_at, type];
[Andrés, Robalino, "10/11/2013", A],
[JT, Turner, "10/12/2013", B],
[Yehuda, Katz, "10/11/2013", A],
[JT, Turner, "10/12/2013", B],
[Yehuda, Katz, "10/11/2013", A]]
"#;
#[test]
fn removes_duplicate_rows() {
let actual = nu!(format!("{SAMPLE_CSV_CONTENT} | uniq | length"));
assert_eq!(actual.out, "3");
}
#[test]
fn uniq_values() {
let actual = nu!(format!(
"{SAMPLE_CSV_CONTENT} | select type | uniq | length"
));
assert_eq!(actual.out, "2");
}
#[test]
fn uniq_empty() {
let actual = nu!("[] | uniq | to nuon");
assert_eq!(actual.out, "[]");
}
#[test]
fn nested_json_structures() {
let sample = r#"
[
{
"name": "this is duplicated",
"nesting": [ { "a": "a", "b": "b" },
{ "c": "c", "d": "d" }
],
"can_be_ordered_differently": {
"array": [1, 2, 3, 4, 5],
"something": { "else": "works" }
}
},
{
"can_be_ordered_differently": {
"something": { "else": "works" },
"array": [1, 2, 3, 4, 5]
},
"nesting": [ { "b": "b", "a": "a" },
{ "d": "d", "c": "c" }
],
"name": "this is duplicated"
},
{
"name": "this is unique",
"nesting": [ { "a": "b", "b": "a" },
{ "c": "d", "d": "c" }
],
"can_be_ordered_differently": {
"array": [],
"something": { "else": "does not work" }
}
},
{
"name": "this is unique",
"nesting": [ { "a": "a", "b": "b", "c": "c" },
{ "d": "d", "e": "e", "f": "f" }
],
"can_be_ordered_differently": {
"array": [],
"something": { "else": "works" }
}
}
]
"#;
let actual = nu!(format!("'{sample}' | from json | uniq | length"));
assert_eq!(actual.out, "3");
}
#[test]
fn uniq_when_keys_out_of_order() {
let actual = nu!(r#"
[{"a": "a", "b": [1,2,3]}, {"b": [1,2,3], "a": "a"}]
| uniq
| length
"#);
assert_eq!(actual.out, "1");
}
#[test]
fn uniq_counting() {
let actual = nu!(r#"
["A", "B", "A"]
| wrap item
| uniq --count
| flatten
| where item == A
| get count
| get 0
"#);
assert_eq!(actual.out, "2");
let actual = nu!(r#"
["A", "B", "A"]
| wrap item
| uniq --count
| flatten
| where item == B
| get count
| get 0
"#);
assert_eq!(actual.out, "1");
}
#[test]
fn uniq_unique() {
let actual = nu!("[1 2 3 4 1 5] | uniq --unique");
let expected = nu!("[2 3 4 5]");
assert_eq!(actual.out, expected.out);
}
#[test]
fn uniq_simple_vals_ints() {
let actual = nu!("[1 2 3 4 1 5] | uniq");
let expected = nu!("[1 2 3 4 5]");
assert_eq!(actual.out, expected.out);
}
#[test]
fn uniq_simple_vals_strs() {
let actual = nu!("[A B C A] | uniq");
let expected = nu!("[A B C]");
assert_eq!(actual.out, expected.out);
}
#[test]
fn table() {
let actual = nu!("
[[fruit day]; [apple monday] [apple friday] [Apple friday] [apple monday] [pear monday] [orange tuesday]]
| uniq
");
let expected = nu!(
"[[fruit day]; [apple monday] [apple friday] [Apple friday] [pear monday] [orange tuesday]]"
);
assert_eq!(actual.out, expected.out);
}
#[test]
fn table_with_ignore_case() {
let actual = nu!(r#"
[[origin, people];
[World, (
[[name, meal];
['Geremias', {plate: 'bitoque', carbs: 100}]
]
)],
[World, (
[[name, meal];
['Martin', {plate: 'bitoque', carbs: 100}]
]
)],
[World, (
[[name, meal];
['Geremias', {plate: 'Bitoque', carbs: 100}]
]
)],
] | uniq --ignore-case
"#);
let expected = nu!(r#"
echo [[origin, people];
[World, (
[[name, meal];
['Geremias', {plate: 'bitoque', carbs: 100}]
]
)],
[World, (
[[name, meal];
['Martin', {plate: 'bitoque', carbs: 100}]
]
)],
]
"#);
assert_eq!(actual.out, expected.out);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/terminal.rs | crates/nu-command/tests/commands/terminal.rs | use nu_test_support::nu;
// Inside nu! stdout is piped so it won't be a terminal
#[test]
fn is_terminal_stdout_piped() {
let actual = nu!(r#"
is-terminal --stdout
"#);
assert_eq!(actual.out, "false");
}
#[test]
fn is_terminal_two_streams() {
let actual = nu!(r#"
is-terminal --stdin --stderr
"#);
assert!(actual.err.contains("Only one stream may be checked"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/chunk_by.rs | crates/nu-command/tests/commands/chunk_by.rs | use nu_test_support::nu;
#[test]
fn chunk_by_on_empty_input_returns_empty_list() {
let actual = nu!("[] | chunk-by {|it| $it} | to nuon");
assert!(actual.err.is_empty());
assert_eq!(actual.out, "[]");
}
#[test]
fn chunk_by_strings_works() {
let sample = r#"[a a a b b b c c c a a a]"#;
let actual = nu!(format!(
r#"
{sample}
| chunk-by {{|it| $it}}
| to nuon
"#
));
assert_eq!(actual.out, "[[a, a, a], [b, b, b], [c, c, c], [a, a, a]]");
}
#[test]
fn chunk_by_field_works() {
let sample = r#"[
{
name: bob,
age: 20,
cool: false
},
{
name: jane,
age: 30,
cool: false
},
{
name: marie,
age: 19,
cool: true
},
{
name: carl,
age: 36,
cool: true
} ]"#;
let actual = nu!(format!(
r#"
{sample}
| chunk-by {{|it| $it.cool}}
| length
"#
));
assert_eq!(actual.out, "2");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/any.rs | crates/nu-command/tests/commands/any.rs | use nu_test_support::nu;
#[test]
fn checks_any_row_is_true() {
let actual = nu!(r#"
echo [ "Ecuador", "USA", "New Zealand" ]
| any {|it| $it == "New Zealand" }
"#);
assert_eq!(actual.out, "true");
}
#[test]
fn checks_any_column_of_a_table_is_true() {
let actual = nu!("
echo [
[ first_name, last_name, rusty_at, likes ];
[ Andrés, Robalino, '10/11/2013', 1 ]
[ JT, Turner, '10/12/2013', 1 ]
[ Darren, Schroeder, '10/11/2013', 1 ]
[ Yehuda, Katz, '10/11/2013', 1 ]
]
| any {|x| $x.rusty_at == '10/12/2013' }
");
assert_eq!(actual.out, "true");
}
#[test]
fn checks_if_any_returns_error_with_invalid_command() {
// Using `with-env` to remove `st` possibly being an external program
let actual = nu!(r#"
with-env {PATH: ""} {
[red orange yellow green blue purple] | any {|it| ($it | st length) > 4 }
}
"#);
assert!(
actual.err.contains("Command `st` not found") && actual.err.contains("Did you mean `ast`?")
);
}
#[test]
fn works_with_1_param_blocks() {
let actual = nu!("[1 2 3] | any {|e| print $e | false }");
assert_eq!(actual.out, "123false");
}
#[test]
fn works_with_0_param_blocks() {
let actual = nu!("[1 2 3] | any {|| print $in | false }");
assert_eq!(actual.out, "123false");
}
#[test]
fn early_exits_with_1_param_blocks() {
let actual = nu!("[1 2 3] | any {|e| print $e | true }");
assert_eq!(actual.out, "1true");
}
#[test]
fn early_exits_with_0_param_blocks() {
let actual = nu!("[1 2 3] | any {|| print $in | true }");
assert_eq!(actual.out, "1true");
}
#[test]
fn any_uses_enumerate_index() {
let actual = nu!("[7 8 9] | enumerate | any {|el| print $el.index | false }");
assert_eq!(actual.out, "012false");
}
#[test]
fn unique_env_each_iteration() {
let actual = nu!(
cwd: "tests/fixtures/formats",
"[1 2] | any {|| print ($env.PWD | str ends-with 'formats') | cd '/' | false } | to nuon"
);
assert_eq!(actual.out, "truetruefalse");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/transpose.rs | crates/nu-command/tests/commands/transpose.rs | use nu_test_support::nu;
#[test]
fn row() {
let actual = nu!("[[key value]; [foo 1] [foo 2]] | transpose -r | debug");
assert!(actual.out.contains("foo: 1"));
}
#[test]
fn row_but_last() {
let actual = nu!("[[key value]; [foo 1] [foo 2]] | transpose -r -l | debug");
assert!(actual.out.contains("foo: 2"));
}
#[test]
fn row_but_all() {
let actual = nu!("[[key value]; [foo 1] [foo 2]] | transpose -r -a | debug");
assert!(actual.out.contains("foo: [1, 2]"));
}
#[test]
fn throw_inner_error() {
let error_msg = "This message should show up";
let error = format!("(error make {{ msg: \"{error_msg}\" }})");
let actual = nu!(format!(
"[[key value]; [foo 1] [foo 2] [{} 3]] | transpose",
error
));
assert!(actual.err.contains(error.as_str()));
}
#[test]
fn rejects_non_table_stream_input() {
let actual = nu!("[1 2 3] | each { |it| ($it * 2) } | transpose | to nuon");
assert!(actual.out.is_empty());
assert!(actual.err.contains("only table"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/while_.rs | crates/nu-command/tests/commands/while_.rs | use nu_test_support::nu;
#[test]
fn while_sum() {
let actual = nu!(
"mut total = 0; mut x = 0; while $x <= 10 { $total = $total + $x; $x = $x + 1 }; $total"
);
assert_eq!(actual.out, "55");
}
#[test]
fn while_doesnt_auto_print_in_each_iteration() {
let actual = nu!("mut total = 0; while $total < 2 { $total = $total + 1; 1 }");
// Make sure we don't see any of these values in the output
// As we do not auto-print loops anymore
assert!(!actual.out.contains('1'));
}
#[test]
fn while_break_on_external_failed() {
let actual =
nu!("mut total = 0; while $total < 2 { $total = $total + 1; print 1; nu --testbin fail }");
// Note: nu! macro auto replace "\n" and "\r\n" with ""
// so our output will be `1`
assert_eq!(actual.out, "1");
}
#[test]
fn failed_while_should_break_running() {
let actual =
nu!("mut total = 0; while $total < 2 { $total = $total + 1; nu --testbin fail }; print 3");
assert!(!actual.out.contains('3'));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/mod.rs | crates/nu-command/tests/commands/mod.rs | mod alias;
mod all;
mod any;
mod append;
mod assignment;
mod base;
mod break_;
mod bytes;
mod cal;
mod cd;
mod chunk_by;
mod chunks;
mod compact;
mod complete;
mod config_env_default;
mod config_nu_default;
mod continue_;
mod conversions;
#[cfg(feature = "sqlite")]
mod database;
mod date;
mod debug_info;
mod def;
mod default;
mod detect_columns;
mod do_;
mod drop;
mod du;
mod each;
mod echo;
mod empty;
mod error_make;
mod every;
mod exec;
mod export;
mod export_def;
mod fill;
mod filter;
mod find;
mod first;
mod flatten;
mod for_;
mod format;
mod generate;
mod get;
mod glob;
mod griddle;
mod group_by;
mod hash_;
mod headers;
mod help;
mod histogram;
mod ignore;
mod insert;
mod inspect;
mod interleave;
mod into_datetime;
mod into_duration;
mod into_filesize;
mod into_int;
mod join;
mod last;
mod length;
mod let_;
mod lines;
mod loop_;
mod ls;
mod match_;
mod math;
mod merge;
mod merge_deep;
mod mktemp;
mod move_;
mod mut_;
mod network;
mod nu_check;
mod open;
mod par_each;
mod parse;
mod path;
mod platform;
mod prepend;
mod print;
#[cfg(feature = "sqlite")]
mod query;
mod random;
mod redirection;
mod reduce;
mod reject;
mod rename;
mod return_;
mod reverse;
mod rm;
mod roll;
mod rotate;
mod run_external;
mod save;
mod select;
mod semicolon;
mod seq;
mod seq_char;
mod seq_date;
mod skip;
mod slice;
mod sort;
mod sort_by;
mod source_env;
mod split_column;
mod split_row;
mod stor;
mod str_;
mod table;
mod take;
mod tee;
mod terminal;
mod to_text;
mod transpose;
mod try_;
mod ucp;
#[cfg(unix)]
mod ulimit;
mod unlet;
mod window;
mod debug;
mod job;
mod umkdir;
mod uname;
mod uniq;
mod uniq_by;
mod update;
mod upsert;
mod url;
mod use_;
mod utouch;
mod where_;
mod which;
mod while_;
mod with_env;
mod wrap;
mod zip;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/config_nu_default.rs | crates/nu-command/tests/commands/config_nu_default.rs | use nu_test_support::nu;
#[test]
fn print_config_nu_default_to_stdout() {
let actual = nu!("config nu --default");
assert_eq!(
actual.out,
nu_utils::ConfigFileKind::Config
.default()
.replace(['\n', '\r'], "")
);
assert!(actual.err.is_empty());
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/drop.rs | crates/nu-command/tests/commands/drop.rs | use nu_test_support::nu;
#[test]
fn columns() {
let actual = nu!("
echo [
[arepas, color];
[3, white]
[8, yellow]
[4, white]
] | drop column | columns | length
");
assert_eq!(actual.out, "1");
}
#[test]
fn drop_columns_positive_value() {
let actual = nu!("echo [[a, b];[1,2]] | drop column -1");
assert!(actual.err.contains("use a positive value"));
}
#[test]
fn more_columns_than_table_has() {
let actual = nu!("
echo [
[arepas, color];
[3, white]
[8, yellow]
[4, white]
] | drop column 3 | columns | is-empty
");
assert_eq!(actual.out, "true");
}
#[test]
fn rows() {
let actual = nu!("
echo [
[arepas];
[3]
[8]
[4]
]
| drop 2
| get arepas
| math sum
");
assert_eq!(actual.out, "3");
}
#[test]
fn more_rows_than_table_has() {
let actual = nu!("[date] | drop 50 | length");
assert_eq!(actual.out, "0");
}
#[test]
fn nth_range_inclusive() {
let actual = nu!("echo 10..15 | drop nth (2..3) | to json --raw");
assert_eq!(actual.out, "[10,11,14,15]");
}
#[test]
fn nth_range_exclusive() {
let actual = nu!("echo 10..15 | drop nth (1..<3) | to json --raw");
assert_eq!(actual.out, "[10,13,14,15]");
}
#[test]
fn nth_missing_first_argument() {
let actual = nu!("echo 10..15 | drop nth \"\"");
assert!(actual.err.contains("int or range"));
}
#[test]
fn fail_on_non_iterator() {
let actual = nu!("1 | drop 50");
assert!(actual.err.contains("command doesn't support"));
}
#[test]
fn disjoint_columns_first_row_becomes_empty() {
let actual = nu!("
[{a: 1}, {b: 2, c: 3}]
| drop column
| columns
| to nuon
");
assert_eq!(actual.out, "[b, c]");
}
#[test]
fn disjoint_columns() {
let actual = nu!("
[{a: 1, b: 2}, {c: 3}]
| drop column
| columns
| to nuon
");
assert_eq!(actual.out, "[a, c]");
}
#[test]
fn record() {
let actual = nu!("{a: 1, b: 2} | drop column | to nuon");
assert_eq!(actual.out, "{a: 1}");
}
#[test]
fn more_columns_than_record_has() {
let actual = nu!("{a: 1, b: 2} | drop column 3 | to nuon");
assert_eq!(actual.out, "{}");
}
#[test]
fn drop_single_index() {
let actual = nu!("echo 10..15 | drop nth 2 | to json --raw");
assert_eq!(actual.out, "[10,11,13,14,15]");
}
#[test]
fn drop_multiple_indices() {
let actual = nu!("echo 0..10 | drop nth 1 3 | to json --raw");
assert_eq!(actual.out, "[0,2,4,5,6,7,8,9,10]");
}
#[test]
fn drop_inclusive_range() {
let actual = nu!("echo 10..15 | drop nth (2..4) | to json --raw");
assert_eq!(actual.out, "[10,11,15]");
}
#[test]
fn drop_exclusive_range() {
let actual = nu!("echo 10..15 | drop nth (2..<4) | to json --raw");
assert_eq!(actual.out, "[10,11,14,15]");
}
#[test]
fn drop_unbounded_range() {
let actual = nu!("echo 0..5 | drop nth 3.. | to json --raw");
assert_eq!(actual.out, "[0,1,2]");
}
#[test]
fn drop_multiple_ranges_including_unbounded() {
let actual = nu!(r#"
0..30
| drop nth 0..10 20..
| to json --raw
"#);
assert_eq!(actual.out, "[11,12,13,14,15,16,17,18,19]");
}
#[test]
fn drop_combination_of_unbounded_range_and_single_index() {
let actual = nu!(r#"
echo 0..15
| drop nth 10.. 5
| to json --raw
"#);
assert_eq!(actual.out, "[0,1,2,3,4,6,7,8,9]");
}
#[test]
fn drop_combination_of_two_unbounded_ranges() {
let actual = nu!(r#"
echo 0..150
| drop nth 0..100 999..
| to json --raw
"#);
let expected: Vec<u32> = (101..=150).collect();
let expected_json = serde_json::to_string(&expected).unwrap();
assert_eq!(actual.out, expected_json);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/format.rs | crates/nu-command/tests/commands/format.rs | use nu_test_support::fs::Stub::{EmptyFile, FileWithContentToBeTrimmed};
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn creates_the_resulting_string_from_the_given_fields() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml
| get package
| format pattern "{name} has license {license}"
"#);
assert_eq!(actual.out, "nu has license ISC");
}
#[test]
fn format_input_record_output_string() {
let actual = nu!(r#"{name: Downloads} | format pattern "{name}""#);
assert_eq!(actual.out, "Downloads");
}
#[test]
fn given_fields_can_be_column_paths() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml
| format pattern "{package.name} is {package.description}"
"#);
assert_eq!(actual.out, "nu is a new type of shell");
}
#[test]
fn cant_use_variables() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml
| format pattern "{$it.package.name} is {$it.package.description}"
"#);
// TODO SPAN: This has been removed during SpanId refactor
assert!(actual.err.contains("Removed functionality"));
}
#[test]
fn error_unmatched_brace() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
open cargo_sample.toml
| format pattern "{package.name"
"#);
assert!(actual.err.contains("unmatched curly brace"));
}
#[test]
fn format_filesize_works() {
Playground::setup("format_filesize_test_1", |dirs, sandbox| {
sandbox.with_files(&[
EmptyFile("yehuda.txt"),
EmptyFile("jttxt"),
EmptyFile("andres.txt"),
]);
let actual = nu!(cwd: dirs.test(), "
ls
| format filesize kB size
| get size
| first
");
assert_eq!(actual.out, "0 kB");
})
}
#[test]
fn format_filesize_works_with_nonempty_files() {
Playground::setup(
"format_filesize_works_with_nonempty_files",
|dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"sample.toml",
r#"
[dependency]
name = "nu"
"#,
)]);
let actual = nu!(
cwd: dirs.test(),
"ls sample.toml | format filesize B size | get size | first"
);
#[cfg(not(windows))]
assert_eq!(actual.out, "25 B");
#[cfg(windows)]
assert_eq!(actual.out, "27 B");
},
)
}
#[test]
fn format_filesize_with_invalid_unit() {
let actual = nu!("1MB | format filesize sec");
assert!(actual.err.contains("invalid_unit"));
}
#[test]
fn format_duration_with_invalid_unit() {
let actual = nu!("1sec | format duration MB");
assert!(actual.err.contains("invalid_unit"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/append.rs | crates/nu-command/tests/commands/append.rs | use nu_test_support::nu;
#[test]
fn adds_a_row_to_the_end() {
let actual = nu!(r#"
echo [ "Andrés N. Robalino", "JT Turner", "Yehuda Katz" ]
| append "pollo loco"
| get 3
"#);
assert_eq!(actual.out, "pollo loco");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/join.rs | crates/nu-command/tests/commands/join.rs | use nu_test_support::nu;
#[test]
fn cases_where_result_is_same_between_join_types_inner() {
do_cases_where_result_is_same_between_join_types("--inner")
}
#[test]
fn cases_where_result_differs_between_join_types_inner() {
do_cases_where_result_differs_between_join_types("--inner")
}
#[test]
fn cases_where_result_differs_between_join_types_with_different_join_keys_inner() {
do_cases_where_result_differs_between_join_types_with_different_join_keys("--inner")
}
#[test]
fn cases_where_result_is_same_between_join_types_left() {
do_cases_where_result_is_same_between_join_types("--left")
}
#[test]
fn cases_where_result_is_same_between_join_types_outer() {
do_cases_where_result_is_same_between_join_types("--outer")
}
#[test]
fn cases_where_result_differs_between_join_types_left() {
do_cases_where_result_differs_between_join_types("--left")
}
#[test]
fn cases_where_result_differs_between_join_types_with_different_join_keys_left() {
do_cases_where_result_differs_between_join_types_with_different_join_keys("--left")
}
#[test]
fn cases_where_result_is_same_between_join_types_right() {
do_cases_where_result_is_same_between_join_types("--right")
}
#[test]
fn cases_where_result_differs_between_join_types_right() {
do_cases_where_result_differs_between_join_types("--right")
}
#[test]
fn cases_where_result_differs_between_join_types_outer() {
do_cases_where_result_differs_between_join_types("--outer")
}
#[test]
fn cases_where_result_differs_between_join_types_with_different_join_keys_outer() {
do_cases_where_result_differs_between_join_types_with_different_join_keys("--outer")
}
fn do_cases_where_result_is_same_between_join_types(join_type: &str) {
// .mode column
// .headers on
for ((left, right, on), expected) in [
(("[]", "[]", "_"), "[]"),
(("[]", "[{a: 1}]", "_"), "[]"),
(("[{a: 1}]", "[]", "_"), "[]"),
(("[{a: 1}]", "[{a: 1}]", "_"), "[]"),
(("[{a: 1}]", "[{a: 1}]", "a"), "[[a]; [1]]"),
(("[{a: 1} {a: 1}]", "[{a: 1}]", "a"), "[[a]; [1], [1]]"),
(("[{a: 1}]", "[{a: 1} {a: 1}]", "a"), "[[a]; [1], [1]]"),
(
("[{a: 1} {a: 1}]", "[{a: 1} {a: 1}]", "a"),
"[[a]; [1], [1], [1], [1]]",
),
(("[{a: 1 b: 1}]", "[{a: 1}]", "a"), "[[a, b]; [1, 1]]"),
(("[{a: 1}]", "[{a: 1 b: 2}]", "a"), "[[a, b]; [1, 2]]"),
(
// create table l (a, b);
// create table r (a, b);
// insert into l (a, b) values (1, 1);
// insert into r (a, b) values (1, 2);
// select * from l inner join r on l.a = r.a;
("[{a: 1 b: 1}]", "[{a: 1 b: 2}]", "a"),
"[[a, b, b_]; [1, 1, 2]]",
),
(("[{a: 1}]", "[{a: 1 b: 1}]", "a"), "[[a, b]; [1, 1]]"),
] {
let expr = format!("{left} | join {right} {join_type} {on} | to nuon");
let actual = nu!(expr).out;
assert_eq!(actual, expected);
// Test again with streaming input (using `each` to convert the input into a ListStream)
let to_list_stream = "each { |i| $i } | ";
let expr = format!("{left} | {to_list_stream} join {right} {join_type} {on} | to nuon");
let actual = nu!(expr).out;
assert_eq!(actual, expected);
}
}
fn do_cases_where_result_differs_between_join_types(join_type: &str) {
// .mode column
// .headers on
for ((left, right, on), join_types) in [
(
("[]", "[{a: 1}]", "a"),
[
("--inner", "[]"),
("--left", "[]"),
("--right", "[[a]; [1]]"),
("--outer", "[[a]; [1]]"),
],
),
(
("[{a: 1}]", "[]", "a"),
[
("--inner", "[]"),
("--left", "[[a]; [1]]"),
("--right", "[]"),
("--outer", "[[a]; [1]]"),
],
),
(
("[{a: 2 b: 1}]", "[{a: 1}]", "a"),
[
("--inner", "[]"),
("--left", "[[a, b]; [2, 1]]"),
("--right", "[[a, b]; [1, null]]"),
("--outer", "[[a, b]; [2, 1], [1, null]]"),
],
),
(
("[{a: 1}]", "[{a: 2 b: 1}]", "a"),
[
("--inner", "[]"),
("--left", "[[a, b]; [1, null]]"),
("--right", "[[a, b]; [2, 1]]"),
("--outer", "[[a, b]; [1, null], [2, 1]]"),
],
),
(
// create table l (a, b);
// create table r (a, b);
// insert into l (a, b) values (1, 2);
// insert into r (a, b) values (2, 1);
("[{a: 1 b: 2}]", "[{a: 2 b: 1}]", "a"),
[
("--inner", "[]"),
("--left", "[[a, b, b_]; [1, 2, null]]"),
// select * from l right outer join r on l.a = r.a;
("--right", "[[a, b, b_]; [2, null, 1]]"),
("--outer", "[[a, b, b_]; [1, 2, null], [2, null, 1]]"),
],
),
(
("[{a: 1 b: 2}]", "[{a: 2 b: 1} {a: 1 b: 1}]", "a"),
[
("--inner", "[[a, b, b_]; [1, 2, 1]]"),
("--left", "[[a, b, b_]; [1, 2, 1]]"),
("--right", "[[a, b, b_]; [2, null, 1], [1, 2, 1]]"),
("--outer", "[[a, b, b_]; [1, 2, 1], [2, null, 1]]"),
],
),
(
(
"[{a: 1 b: 1} {a: 2 b: 2} {a: 3 b: 3}]",
"[{a: 1 c: 1} {a: 3 c: 3}]",
"a",
),
[
("--inner", "[[a, b, c]; [1, 1, 1], [3, 3, 3]]"),
("--left", "[[a, b, c]; [1, 1, 1], [2, 2, null], [3, 3, 3]]"),
("--right", "[[a, b, c]; [1, 1, 1], [3, 3, 3]]"),
("--outer", "[[a, b, c]; [1, 1, 1], [2, 2, null], [3, 3, 3]]"),
],
),
(
// create table l (a, c);
// create table r (a, b);
// insert into l (a, c) values (1, 1), (2, 2), (3, 3);
// insert into r (a, b) values (1, 1), (3, 3), (4, 4);
(
"[{a: 1 c: 1} {a: 2 c: 2} {a: 3 c: 3}]",
"[{a: 1 b: 1} {a: 3 b: 3} {a: 4 b: 4}]",
"a",
),
[
("--inner", "[[a, c, b]; [1, 1, 1], [3, 3, 3]]"),
("--left", "[[a, c, b]; [1, 1, 1], [2, 2, null], [3, 3, 3]]"),
// select * from l right outer join r on l.a = r.a;
("--right", "[[a, c, b]; [1, 1, 1], [3, 3, 3], [4, null, 4]]"),
(
"--outer",
"[[a, c, b]; [1, 1, 1], [2, 2, null], [3, 3, 3], [4, null, 4]]",
),
],
),
(
// a row in the left table does not have the join column
(
"[{a: 1 ref: 1} {a: 2 ref: 2} {a: 3}]",
"[{ref: 1 b: 1} {ref: 2 b: 2} {ref: 3 b: 3}]",
"ref",
),
[
("--inner", "[[a, ref, b]; [1, 1, 1], [2, 2, 2]]"),
(
"--left",
"[[a, ref, b]; [1, 1, 1], [2, 2, 2], [3, null, null]]",
),
(
"--right",
"[[a, ref, b]; [1, 1, 1], [2, 2, 2], [null, 3, 3]]",
),
(
"--outer",
"[[a, ref, b]; [1, 1, 1], [2, 2, 2], [3, null, null], [null, 3, 3]]",
),
],
),
(
// a row in the right table does not have the join column
(
"[{a: 1 ref: 1} {a: 2 ref: 2} {a: 3 ref: 3}]",
"[{ref: 1 b: 1} {ref: 2 b: 2} {b: 3}]",
"ref",
),
[
("--inner", "[[a, ref, b]; [1, 1, 1], [2, 2, 2]]"),
(
"--left",
"[[a, ref, b]; [1, 1, 1], [2, 2, 2], [3, 3, null]]",
),
(
"--right",
"[[a, ref, b]; [1, 1, 1], [2, 2, 2], [null, null, 3]]",
),
(
"--outer",
"[[a, ref, b]; [1, 1, 1], [2, 2, 2], [3, 3, null], [null, null, 3]]",
),
],
),
] {
for (join_type_, expected) in join_types {
if join_type_ == join_type {
let expr = format!("{left} | join {right} {join_type} {on} | to nuon");
let actual = nu!(expr).out;
assert_eq!(actual, expected);
// Test again with streaming input (using `each` to convert the input into a ListStream)
let to_list_stream = "each { |i| $i } | ";
let expr =
format!("{left} | {to_list_stream} join {right} {join_type} {on} | to nuon");
let actual = nu!(expr).out;
assert_eq!(actual, expected);
}
}
}
}
fn do_cases_where_result_differs_between_join_types_with_different_join_keys(join_type: &str) {
// .mode column
// .headers on
for ((left, right, left_on, right_on), join_types) in [
(
("[]", "[{z: 1}]", "a", "z"),
[
("--inner", "[]"),
("--left", "[]"),
("--right", "[[z]; [1]]"),
("--outer", "[[z]; [1]]"),
],
),
(
("[{a: 1}]", "[]", "a", "z"),
[
("--inner", "[]"),
("--left", "[[a]; [1]]"),
("--right", "[]"),
("--outer", "[[a]; [1]]"),
],
),
(
("[{a: 2 b: 1}]", "[{z: 1}]", "a", "z"),
[
("--inner", "[]"),
("--left", "[[a, b, z]; [2, 1, null]]"),
("--right", "[[a, b, z]; [null, null, 1]]"),
("--outer", "[[a, b, z]; [2, 1, null], [null, null, 1]]"),
],
),
(
("[{a: 1}]", "[{z: 2 b: 1}]", "a", "z"),
[
("--inner", "[]"),
("--left", "[[a, z, b]; [1, null, null]]"),
("--right", "[[a, z, b]; [null, 2, 1]]"),
("--outer", "[[a, z, b]; [1, null, null], [null, 2, 1]]"),
],
),
(
// create table l (a, b);
// create table r (a, b);
// insert into l (a, b) values (1, 2);
// insert into r (a, b) values (2, 1);
("[{a: 1 b: 2}]", "[{z: 2 b: 1}]", "a", "z"),
[
("--inner", "[]"),
("--left", "[[a, b, z, b_]; [1, 2, null, null]]"),
// select * from l right outer join r on l.a = r.z;
("--right", "[[a, b, z, b_]; [null, null, 2, 1]]"),
(
"--outer",
"[[a, b, z, b_]; [1, 2, null, null], [null, null, 2, 1]]",
),
],
),
(
("[{a: 1 b: 2}]", "[{z: 2 b: 1} {z: 1 b: 1}]", "a", "z"),
[
("--inner", "[[a, b, z, b_]; [1, 2, 1, 1]]"),
("--left", "[[a, b, z, b_]; [1, 2, 1, 1]]"),
(
"--right",
"[[a, b, z, b_]; [null, null, 2, 1], [1, 2, 1, 1]]",
),
(
"--outer",
"[[a, b, z, b_]; [1, 2, 1, 1], [null, null, 2, 1]]",
),
],
),
(
(
"[{a: 1 b: 1} {a: 2 b: 2} {a: 3 b: 3}]",
"[{z: 1 c: 1} {z: 3 c: 3}]",
"a",
"z",
),
[
("--inner", "[[a, b, z, c]; [1, 1, 1, 1], [3, 3, 3, 3]]"),
(
"--left",
"[[a, b, z, c]; [1, 1, 1, 1], [2, 2, null, null], [3, 3, 3, 3]]",
),
("--right", "[[a, b, z, c]; [1, 1, 1, 1], [3, 3, 3, 3]]"),
(
"--outer",
"[[a, b, z, c]; [1, 1, 1, 1], [2, 2, null, null], [3, 3, 3, 3]]",
),
],
),
(
// create table l (a, c);
// create table r (a, b);
// insert into l (a, c) values (1, 1), (2, 2), (3, 3);
// insert into r (a, b) values (1, 1), (3, 3), (4, 4);
(
"[{a: 1 c: 1} {a: 2 c: 2} {a: 3 c: 3}]",
"[{z: 1 b: 1} {z: 3 b: 3} {z: 4 b: 4}]",
"a",
"z",
),
[
("--inner", "[[a, c, z, b]; [1, 1, 1, 1], [3, 3, 3, 3]]"),
(
"--left",
"[[a, c, z, b]; [1, 1, 1, 1], [2, 2, null, null], [3, 3, 3, 3]]",
),
// select * from l right outer join r on l.a = r.z;
(
"--right",
"[[a, c, z, b]; [1, 1, 1, 1], [3, 3, 3, 3], [null, null, 4, 4]]",
),
(
"--outer",
"[[a, c, z, b]; [1, 1, 1, 1], [2, 2, null, null], [3, 3, 3, 3], [null, null, 4, 4]]",
),
],
),
] {
for (join_type_, expected) in join_types {
if join_type_ == join_type {
let expr =
format!("{left} | join {right} {join_type} {left_on} {right_on} | to nuon");
let actual = nu!(expr).out;
assert_eq!(actual, expected);
// Test again with streaming input (using `each` to convert the input into a ListStream)
let to_list_stream = "each { |i| $i } | ";
let expr = format!(
"{left} | {to_list_stream} join {right} {join_type} {left_on} {right_on} | to nuon"
);
let actual = nu!(expr).out;
assert_eq!(actual, expected);
}
}
}
}
#[test]
fn test_alternative_table_syntax() {
let join_type = "--inner";
for ((left, right, on), expected) in [
(("[{a: 1}]", "[{a: 1}]", "a"), "[[a]; [1]]"),
(("[{a: 1}]", "[[a]; [1]]", "a"), "[[a]; [1]]"),
(("[[a]; [1]]", "[{a: 1}]", "a"), "[[a]; [1]]"),
(("[[a]; [1]]", "[[a]; [1]]", "a"), "[[a]; [1]]"),
] {
let expr = format!("{left} | join {right} {join_type} {on} | to nuon");
let actual = nu!(&expr).out;
assert_eq!(actual, expected, "Expression was {}", &expr);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/alias.rs | crates/nu-command/tests/commands/alias.rs | use nu_test_support::fs::Stub::FileWithContentToBeTrimmed;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[ignore = "TODO?: Aliasing parser keywords does not work anymore"]
#[test]
fn alias_simple() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
alias bar = use sample_def.nu greet;
bar;
greet
"#);
assert_eq!(actual.out, "hello");
}
#[ignore = "TODO?: Aliasing parser keywords does not work anymore"]
#[test]
fn alias_hiding_1() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
overlay use ./activate-foo.nu;
scope aliases | find deactivate-foo | length
"#);
assert_eq!(actual.out, "1");
}
#[ignore = "TODO?: Aliasing parser keywords does not work anymore"]
#[test]
fn alias_hiding_2() {
let actual = nu!(cwd: "tests/fixtures/formats", r#"
overlay use ./activate-foo.nu;
deactivate-foo;
scope aliases | find deactivate-foo | length
"#);
assert_eq!(actual.out, "0");
}
#[test]
fn alias_fails_with_invalid_name() {
let err_msg = "name can't be a number, a filesize, or contain a hash # or caret ^";
let actual = nu!(r#" alias 1234 = echo "test" "#);
assert!(actual.err.contains(err_msg));
let actual = nu!(r#" alias 5gib = echo "test" "#);
assert!(actual.err.contains(err_msg));
let actual = nu!(r#" alias "te#t" = echo "test" "#);
assert!(actual.err.contains(err_msg));
let actual = nu!(r#" alias ^foo = echo "bar" "#);
assert!(actual.err.contains(err_msg));
}
#[test]
fn cant_alias_keyword() {
let actual = nu!(r#" alias ou = let "#);
assert!(actual.err.contains("cant_alias_keyword"));
}
#[test]
fn alias_wont_recurse() {
let actual = nu!("
module myspamsymbol {
export def myfoosymbol [prefix: string, msg: string] {
$prefix + $msg
}
};
use myspamsymbol myfoosymbol;
alias myfoosymbol = myfoosymbol 'hello';
myfoosymbol ' world'
");
assert_eq!(actual.out, "hello world");
assert!(actual.err.is_empty());
}
// Issue https://github.com/nushell/nushell/issues/8246
#[test]
fn alias_wont_recurse2() {
Playground::setup("alias_wont_recurse2", |dirs, sandbox| {
sandbox.with_files(&[FileWithContentToBeTrimmed(
"spam.nu",
r#"
def eggs [] { spam 'eggs' }
alias spam = spam 'spam'
"#,
)]);
let actual = nu!(cwd: dirs.test(), r#"
def spam [what: string] { 'spam ' + $what };
source spam.nu;
spam
"#);
assert_eq!(actual.out, "spam spam");
assert!(actual.err.is_empty());
})
}
#[test]
fn alias_invalid_expression() {
let actual = nu!(r#" alias spam = 'foo' "#);
assert!(actual.err.contains("cant_alias_expression"));
let actual = nu!(r#" alias spam = ([1 2 3] | length) "#);
assert!(actual.err.contains("cant_alias_expression"));
let actual = nu!(r#" alias spam = 0..12 "#);
assert!(actual.err.contains("cant_alias_expression"));
}
#[test]
fn alias_if() {
let actual = nu!(r#" alias spam = if true { 'spam' } else { 'eggs' }; spam "#);
assert_eq!(actual.out, "spam");
}
#[test]
fn alias_match() {
let actual = nu!(r#" alias spam = match 3 { 1..10 => 'yes!' }; spam "#);
assert_eq!(actual.out, "yes!");
}
// Issue https://github.com/nushell/nushell/issues/8103
#[test]
fn alias_multiword_name() {
let actual = nu!(r#"alias `foo bar` = echo 'test'; foo bar"#);
assert_eq!(actual.out, "test");
let actual = nu!(r#"alias 'foo bar' = echo 'test'; foo bar"#);
assert_eq!(actual.out, "test");
let actual = nu!(r#"alias "foo bar" = echo 'test'; foo bar"#);
assert_eq!(actual.out, "test");
}
#[test]
fn alias_ordering() {
let actual = nu!(r#"alias bar = echo; def echo [] { 'dummy echo' }; bar 'foo'"#);
assert_eq!(actual.out, "foo");
}
#[test]
fn alias_default_help() {
let actual = nu!("alias teapot = echo 'I am a beautiful teapot'; help teapot");
// There must be at least one line of help
let first_help_line = actual.out.lines().next().unwrap();
assert!(first_help_line.starts_with("Alias for `echo 'I am a beautiful teapot'`"));
}
#[test]
fn export_alias_with_overlay_use_works() {
let actual = nu!("export alias teapot = overlay use");
assert!(actual.err.is_empty())
}
#[test]
fn alias_flag() {
let actual = nu!("alias si = stor import");
assert!(actual.err.is_empty());
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/def.rs | crates/nu-command/tests/commands/def.rs | use nu_test_support::nu;
use nu_test_support::playground::Playground;
use std::fs;
#[test]
fn def_with_trailing_comma() {
let actual = nu!("def test-command [ foo: int, ] { $foo }; test-command 1");
assert!(actual.out == "1");
}
#[test]
fn def_with_comment() {
Playground::setup("def_with_comment", |dirs, _| {
let data = r#"
#My echo
export def e [arg] {echo $arg}
"#;
fs::write(dirs.root().join("def_test"), data).expect("Unable to write file");
let actual = nu!(
cwd: dirs.root(),
"use def_test e; help e | to json -r"
);
assert!(actual.out.contains("My echo\\n\\n"));
});
}
#[test]
fn def_with_param_comment() {
Playground::setup("def_with_param_comment", |dirs, _| {
let data = r#"
export def e [
param:string #My cool attractive param
] {echo $param};
"#;
fs::write(dirs.root().join("def_test"), data).expect("Unable to write file");
let actual = nu!(
cwd: dirs.root(),
"use def_test e; help e"
);
assert!(actual.out.contains(r#"My cool attractive param"#));
})
}
#[test]
fn def_errors_with_no_space_between_params_and_name_1() {
let actual = nu!("def test-command[] {}");
assert!(actual.err.contains("expected space"));
}
#[test]
fn def_errors_with_no_space_between_params_and_name_2() {
let actual = nu!("def --env test-command() {}");
assert!(actual.err.contains("expected space"));
}
#[test]
fn def_errors_with_multiple_short_flags() {
let actual = nu!("def test-command [ --long(-l)(-o) ] {}");
assert!(actual.err.contains("expected only one short flag"));
}
#[test]
fn def_errors_with_comma_before_alternative_short_flag() {
let actual = nu!("def test-command [ --long, (-l) ] {}");
assert!(actual.err.contains("expected parameter"));
}
#[test]
fn def_errors_with_comma_before_equals() {
let actual = nu!("def test-command [ foo, = 1 ] {}");
assert!(actual.err.contains("expected parameter"));
}
#[test]
fn def_errors_with_colon_before_equals() {
let actual = nu!("def test-command [ foo: = 1 ] {}");
assert!(actual.err.contains("expected type"));
}
#[test]
fn def_errors_with_comma_before_colon() {
let actual = nu!("def test-command [ foo, : int ] {}");
assert!(actual.err.contains("expected parameter"));
}
#[test]
fn def_errors_with_multiple_colons() {
let actual = nu!("def test-command [ foo::int ] {}");
assert!(actual.err.contains("expected type"));
}
#[test]
fn def_errors_with_multiple_types() {
let actual = nu!("def test-command [ foo:int:string ] {}");
assert!(actual.err.contains("expected parameter"));
}
#[test]
fn def_errors_with_trailing_colon() {
let actual = nu!("def test-command [ foo: int: ] {}");
assert!(actual.err.contains("expected parameter"));
}
#[test]
fn def_errors_with_trailing_default_value() {
let actual = nu!("def test-command [ foo: int = ] {}");
assert!(actual.err.contains("expected default value"));
}
#[test]
fn def_errors_with_multiple_commas() {
let actual = nu!("def test-command [ foo,,bar ] {}");
assert!(actual.err.contains("expected parameter"));
}
#[test]
fn def_fails_with_invalid_name() {
let err_msg = "command name can't be a number, a filesize, or contain a hash # or caret ^";
let actual = nu!(r#"def 1234 = echo "test""#);
assert!(actual.err.contains(err_msg));
let actual = nu!(r#"def 5gib = echo "test""#);
assert!(actual.err.contains(err_msg));
let actual = nu!("def ^foo [] {}");
assert!(actual.err.contains(err_msg));
}
#[test]
fn def_with_list() {
Playground::setup("def_with_list", |dirs, _| {
let data = r#"
def e [
param: list
] {echo $param};
"#;
fs::write(dirs.root().join("def_test"), data).expect("Unable to write file");
let actual = nu!(
cwd: dirs.root(),
"source def_test; e [one] | to json -r"
);
assert!(actual.out.contains(r#"one"#));
})
}
#[test]
fn def_with_default_list() {
Playground::setup("def_with_default_list", |dirs, _| {
let data = r#"
def f [
param: list = [one]
] {echo $param};
"#;
fs::write(dirs.root().join("def_test"), data).expect("Unable to write file");
let actual = nu!(
cwd: dirs.root(),
"source def_test; f | to json -r"
);
assert!(actual.out.contains(r#"["one"]"#));
})
}
#[test]
fn def_with_paren_params() {
let actual = nu!("def foo (x: int, y: int) { $x + $y }; foo 1 2");
assert_eq!(actual.out, "3");
}
#[test]
fn def_default_value_shouldnt_restrict_explicit_type() {
let actual = nu!("def foo [x: any = null] { $x }; foo 1");
assert_eq!(actual.out, "1");
let actual2 = nu!("def foo [--x: any = null] { $x }; foo --x 1");
assert_eq!(actual2.out, "1");
}
#[test]
fn def_default_value_should_restrict_implicit_type() {
let actual = nu!("def foo [x = 3] { $x }; foo 3.0");
assert!(actual.err.contains("expected int"));
let actual2 = nu!("def foo2 [--x = 3] { $x }; foo2 --x 3.0");
assert!(actual2.err.contains("expected int"));
}
#[test]
fn def_wrapped_with_block() {
let actual = nu!(
"def --wrapped foo [...rest] { print ($rest | str join ',' ) }; foo --bar baz -- -q -u -x"
);
assert_eq!(actual.out, "--bar,baz,--,-q,-u,-x");
}
#[test]
fn def_wrapped_from_module() {
let actual = nu!(r#"module spam {
export def --wrapped my-echo [...rest] { nu --testbin cococo ...$rest }
}
use spam
spam my-echo foo -b -as -9 --abc -- -Dxmy=AKOO - bar
"#);
assert!(
actual
.out
.contains("foo -b -as -9 --abc -- -Dxmy=AKOO - bar")
);
}
#[test]
fn def_cursed_env_flag_positions() {
let actual = nu!("def spam --env [] { $env.SPAM = 'spam' }; spam; $env.SPAM");
assert_eq!(actual.out, "spam");
let actual =
nu!("def spam --env []: nothing -> nothing { $env.SPAM = 'spam' }; spam; $env.SPAM");
assert_eq!(actual.out, "spam");
}
#[test]
#[ignore = "TODO: Investigate why it's not working, it might be the signature parsing"]
fn def_cursed_env_flag_positions_2() {
let actual = nu!("def spam [] --env { $env.SPAM = 'spam' }; spam; $env.SPAM");
assert_eq!(actual.out, "spam");
let actual = nu!("def spam [] { $env.SPAM = 'spam' } --env; spam; $env.SPAM");
assert_eq!(actual.out, "spam");
let actual =
nu!("def spam []: nothing -> nothing { $env.SPAM = 'spam' } --env; spam; $env.SPAM");
assert_eq!(actual.out, "spam");
}
#[test]
fn export_def_cursed_env_flag_positions() {
let actual = nu!("export def spam --env [] { $env.SPAM = 'spam' }; spam; $env.SPAM");
assert_eq!(actual.out, "spam");
let actual =
nu!("export def spam --env []: nothing -> nothing { $env.SPAM = 'spam' }; spam; $env.SPAM");
assert_eq!(actual.out, "spam");
}
#[test]
#[ignore = "TODO: Investigate why it's not working, it might be the signature parsing"]
fn export_def_cursed_env_flag_positions_2() {
let actual = nu!("export def spam [] --env { $env.SPAM = 'spam' }; spam; $env.SPAM");
assert_eq!(actual.out, "spam");
let actual = nu!("export def spam [] { $env.SPAM = 'spam' } --env; spam; $env.SPAM");
assert_eq!(actual.out, "spam");
let actual =
nu!("export def spam []: nothing -> nothing { $env.SPAM = 'spam' } --env; spam; $env.SPAM");
assert_eq!(actual.out, "spam");
}
#[test]
fn def_cursed_wrapped_flag_positions() {
let actual = nu!("def spam --wrapped [...rest] { $rest.0 }; spam --foo");
assert_eq!(actual.out, "--foo");
let actual = nu!("def spam --wrapped [...rest]: nothing -> nothing { $rest.0 }; spam --foo");
assert_eq!(actual.out, "--foo");
}
#[test]
#[ignore = "TODO: Investigate why it's not working, it might be the signature parsing"]
fn def_cursed_wrapped_flag_positions_2() {
let actual = nu!("def spam [...rest] --wrapped { $rest.0 }; spam --foo");
assert_eq!(actual.out, "--foo");
let actual = nu!("def spam [...rest] { $rest.0 } --wrapped; spam --foo");
assert_eq!(actual.out, "--foo");
let actual = nu!("def spam [...rest]: nothing -> nothing { $rest.0 } --wrapped; spam --foo");
assert_eq!(actual.out, "--foo");
}
#[test]
fn def_wrapped_missing_rest_error() {
let actual = nu!("def --wrapped spam [] {}");
assert!(actual.err.contains("missing_positional"))
}
#[test]
fn def_wrapped_wrong_rest_type_error() {
let actual = nu!("def --wrapped spam [...eggs: list<string>] { $eggs }");
assert!(actual.err.contains("type_mismatch_help"));
assert!(actual.err.contains("of ...eggs to 'string'"));
}
#[test]
fn def_env_wrapped() {
let actual = nu!(
"def --env --wrapped spam [...eggs: string] { $env.SPAM = $eggs.0 }; spam bacon; $env.SPAM"
);
assert_eq!(actual.out, "bacon");
}
#[test]
fn def_env_wrapped_no_help() {
let actual = nu!("def --wrapped foo [...rest] { echo $rest }; foo -h | to json --raw");
assert_eq!(actual.out, r#"["-h"]"#);
}
#[test]
fn def_recursive_func_should_work() {
let actual = nu!("def bar [] { let x = 1; ($x | foo) }; def foo [] { foo }");
assert!(actual.err.is_empty());
let actual = nu!(r#"
def recursive [c: int] {
if ($c == 0) { return }
if ($c mod 2 > 0) {
$in | recursive ($c - 1)
} else {
recursive ($c - 1)
}
}"#);
assert!(actual.err.is_empty());
}
#[test]
fn export_def_recursive_func_should_work() {
let actual = nu!("export def bar [] { let x = 1; ($x | foo) }; export def foo [] { foo }");
assert!(actual.err.is_empty());
let actual = nu!(r#"
export def recursive [c: int] {
if ($c == 0) { return }
if ($c mod 2 > 0) {
$in | recursive ($c - 1)
} else {
recursive ($c - 1)
}
}"#);
assert!(actual.err.is_empty());
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/semicolon.rs | crates/nu-command/tests/commands/semicolon.rs | use nu_test_support::nu;
use nu_test_support::playground::Playground;
#[test]
fn semicolon_allows_lhs_to_complete() {
Playground::setup("create_test_1", |dirs, _sandbox| {
let actual = nu!(
cwd: dirs.test(),
"touch i_will_be_created_semi.txt; echo done"
);
let path = dirs.test().join("i_will_be_created_semi.txt");
assert!(path.exists());
assert_eq!(actual.out, "done");
})
}
#[test]
fn semicolon_lhs_error_stops_processing() {
let actual = nu!("where 1 1; echo done");
assert!(!actual.out.contains("done"));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/window.rs | crates/nu-command/tests/commands/window.rs | use nu_test_support::nu;
#[test]
fn window_size_negative() {
let actual = nu!("[0 1 2] | window -1");
assert!(actual.err.contains("positive"));
}
#[test]
fn window_size_zero() {
let actual = nu!("[0 1 2] | window 0");
assert!(actual.err.contains("zero"));
}
#[test]
fn window_size_not_int() {
let actual = nu!("[0 1 2] | window (if true { 1sec })");
assert!(actual.err.contains("can't convert"));
}
#[test]
fn stride_negative() {
let actual = nu!("[0 1 2] | window 1 -s -1");
assert!(actual.err.contains("positive"));
}
#[test]
fn stride_zero() {
let actual = nu!("[0 1 2] | window 1 -s 0");
assert!(actual.err.contains("zero"));
}
#[test]
fn stride_not_int() {
let actual = nu!("[0 1 2] | window 1 -s (if true { 1sec })");
assert!(actual.err.contains("can't convert"));
}
#[test]
fn empty() {
let actual = nu!("[] | window 2 | is-empty");
assert_eq!(actual.out, "true");
}
#[test]
fn list_stream() {
let actual = nu!("([0 1 2] | every 1 | window 2) == ([0 1 2] | window 2)");
assert_eq!(actual.out, "true");
}
#[test]
fn table_stream() {
let actual = nu!(
"([[foo bar]; [0 1] [2 3] [4 5]] | every 1 | window 2) == ([[foo bar]; [0 1] [2 3] [4 5]] | window 2)"
);
assert_eq!(actual.out, "true");
}
#[test]
fn no_empty_chunks() {
let actual = nu!("([0 1 2 3 4 5] | window 3 -s 3 -r | length) == 2");
assert_eq!(actual.out, "true");
}
#[test]
fn same_as_chunks() {
let actual = nu!("([0 1 2 3 4] | window 2 -s 2 -r) == ([0 1 2 3 4 ] | chunks 2)");
assert_eq!(actual.out, "true");
}
#[test]
fn stride_equal_to_window_size() {
let actual = nu!("([0 1 2 3] | window 2 -s 2 | flatten) == [0 1 2 3]");
assert_eq!(actual.out, "true");
}
#[test]
fn stride_greater_than_window_size() {
let actual = nu!("([0 1 2 3 4] | window 2 -s 3 | flatten) == [0 1 3 4]");
assert_eq!(actual.out, "true");
}
#[test]
fn stride_less_than_window_size() {
let actual = nu!("([0 1 2 3 4 5] | window 3 -s 2 | length) == 2");
assert_eq!(actual.out, "true");
}
#[test]
fn stride_equal_to_window_size_remainder() {
let actual = nu!("([0 1 2 3 4] | window 2 -s 2 -r | flatten) == [0 1 2 3 4]");
assert_eq!(actual.out, "true");
}
#[test]
fn stride_greater_than_window_size_remainder() {
let actual = nu!("([0 1 2 3 4] | window 2 -s 3 -r | flatten) == [0 1 3 4]");
assert_eq!(actual.out, "true");
}
#[test]
fn stride_less_than_window_size_remainder() {
let actual = nu!("([0 1 2 3 4 5] | window 3 -s 2 -r | length) == 3");
assert_eq!(actual.out, "true");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/into_int.rs | crates/nu-command/tests/commands/into_int.rs | use chrono::{DateTime, FixedOffset, NaiveDate, TimeZone};
use rstest::rstest;
use nu_test_support::nu;
#[test]
fn into_int_filesize() {
let actual = nu!("echo 1kb | into int | each { |it| $it / 1000 }");
assert!(actual.out.contains('1'));
}
#[test]
fn into_int_filesize2() {
let actual = nu!("echo 1kib | into int | each { |it| $it / 1024 }");
assert!(actual.out.contains('1'));
}
#[test]
fn into_int_int() {
let actual = nu!("echo 1024 | into int | each { |it| $it / 1024 }");
assert!(actual.out.contains('1'));
}
#[test]
fn into_int_binary() {
let actual = nu!("echo 0x[01010101] | into int");
assert!(actual.out.contains("16843009"));
}
#[test]
fn into_int_binary_signed() {
let actual = nu!("echo 0x[f0] | into int --signed");
assert!(actual.out.contains("-16"));
}
#[test]
fn into_int_binary_back_and_forth() {
let actual = nu!("echo 0x[f0] | into int | into binary | to nuon");
assert!(actual.out.contains("0x[F000000000000000]"));
}
#[test]
fn into_int_binary_signed_back_and_forth() {
let actual = nu!("echo 0x[f0] | into int --signed | into binary | to nuon");
assert!(actual.out.contains("0x[F0FFFFFFFFFFFFFF]"));
}
#[test]
fn into_int_binary_empty() {
let actual = nu!("echo 0x[] | into int");
assert!(actual.out.contains('0'))
}
#[test]
fn into_int_binary_signed_empty() {
let actual = nu!("echo 0x[] | into int --signed");
assert!(actual.out.contains('0'))
}
#[test]
#[ignore]
fn into_int_datetime1() {
let dt = DateTime::parse_from_rfc3339("1983-04-13T12:09:14.123456789+00:00");
eprintln!("dt debug {dt:?}");
assert_eq!(
dt,
Ok(FixedOffset::east_opt(0)
.unwrap()
.from_local_datetime(
&NaiveDate::from_ymd_opt(1983, 4, 13)
.unwrap()
.and_hms_nano_opt(12, 9, 14, 123456789)
.unwrap()
)
.unwrap())
);
let dt_nano = dt.expect("foo").timestamp_nanos_opt().unwrap_or_default();
assert_eq!(dt_nano % 1_000_000_000, 123456789);
}
#[rstest]
#[case("1983-04-13T12:09:14.123456789-05:00", "419101754123456789")] // full precision
#[case("1983-04-13T12:09:14.456789-05:00", "419101754456789000")] // microsec
#[case("1983-04-13T12:09:14-05:00", "419101754000000000")] // sec
#[case("2052-04-13T12:09:14.123456789-05:00", "2596640954123456789")] // future date > 2038 epoch
#[case("1902-04-13T12:09:14.123456789-05:00", "-2137042245876543211")] // past date < 1970
fn into_int_datetime(#[case] time_in: &str, #[case] int_out: &str) {
let actual = nu!(&format!(
r#""{time_in}" | into datetime --format "%+" | into int"#
));
assert_eq!(int_out, actual.out);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/rotate.rs | crates/nu-command/tests/commands/rotate.rs | use nu_test_support::nu;
#[test]
fn counter_clockwise() {
let table = r#"[
[col1, col2, EXPECTED];
[---, "|||", XX1]
[---, "|||", XX2]
[---, "|||", XX3]
]"#;
let expected = nu!(r#"
[
[ column0, column1, column2, column3];
[ EXPECTED, XX1, XX2, XX3]
[ col2, "|||", "|||", "|||"]
[ col1, ---, ---, ---]
]
| where column0 == EXPECTED
| get column1 column2 column3
| str join "-"
"#);
let actual = nu!(format!(
r#"
{table}
| rotate --ccw
| where column0 == EXPECTED
| get column1 column2 column3
| str join "-"
"#
));
assert_eq!(actual.out, expected.out);
}
#[test]
fn clockwise() {
let table = r#"[
[col1, col2, EXPECTED];
[ ---, "|||", XX1]
[ ---, "|||", XX2]
[ ---, "|||", XX3]
]"#;
let expected = nu!(r#"
[
[ column0, column1, column2, column3];
[ ---, ---, ---, col1]
[ "|||", "|||", "|||", col2]
[ XX3, XX2, XX1, EXPECTED]
]
| where column3 == EXPECTED
| get column0 column1 column2
| str join "-"
"#);
let actual = nu!(format!(
r#"
{table}
| rotate
| where column3 == EXPECTED
| get column0 column1 column2
| str join "-"
"#,
));
assert_eq!(actual.out, expected.out);
}
#[test]
fn different_cols_vals_err() {
let actual = nu!("[[[one], [two, three]]] | first | rotate");
assert!(
actual
.err
.contains("Attempted to create a record from different number of columns and values")
)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.