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/tests/commands/reject.rs
crates/nu-command/tests/commands/reject.rs
use nu_test_support::nu; #[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] ] | reject type first_name | columns | str join ", " "#); assert_eq!(actual.out, "last_name, rusty_at"); } #[test] fn skip_cell_rejection() { let actual = nu!("[ {a: 1, b: 2,c:txt}, { a:val } ] | reject a | get c?.0"); assert_eq!(actual.out, "txt"); } #[test] fn complex_nested_columns() { let actual = nu!(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"] ] } } | reject nu."0xATYKARNU" nu.committers | get nu | columns | str join ", " "#); assert_eq!(actual.out, "releases"); } #[test] fn ignores_duplicate_columns_rejected() { let actual = nu!(r#" echo [ ["first name", "last name"]; [Andrés Robalino] [Andrés Jnth] ] | reject "first name" "first name" | columns | str join ", " "#); assert_eq!(actual.out, "last name"); } #[test] fn ignores_duplicate_rows_rejected() { let actual = nu!("[[a,b];[1 2] [3 4] [5 6]] | reject 2 2 | to nuon"); assert_eq!(actual.out, "[[a, b]; [1, 2], [3, 4]]"); } #[test] fn reject_record_from_raw_eval() { let actual = nu!(r#"{"a": 3} | reject a | describe"#); assert!(actual.out.contains("record")); } #[test] fn reject_table_from_raw_eval() { let actual = nu!(r#"[{"a": 3}] | reject a"#); assert!(actual.out.contains("record 0 fields")); } #[test] fn reject_nested_field() { let actual = nu!("{a:{b:3,c:5}} | reject a.b | debug"); assert_eq!(actual.out, "{a: {c: 5}}"); } #[test] fn reject_optional_column() { let actual = nu!("{} | reject foo? | to nuon"); assert_eq!(actual.out, "{}"); let actual = nu!("[{}] | reject foo? | to nuon"); assert_eq!(actual.out, "[{}]"); let actual = nu!("[{} {foo: 2}] | reject foo? | to nuon"); assert_eq!(actual.out, "[{}, {}]"); let actual = nu!("[{foo: 1} {foo: 2}] | reject foo? | to nuon"); assert_eq!(actual.out, "[{}, {}]"); } #[test] fn reject_optional_row() { let actual = nu!("[{foo: 'bar'}] | reject 3? | to nuon"); assert_eq!(actual.out, "[[foo]; [bar]]"); } #[test] fn reject_columns_with_list_spread() { let actual = nu!( "let arg = [type size]; [[name type size];[Cargo.toml file 10mb] [Cargo.lock file 10mb] [src dir 100mb]] | reject ...$arg | to nuon" ); assert_eq!( actual.out, r#"[[name]; ["Cargo.toml"], ["Cargo.lock"], [src]]"# ); } #[test] fn reject_rows_with_list_spread() { let actual = nu!( "let arg = [2 0]; [[name type size];[Cargo.toml file 10mb] [Cargo.lock file 10mb] [src dir 100mb]] | reject ...$arg | to nuon" ); assert_eq!( actual.out, r#"[[name, type, size]; ["Cargo.lock", file, 10000000b]]"# ); } #[test] fn reject_mixed_with_list_spread() { let actual = nu!( "let arg = [type 2]; [[name type size];[Cargp.toml file 10mb] [ Cargo.lock file 10mb] [src dir 100mb]] | reject ...$arg | to nuon" ); assert_eq!( actual.out, r#"[[name, size]; ["Cargp.toml", 10000000b], ["Cargo.lock", 10000000b]]"# ); } #[test] fn reject_multiple_rows_ascending() { let actual = nu!("[[a,b];[1 2] [3 4] [5 6]] | reject 1 2 | to nuon"); assert_eq!(actual.out, "[[a, b]; [1, 2]]"); } #[test] fn reject_multiple_rows_descending() { let actual = nu!("[[a,b];[1 2] [3 4] [5 6]] | reject 2 1 | to nuon"); assert_eq!(actual.out, "[[a, b]; [1, 2]]"); } #[test] fn test_ignore_errors_flag() { let actual = nu!("[[a, b]; [1, 2], [3, 4], [5, 6]] | reject 5 -o | to nuon"); assert_eq!(actual.out, "[[a, b]; [1, 2], [3, 4], [5, 6]]"); } #[test] fn test_ignore_errors_flag_var() { let actual = nu!("let arg = [5 c]; [[a, b]; [1, 2], [3, 4], [5, 6]] | reject ...$arg -o | to nuon"); assert_eq!(actual.out, "[[a, b]; [1, 2], [3, 4], [5, 6]]"); } #[test] fn test_works_with_integer_path_and_stream() { let actual = nu!("[[N u s h e l l]] | flatten | reject 1 | to nuon"); assert_eq!(actual.out, "[N, s, h, e, l, l]"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/each.rs
crates/nu-command/tests/commands/each.rs
use nu_test_support::nu; #[test] fn each_works_separately() { let actual = nu!("echo [1 2 3] | each { |it| echo $it 10 | math sum } | to json -r"); assert_eq!(actual.out, "[11,12,13]"); } #[test] fn each_group_works() { let actual = nu!("echo [1 2 3 4 5 6] | chunks 3 | to json --raw"); assert_eq!(actual.out, "[[1,2,3],[4,5,6]]"); } #[test] fn each_window() { let actual = nu!("echo [1 2 3 4] | window 3 | to json --raw"); assert_eq!(actual.out, "[[1,2,3],[2,3,4]]"); } #[test] fn each_window_stride() { let actual = nu!("echo [1 2 3 4 5 6] | window 3 -s 2 | to json --raw"); assert_eq!(actual.out, "[[1,2,3],[3,4,5]]"); } #[test] fn each_no_args_in_block() { let actual = nu!("echo [[foo bar]; [a b] [c d] [e f]] | each {|i| $i | to json -r } | get 1"); assert_eq!(actual.out, r#"{"foo":"c","bar":"d"}"#); } #[test] fn each_implicit_it_in_block() { let actual = nu!( "echo [[foo bar]; [a b] [c d] [e f]] | each { |it| nu --testbin cococo $it.foo } | str join" ); assert_eq!(actual.out, "ace"); } #[test] fn each_uses_enumerate_index() { let actual = nu!("[7 8 9 10] | enumerate | each {|el| $el.index } | to nuon"); assert_eq!(actual.out, "[0, 1, 2, 3]"); } #[test] fn each_while_uses_enumerate_index() { let actual = nu!("[7 8 9 10] | enumerate | each while {|el| $el.index } | to nuon"); assert_eq!(actual.out, "[0, 1, 2, 3]"); } #[test] fn errors_in_nested_each_show() { let actual = nu!("[[1,2]] | each {|x| $x | each {|y| error make {msg: \"oh noes\"} } }"); assert!(actual.err.contains("oh noes")) } #[test] fn errors_in_nested_each_full_chain() { let actual = nu!(r#" 0..1 | each {|i| 0..1 | each {|j| error make {msg: boom} } } "#); let eval_block_with_input_count = actual.err.matches("eval_block_with_input").count(); assert_eq!(eval_block_with_input_count, 2); } #[test] fn each_noop_on_single_null() { let actual = nu!("null | each { \"test\" } | describe"); assert_eq!(actual.out, "nothing"); } #[test] fn each_flatten_dont_collect() { let collected = nu!(r##" def round [] { each {|e| print -n $"\(($e)\)"; $e } } def square [] { each {|e| print -n $"[($e)]"; $e } } [0 3] | each {|e| $e..<($e + 3) | round } | flatten | square | ignore "##); assert_eq!(collected.out, r#"(0)(1)(2)[0][1][2](3)(4)(5)[3][4][5]"#); let streamed = nu!(r##" def round [] { each {|e| print -n $"\(($e)\)"; $e } } def square [] { each {|e| print -n $"[($e)]"; $e } } [0 3] | each --flatten {|e| $e..<($e + 3) | round } | square | ignore "##); assert_eq!(streamed.out, r#"(0)[0](1)[1](2)[2](3)[3](4)[4](5)[5]"#); }
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_filesize.rs
crates/nu-command/tests/commands/into_filesize.rs
use nu_test_support::nu; #[test] fn int() { let actual = nu!("1 | into filesize"); assert!(actual.out.contains("1 B")); } #[test] fn float() { let actual = nu!("1.2 | into filesize"); assert!(actual.out.contains("1 B")); } #[test] fn str() { let actual = nu!("'2000' | into filesize"); assert!(actual.out.contains("2.0 kB")); } #[test] fn str_newline() { let actual = nu!(r#" "2000 " | into filesize "#); assert!(actual.out.contains("2.0 kB")); } #[test] fn str_many_newlines() { let actual = nu!(r#" "2000 " | into filesize "#); assert!(actual.out.contains("2.0 kB")); } #[test] fn filesize() { let actual = nu!("3kB | into filesize"); assert!(actual.out.contains("3.0 kB")); } #[test] fn negative_filesize() { let actual = nu!("-3kB | into filesize"); assert!(actual.out.contains("-3.0 kB")); } #[test] fn negative_str_filesize() { let actual = nu!("'-3kB' | into filesize"); assert!(actual.out.contains("-3.0 kB")); } #[test] fn wrong_negative_str_filesize() { let actual = nu!("'--3kB' | into filesize"); assert!(actual.err.contains("can't convert string to filesize")); } #[test] fn large_negative_str_filesize() { let actual = nu!("'-10000PB' | into filesize"); assert!(actual.err.contains("can't convert string to filesize")); } #[test] fn negative_str() { let actual = nu!("'-1' | into filesize"); assert!(actual.out.contains("-1 B")); } #[test] fn wrong_negative_str() { let actual = nu!("'--1' | into filesize"); assert!(actual.err.contains("can't convert string to filesize")); } #[test] fn positive_str_filesize() { let actual = nu!("'+1kB' | into filesize"); assert!(actual.out.contains("1.0 kB")); } #[test] fn wrong_positive_str_filesize() { let actual = nu!("'++1kB' | into filesize"); assert!(actual.err.contains("can't convert string to filesize")); } #[test] fn large_positive_str_filesize() { let actual = nu!("'+10000PB' | into filesize"); assert!(actual.err.contains("can't convert string to filesize")); } #[test] fn positive_str() { let actual = nu!("'+1' | into filesize"); assert!(actual.out.contains("1 B")); } #[test] fn wrong_positive_str() { let actual = nu!("'++1' | into filesize"); assert!(actual.err.contains("can't convert string to filesize")); } #[test] fn invalid_str() { let actual = nu!("'42.0 42.0 kB' | into filesize"); assert!(actual.err.contains("can't convert string to filesize")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/lines.rs
crates/nu-command/tests/commands/lines.rs
use nu_test_support::nu; #[test] fn lines() { let actual = nu!(cwd: "tests/fixtures/formats", r#" open cargo_sample.toml -r | lines | skip while {|it| $it != "[dependencies]" } | skip 1 | first | split column "=" | get column0.0 | str trim "#); assert_eq!(actual.out, "rustyline"); } #[test] fn lines_proper_buffering() { let actual = nu!(cwd: "tests/fixtures/formats", " open lines_test.txt -r | lines | str length | to json -r "); assert_eq!(actual.out, "[8193,3]"); } #[test] fn lines_multi_value_split() { let actual = nu!(cwd: "tests/fixtures/formats", " open sample-simple.json | get first second | lines | length "); assert_eq!(actual.out, "6"); } /// test whether this handles CRLF and LF in the same input #[test] fn lines_mixed_line_endings() { let actual = nu!(cwd: "tests/fixtures/formats", r#" "foo\nbar\r\nquux" | lines | length "#); assert_eq!(actual.out, "3"); } #[cfg(not(windows))] #[test] fn lines_on_error() { let actual = nu!("open . | lines"); assert!(actual.err.contains("Is a directory")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/save.rs
crates/nu-command/tests/commands/save.rs
use nu_test_support::fs::{Stub, file_contents}; use nu_test_support::nu; use nu_test_support::playground::Playground; use std::io::Write; #[test] fn writes_out_csv() { Playground::setup("save_test_2", |dirs, sandbox| { sandbox.with_files(&[]); let expected_file = dirs.test().join("cargo_sample.csv"); nu!( cwd: dirs.root(), r#"[[name, version, description, license, edition]; [nu, "0.14", "A new type of shell", "MIT", "2018"]] | save save_test_2/cargo_sample.csv"#, ); let actual = file_contents(expected_file); println!("{actual}"); assert!(actual.contains("nu,0.14,A new type of shell,MIT,2018")); }) } #[test] fn writes_out_list() { Playground::setup("save_test_3", |dirs, sandbox| { sandbox.with_files(&[]); let expected_file = dirs.test().join("list_sample.txt"); nu!( cwd: dirs.root(), "[a b c d] | save save_test_3/list_sample.txt", ); let actual = file_contents(expected_file); println!("{actual}"); assert_eq!(actual, "a\nb\nc\nd\n") }) } #[test] fn save_append_will_create_file_if_not_exists() { Playground::setup("save_test_3", |dirs, sandbox| { sandbox.with_files(&[]); let expected_file = dirs.test().join("new-file.txt"); nu!( cwd: dirs.root(), r#"'hello' | save --raw --append save_test_3/new-file.txt"#, ); let actual = file_contents(expected_file); println!("{actual}"); assert_eq!(actual, "hello"); }) } #[test] fn save_append_will_not_overwrite_content() { Playground::setup("save_test_4", |dirs, sandbox| { sandbox.with_files(&[]); let expected_file = dirs.test().join("new-file.txt"); { let mut file = std::fs::File::create(&expected_file).expect("Failed to create test file"); file.write_all("hello ".as_bytes()) .expect("Failed to write to test file"); file.flush().expect("Failed to flush io") } nu!( cwd: dirs.root(), r#"'world' | save --append save_test_4/new-file.txt"#, ); let actual = file_contents(expected_file); println!("{actual}"); assert_eq!(actual, "hello world"); }) } #[test] fn save_stderr_and_stdout_to_same_file() { Playground::setup("save_test_5", |dirs, sandbox| { sandbox.with_files(&[]); let actual = nu!( cwd: dirs.root(), r#" $env.FOO = "bar"; $env.BAZ = "ZZZ"; do -c {nu -n -c 'nu --testbin echo_env FOO; nu --testbin echo_env_stderr BAZ'} | save -r save_test_5/new-file.txt --stderr save_test_5/new-file.txt "#, ); assert!( actual .err .contains("can't save both input and stderr input to the same file") ); }) } #[test] fn save_stderr_and_stdout_to_diff_file() { Playground::setup("save_test_6", |dirs, sandbox| { sandbox.with_files(&[]); let expected_file = dirs.test().join("log.txt"); let expected_stderr_file = dirs.test().join("err.txt"); nu!( cwd: dirs.root(), r#" $env.FOO = "bar"; $env.BAZ = "ZZZ"; do -c {nu -n -c 'nu --testbin echo_env FOO; nu --testbin echo_env_stderr BAZ'} | save -r save_test_6/log.txt --stderr save_test_6/err.txt "#, ); let actual = file_contents(expected_file); assert!(actual.contains("bar")); assert!(!actual.contains("ZZZ")); let actual = file_contents(expected_stderr_file); assert!(actual.contains("ZZZ")); assert!(!actual.contains("bar")); }) } #[test] fn save_string_and_stream_as_raw() { Playground::setup("save_test_7", |dirs, sandbox| { sandbox.with_files(&[]); let expected_file = dirs.test().join("temp.html"); nu!( cwd: dirs.root(), r#" "<!DOCTYPE html><html><body><a href='http://example.org/'>Example</a></body></html>" | save save_test_7/temp.html "#, ); let actual = file_contents(expected_file); assert_eq!( actual, r#"<!DOCTYPE html><html><body><a href='http://example.org/'>Example</a></body></html>"# ) }) } #[test] fn save_not_override_file_by_default() { Playground::setup("save_test_8", |dirs, sandbox| { sandbox.with_files(&[Stub::EmptyFile("log.txt")]); let actual = nu!( cwd: dirs.root(), r#""abcd" | save save_test_8/log.txt"# ); assert!(actual.err.contains("Destination file already exists")); }) } #[test] fn save_override_works() { Playground::setup("save_test_9", |dirs, sandbox| { sandbox.with_files(&[Stub::EmptyFile("log.txt")]); let expected_file = dirs.test().join("log.txt"); nu!( cwd: dirs.root(), r#""abcd" | save save_test_9/log.txt -f"# ); let actual = file_contents(expected_file); assert_eq!(actual, "abcd"); }) } #[test] fn save_failure_not_overrides() { Playground::setup("save_test_10", |dirs, sandbox| { sandbox.with_files(&[Stub::FileWithContent("result.toml", "Old content")]); let expected_file = dirs.test().join("result.toml"); nu!( cwd: dirs.root(), // Writing number to file as toml fails "3 | save save_test_10/result.toml -f" ); let actual = file_contents(expected_file); assert_eq!(actual, "Old content"); }) } #[test] fn save_append_works_on_stderr() { Playground::setup("save_test_11", |dirs, sandbox| { sandbox.with_files(&[ Stub::FileWithContent("log.txt", "Old"), Stub::FileWithContent("err.txt", "Old Err"), ]); let expected_file = dirs.test().join("log.txt"); let expected_stderr_file = dirs.test().join("err.txt"); nu!( cwd: dirs.root(), r#" $env.FOO = " New"; $env.BAZ = " New Err"; do -i {nu -n -c 'nu --testbin echo_env FOO; nu --testbin echo_env_stderr BAZ'} | save -a -r save_test_11/log.txt --stderr save_test_11/err.txt"#, ); let actual = file_contents(expected_file); assert_eq!(actual, "Old New\n"); let actual = file_contents(expected_stderr_file); assert_eq!(actual, "Old Err New Err\n"); }) } #[test] fn save_not_overrides_err_by_default() { Playground::setup("save_test_12", |dirs, sandbox| { sandbox.with_files(&[Stub::FileWithContent("err.txt", "Old Err")]); let actual = nu!( cwd: dirs.root(), r#" $env.FOO = " New"; $env.BAZ = " New Err"; do -i {nu -n -c 'nu --testbin echo_env FOO; nu --testbin echo_env_stderr BAZ'} | save -r save_test_12/log.txt --stderr save_test_12/err.txt"#, ); assert!(actual.err.contains("Destination file already exists")); }) } #[test] fn save_override_works_stderr() { Playground::setup("save_test_13", |dirs, sandbox| { sandbox.with_files(&[ Stub::FileWithContent("log.txt", "Old"), Stub::FileWithContent("err.txt", "Old Err"), ]); let expected_file = dirs.test().join("log.txt"); let expected_stderr_file = dirs.test().join("err.txt"); nu!( cwd: dirs.root(), r#" $env.FOO = "New"; $env.BAZ = "New Err"; do -i {nu -n -c 'nu --testbin echo_env FOO; nu --testbin echo_env_stderr BAZ'} | save -f -r save_test_13/log.txt --stderr save_test_13/err.txt"#, ); let actual = file_contents(expected_file); assert_eq!(actual, "New\n"); let actual = file_contents(expected_stderr_file); assert_eq!(actual, "New Err\n"); }) } #[test] fn save_list_stream() { Playground::setup("save_test_13", |dirs, sandbox| { sandbox.with_files(&[]); let expected_file = dirs.test().join("list_sample.txt"); nu!( cwd: dirs.root(), "[a b c d] | each {|i| $i} | save -r save_test_13/list_sample.txt", ); let actual = file_contents(expected_file); assert_eq!(actual, "a\nb\nc\nd\n") }) } #[test] fn writes_out_range() { Playground::setup("save_test_14", |dirs, sandbox| { sandbox.with_files(&[]); let expected_file = dirs.test().join("list_sample.json"); nu!( cwd: dirs.root(), "1..3 | save save_test_14/list_sample.json", ); let actual = file_contents(expected_file); println!("{actual}"); assert_eq!(actual, "[\n 1,\n 2,\n 3\n]") }) } // https://github.com/nushell/nushell/issues/10044 #[test] fn save_file_correct_relative_path() { Playground::setup("save_test_15", |dirs, sandbox| { sandbox.with_files(&[Stub::FileWithContent( "test.nu", r#" export def main [] { let foo = "foo" mkdir bar cd bar 'foo!' | save $foo } "#, )]); let expected_file = dirs.test().join("bar/foo"); nu!( cwd: dirs.test(), r#"use test.nu; test"# ); let actual = file_contents(expected_file); assert_eq!(actual, "foo!"); }) } #[test] fn save_same_file_with_extension() { Playground::setup("save_test_16", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " echo 'world' | save --raw hello.md; open --raw hello.md | save --raw --force hello.md "); assert!( actual .err .contains("pipeline input and output are the same file") ); }) } #[test] fn save_same_file_with_extension_pipeline() { Playground::setup("save_test_17", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " echo 'world' | save --raw hello.md; open --raw hello.md | prepend 'hello' | save --raw --force hello.md "); assert!( actual .err .contains("pipeline input and output are the same file") ); }) } #[test] fn save_same_file_without_extension() { Playground::setup("save_test_18", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " echo 'world' | save hello; open hello | save --force hello "); assert!( actual .err .contains("pipeline input and output are the same file") ); }) } #[test] fn save_same_file_without_extension_pipeline() { Playground::setup("save_test_19", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " echo 'world' | save hello; open hello | prepend 'hello' | save --force hello "); assert!( actual .err .contains("pipeline input and output are the same file") ); }) } #[test] fn save_with_custom_converter() { Playground::setup("save_with_custom_converter", |dirs, _| { let file = dirs.test().join("test.ndjson"); nu!(cwd: dirs.test(), r#" def "to ndjson" []: any -> string { each { to json --raw } | to text --no-newline } ; {a: 1, b: 2} | save test.ndjson "#); let actual = file_contents(file); assert_eq!(actual, r#"{"a":1,"b":2}"#); }) } #[test] fn save_same_file_with_collect() { Playground::setup("save_test_20", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " echo 'world' | save hello; open hello | prepend 'hello' | collect | save --force hello; open hello "); assert!(actual.status.success()); assert_eq!("helloworld", actual.out); }) } #[test] fn save_same_file_with_collect_and_filter() { Playground::setup("save_test_21", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " echo 'world' | save hello; open hello | prepend 'hello' | collect | filter { true } | save --force hello; open hello "); assert!(actual.status.success()); assert_eq!("helloworld", actual.out); }) } #[test] fn save_from_child_process_dont_sink_stderr() { Playground::setup("save_test_22", |dirs, sandbox| { sandbox.with_files(&[ Stub::FileWithContent("log.txt", "Old"), Stub::FileWithContent("err.txt", "Old Err"), ]); let expected_file = dirs.test().join("log.txt"); let expected_stderr_file = dirs.test().join("err.txt"); let actual = nu!( cwd: dirs.root(), r#" $env.FOO = " New"; $env.BAZ = " New Err"; do -i {nu -n -c 'nu --testbin echo_env FOO; nu --testbin echo_env_stderr BAZ'} | save -a -r save_test_22/log.txt"#, ); assert_eq!(actual.err.trim_end(), " New Err"); let actual = file_contents(expected_file); assert_eq!(actual.trim_end(), "Old New"); let actual = file_contents(expected_stderr_file); assert_eq!(actual.trim_end(), "Old Err"); }) } #[test] fn parent_redirection_doesnt_affect_save() { Playground::setup("save_test_23", |dirs, sandbox| { sandbox.with_files(&[ Stub::FileWithContent("log.txt", "Old"), Stub::FileWithContent("err.txt", "Old Err"), ]); let expected_file = dirs.test().join("log.txt"); let expected_stderr_file = dirs.test().join("err.txt"); let actual = nu!( cwd: dirs.root(), r#" $env.FOO = " New"; $env.BAZ = " New Err"; def tttt [] { do -i {nu -n -c 'nu --testbin echo_env FOO; nu --testbin echo_env_stderr BAZ'} | save -a -r save_test_23/log.txt }; tttt e> ("save_test_23" | path join empty_file)"# ); assert_eq!(actual.err.trim_end(), " New Err"); let actual = file_contents(expected_file); assert_eq!(actual.trim_end(), "Old New"); let actual = file_contents(expected_stderr_file); assert_eq!(actual.trim_end(), "Old Err"); let actual = file_contents(dirs.test().join("empty_file")); assert_eq!(actual.trim_end(), ""); }) } #[test] fn save_missing_parent_dir() { Playground::setup("save_test_24", |dirs, sandbox| { sandbox.with_files(&[]); let actual = nu!( cwd: dirs.root(), r#"'hello' | save save_test_24/foobar/hello.txt"#, ); assert!(actual.err.contains("nu::shell::io::directory_not_found")); assert!(actual.err.contains("foobar' does not exist")); }) } #[test] fn save_missing_ancestor_dir() { Playground::setup("save_test_24", |dirs, sandbox| { sandbox.with_files(&[]); std::fs::create_dir(dirs.test().join("foo")) .expect("should have been able to create subdir for test"); let actual = nu!( cwd: dirs.root(), r#"'hello' | save save_test_24/foo/bar/baz/hello.txt"#, ); assert!(actual.err.contains("nu::shell::io::directory_not_found")); assert!(actual.err.contains("bar' does not exist")); }) } #[test] fn force_save_to_dir() { let actual = nu!(cwd: "crates/nu-command/tests/commands", r#" "aaa" | save -f .. "#); assert!(actual.err.contains("nu::shell::io::is_a_directory")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/du.rs
crates/nu-command/tests/commands/du.rs
use nu_test_support::fs::Stub::EmptyFile; use nu_test_support::{nu, playground::Playground}; use rstest::rstest; #[test] fn test_du_flag_min_size() { let actual = nu!(cwd: "tests/fixtures/formats", r#" du -m -1 "#); assert!( actual .err .contains("Negative value passed when positive one is required") ); let actual = nu!(cwd: "tests/fixtures/formats", r#" du -m 1 "#); assert!(actual.err.is_empty()); } #[test] fn test_du_flag_max_depth() { let actual = nu!(cwd: "tests/fixtures/formats", r#" du -d -2 "#); assert!( actual .err .contains("Negative value passed when positive one is required") ); let actual = nu!(cwd: "tests/fixtures/formats", r#" du -d 2 "#); assert!(actual.err.is_empty()); } #[rstest] #[case("a]c")] #[case("a[c")] #[case("a[bc]d")] #[case("a][c")] fn du_files_with_glob_metachars(#[case] src_name: &str) { Playground::setup("du_test_16", |dirs, sandbox| { sandbox.with_files(&[EmptyFile(src_name)]); let src = dirs.test().join(src_name); let actual = nu!( cwd: dirs.test(), format!( "du -d 1 '{}'", src.display(), ) ); assert!(actual.err.is_empty()); // also test for variables. let actual = nu!( cwd: dirs.test(), format!( "let f = '{}'; du -d 1 $f", src.display(), ) ); assert!(actual.err.is_empty()); }); } #[cfg(not(windows))] #[rstest] #[case("a]?c")] #[case("a*.?c")] // windows doesn't allow filename with `*`. fn du_files_with_glob_metachars_nw(#[case] src_name: &str) { du_files_with_glob_metachars(src_name); } #[test] fn du_with_multiple_path() { let actual = nu!(cwd: "tests/fixtures", "du cp formats | get path | path basename"); assert!(actual.out.contains("cp")); assert!(actual.out.contains("formats")); assert!(!actual.out.contains("lsp")); assert!(actual.status.success()); // report errors if one path not exists let actual = nu!(cwd: "tests/fixtures", "du cp asdf | get path | path basename"); assert!(actual.err.contains("nu::shell::io::not_found")); assert!(!actual.status.success()); // du with spreading empty list should returns nothing. let actual = nu!(cwd: "tests/fixtures", "du ...[] | length"); assert_eq!(actual.out, "0"); } #[test] fn test_du_output_columns() { let actual = nu!( cwd: "tests/fixtures/formats", "du -m 1 | columns | str join ','" ); assert_eq!(actual.out, "path,apparent,physical"); let actual = nu!( cwd: "tests/fixtures/formats", "du -m 1 -l | columns | str join ','" ); assert_eq!(actual.out, "path,apparent,physical,directories,files"); } #[test] fn du_wildcards() { Playground::setup("du_wildcards", |dirs, sandbox| { sandbox.with_files(&[EmptyFile(".a")]); // by default, wildcard don't match dot files. let actual = nu!( cwd: dirs.test(), "du * | length", ); assert_eq!(actual.out, "0"); // unless `-a` flag is provided. let actual = nu!( cwd: dirs.test(), "du -a * | length", ); 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/group_by.rs
crates/nu-command/tests/commands/group_by.rs
use nu_test_support::nu; #[test] fn groups() { let sample = 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] ]"#; let actual = nu!(format!( r#" {sample} | group-by rusty_at | get "10/11/2013" | length "# )); assert_eq!(actual.out, "2"); } #[test] fn errors_if_given_unknown_column_name() { 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}' | from json | group-by {{|| get nu.releases.missing_column }} "# )); assert!(actual.err.contains("cannot find column")); } #[test] fn errors_if_column_not_found() { let sample = 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]] "#; let actual = nu!(format!("{sample} | group-by ttype")); assert!(actual.err.contains("did you mean 'type'"),); } #[test] fn group_by_on_empty_list_returns_empty_record() { let actual = nu!("[[a b]; [1 2]] | where false | group-by a | to nuon --raw"); let expected = r#"{}"#; assert!(actual.err.is_empty()); assert_eq!(actual.out, expected); } #[test] fn group_by_to_table_on_empty_list_returns_empty_list() { let actual = nu!("[[a b]; [1 2]] | where false | group-by --to-table a | to nuon --raw"); let expected = r#"[]"#; assert!(actual.err.is_empty()); assert_eq!(actual.out, expected); } #[test] fn optional_cell_path_works() { let actual = nu!("[{foo: 123}, {foo: 234}, {bar: 345}] | group-by foo? | to nuon"); let expected = r#"{"123": [[foo]; [123]], "234": [[foo]; [234]]}"#; 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/unlet.rs
crates/nu-command/tests/commands/unlet.rs
use nu_test_support::nu; #[test] fn unlet_basic() { let actual = nu!("let x = 42; unlet $x; $x"); assert!(actual.err.contains("Variable not found")); } #[test] fn unlet_builtin_nu() { let actual = nu!("unlet $nu"); assert!(actual.err.contains("cannot be deleted")); } #[test] fn unlet_builtin_env() { let actual = nu!("unlet $env"); assert!(actual.err.contains("cannot be deleted")); } #[test] fn unlet_not_variable() { let actual = nu!("unlet 42"); assert!( actual .err .contains("Argument must be a variable reference like $x") ); } #[test] fn unlet_wrong_number_args() { let actual = nu!("unlet"); assert!(actual.err.contains("unlet takes at least one argument")); } #[test] fn unlet_multiple_args() { let actual = nu!("let x = 1; let y = 2; unlet $x $y; $x"); assert!(actual.err.contains("Variable not found")); } #[test] fn unlet_multiple_deletes_both() { let actual = nu!("let x = 1; let y = 2; unlet $x $y; $y"); assert!(actual.err.contains("Variable not found")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/ulimit.rs
crates/nu-command/tests/commands/ulimit.rs
use nu_test_support::nu; use nu_test_support::playground::Playground; #[test] fn limit_set_soft1() { Playground::setup("limit_set_soft1", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " let soft = (ulimit -s | first | get soft); ulimit -s -H $soft; let hard = (ulimit -s | first | get hard); $soft == $hard "); assert!(actual.out.contains("true")); }); } #[test] fn limit_set_soft2() { Playground::setup("limit_set_soft2", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " let soft = (ulimit -s | first | get soft); ulimit -s -H soft; let hard = (ulimit -s | first | get hard); $soft == $hard "); assert!(actual.out.contains("true")); }); } #[test] fn limit_set_hard1() { Playground::setup("limit_set_hard1", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " let hard = (ulimit -s | first | get hard); ulimit -s $hard; let soft = (ulimit -s | first | get soft); $soft == $hard "); assert!(actual.out.contains("true")); }); } #[test] fn limit_set_hard2() { Playground::setup("limit_set_hard2", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " let hard = (ulimit -s | first | get hard); ulimit -s hard; let soft = (ulimit -s | first | get soft); $soft == $hard "); assert!(actual.out.contains("true")); }); } #[test] fn limit_set_invalid1() { Playground::setup("limit_set_invalid1", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " let hard = (ulimit -s | first | get hard); match $hard { \"unlimited\" => { echo \"unlimited\" }, $x => { let new = $x + 1; ulimit -s $new } } "); assert!( actual.out.contains("unlimited") || actual.err.contains("EPERM: Operation not permitted") ); }); } #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))] #[test] fn limit_set_invalid2() { Playground::setup("limit_set_invalid2", |dirs, _sandbox| { let actual = nu!( cwd: dirs.test(), " let val = -100; ulimit -c $val " ); assert!(actual.err.contains("can't convert i64 to rlim_t")); }); } #[test] fn limit_set_invalid3() { Playground::setup("limit_set_invalid3", |dirs, _sandbox| { let actual = nu!( cwd: dirs.test(), " ulimit -c abcd " ); assert!( actual .err .contains("Only unlimited, soft and hard are supported for strings") ); }); } #[test] fn limit_set_invalid4() { Playground::setup("limit_set_invalid4", |dirs, _sandbox| { let actual = nu!( cwd: dirs.test(), " ulimit -c 100.0 " ); assert!(actual.err.contains("string, int or filesize required")); }); } #[test] fn limit_set_invalid5() { use nix::sys::resource::rlim_t; let max = (rlim_t::MAX / 1024) + 1; Playground::setup("limit_set_invalid5", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), format!(r#" let hard = (ulimit -c | first | get hard) match $hard {{ "unlimited" => {{ ulimit -c -S 0 ulimit -c {max} ulimit -c | first | get soft }}, _ => {{ echo "unlimited" }} }} "#)); assert!(actual.out.eq("unlimited")); }); } #[test] fn limit_set_filesize1() { Playground::setup("limit_set_filesize1", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " let hard = (ulimit -c | first | get hard); match $hard { \"unlimited\" => { ulimit -c 1Mib; ulimit -c | first | get soft }, $x if $x >= 1024 * 1024 => { ulimit -c 1Mib; ulimit -c | first | get soft } _ => { echo \"hard limit too small\" } } "); assert!(actual.out.eq("1024") || actual.out.eq("hard limit too small")); }); } #[test] fn limit_set_filesize2() { Playground::setup("limit_set_filesize2", |dirs, _sandbox| { let actual = nu!( cwd: dirs.test(), " ulimit -n 10Kib " ); assert!( actual .err .contains("filesize is not compatible with resource RLIMIT_NOFILE") ); }); }
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_duration.rs
crates/nu-command/tests/commands/into_duration.rs
use nu_test_support::nu; // Tests happy paths #[test] fn into_duration_float() { let actual = nu!(r#"1.07min | into duration"#); assert_eq!("1min 4sec 200ms", actual.out); } #[test] fn into_duration_from_record_cell_path() { let actual = nu!(r#"{d: '1hr'} | into duration d"#); let expected = nu!(r#"{d: 1hr}"#); assert_eq!(expected.out, actual.out); } #[test] fn into_duration_from_record() { let actual = nu!( r#"{week: 10, day: 1, hour: 2, minute: 3, second: 4, millisecond: 5, microsecond: 6, nanosecond: 7, sign: '+'} | into duration | into record"# ); let expected = nu!( r#"{week: 10, day: 1, hour: 2, minute: 3, second: 4, millisecond: 5, microsecond: 6, nanosecond: 7, sign: '+'}"# ); assert_eq!(expected.out, actual.out); } #[test] fn into_duration_from_record_negative() { let actual = nu!( r#"{week: 10, day: 1, hour: 2, minute: 3, second: 4, millisecond: 5, microsecond: 6, nanosecond: 7, sign: '-'} | into duration | into record"# ); let expected = nu!( r#"{week: 10, day: 1, hour: 2, minute: 3, second: 4, millisecond: 5, microsecond: 6, nanosecond: 7, sign: '-'}"# ); assert_eq!(expected.out, actual.out); } #[test] fn into_duration_from_record_defaults() { let actual = nu!(r#"{} | into duration | into int"#); assert_eq!("0".to_string(), actual.out); } #[test] fn into_duration_from_record_round_trip() { let actual = nu!( r#"('10wk 1day 2hr 3min 4sec 5ms 6µs 7ns' | into duration | into record | into duration | into string) == '10wk 1day 2hr 3min 4sec 5ms 6µs 7ns'"# ); assert!(actual.out.contains("true")); } #[test] fn into_duration_table_column() { let actual = nu!(r#"[[value]; ['1sec'] ['2min'] ['3hr'] ['4day'] ['5wk']] | into duration value"#); let expected = nu!(r#"[[value]; [1sec] [2min] [3hr] [4day] [5wk]]"#); assert_eq!(actual.out, expected.out); } // Tests error paths #[test] fn into_duration_from_record_fails_with_wrong_type() { let actual = nu!(r#"{week: '10'} | into duration"#); assert!( actual .err .contains("nu::shell::only_supports_this_input_type") ); } #[test] fn into_duration_from_record_fails_with_invalid_date_time_values() { let actual = nu!(r#"{week: -10} | into duration"#); assert!(actual.err.contains("nu::shell::incorrect_value")); } #[test] fn into_duration_from_record_fails_with_invalid_sign() { let actual = nu!(r#"{week: 10, sign: 'x'} | into duration"#); assert!(actual.err.contains("nu::shell::incorrect_value")); } // Tests invalid usage #[test] fn into_duration_invalid_unit() { let actual = nu!(r#"1 | into duration --unit xx"#); assert!(actual.err.contains("nu::shell::invalid_unit")); } #[test] fn into_duration_filesize_unit() { let actual = nu!(r#"1 | into duration --unit MB"#); assert!(actual.err.contains("nu::shell::invalid_unit")); } #[test] fn into_duration_from_record_fails_with_unknown_key() { let actual = nu!(r#"{week: 10, unknown: 1} | into duration"#); assert!(actual.err.contains("nu::shell::unsupported_input")); } #[test] fn into_duration_from_record_incompatible_with_unit_flag() { let actual = nu!( r#"{week: 10, day: 1, hour: 2, minute: 3, second: 4, sign: '-'} | into duration --unit sec"# ); assert!(actual.err.contains("nu::shell::incompatible_parameters")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/source_env.rs
crates/nu-command/tests/commands/source_env.rs
use nu_test_support::fs::Stub::{EmptyFile, FileWithContent, FileWithContentToBeTrimmed}; use nu_test_support::nu; use nu_test_support::playground::Playground; #[should_panic] #[test] fn sources_also_files_under_custom_lib_dirs_path() { Playground::setup("source_test_1", |dirs, nu| { let file = dirs.test().join("config.toml"); let library_path = dirs.test().join("lib"); nu.with_config(file); nu.with_files(&[FileWithContent( "config.toml", &format!( r#" lib_dirs = ["{}"] skip_welcome_message = true "#, library_path.as_os_str().to_str().unwrap(), ), )]); nu.within("lib").with_files(&[FileWithContent( "my_library.nu", r#" source-env my_library/main.nu "#, )]); nu.within("lib/my_library").with_files(&[FileWithContent( "main.nu", r#" $env.hello = "hello nu" "#, )]); let actual = nu!(" source-env my_library.nu ; hello "); assert_eq!(actual.out, "hello nu"); }) } fn try_source_foo_with_double_quotes_in(testdir: &str, playdir: &str) { Playground::setup(playdir, |dirs, sandbox| { let testdir = String::from(testdir); let mut foo_file = testdir.clone(); foo_file.push_str("/foo.nu"); sandbox.mkdir(&testdir); sandbox.with_files(&[FileWithContent(&foo_file, "echo foo")]); let cmd = String::from("source-env ") + r#"""# + foo_file.as_str() + r#"""#; let actual = nu!(cwd: dirs.test(), &cmd); assert_eq!(actual.out, "foo"); }); } fn try_source_foo_with_single_quotes_in(testdir: &str, playdir: &str) { Playground::setup(playdir, |dirs, sandbox| { let testdir = String::from(testdir); let mut foo_file = testdir.clone(); foo_file.push_str("/foo.nu"); sandbox.mkdir(&testdir); sandbox.with_files(&[FileWithContent(&foo_file, "echo foo")]); let cmd = String::from("source-env ") + r#"'"# + foo_file.as_str() + r#"'"#; let actual = nu!(cwd: dirs.test(), &cmd); assert_eq!(actual.out, "foo"); }); } fn try_source_foo_without_quotes_in(testdir: &str, playdir: &str) { Playground::setup(playdir, |dirs, sandbox| { let testdir = String::from(testdir); let mut foo_file = testdir.clone(); foo_file.push_str("/foo.nu"); sandbox.mkdir(&testdir); sandbox.with_files(&[FileWithContent(&foo_file, "echo foo")]); let cmd = String::from("source-env ") + foo_file.as_str(); let actual = nu!(cwd: dirs.test(), &cmd); assert_eq!(actual.out, "foo"); }); } #[test] fn sources_unicode_file_in_normal_dir() { try_source_foo_with_single_quotes_in("foo", "source_test_1"); try_source_foo_with_double_quotes_in("foo", "source_test_2"); try_source_foo_without_quotes_in("foo", "source_test_3"); } #[test] fn sources_unicode_file_in_unicode_dir_without_spaces_1() { try_source_foo_with_single_quotes_in("🚒", "source_test_4"); try_source_foo_with_double_quotes_in("🚒", "source_test_5"); try_source_foo_without_quotes_in("🚒", "source_test_6"); } #[cfg(not(windows))] // ':' is not allowed in Windows paths #[test] fn sources_unicode_file_in_unicode_dir_without_spaces_2() { try_source_foo_with_single_quotes_in(":fire_engine:", "source_test_7"); try_source_foo_with_double_quotes_in(":fire_engine:", "source_test_8"); try_source_foo_without_quotes_in(":fire_engine:", "source_test_9"); } #[test] fn sources_unicode_file_in_unicode_dir_with_spaces_1() { // this one fails try_source_foo_with_single_quotes_in("e-$ èрт🚒♞中片-j", "source_test_8"); // this one passes try_source_foo_with_double_quotes_in("e-$ èрт🚒♞中片-j", "source_test_9"); } #[cfg(not(windows))] // ':' is not allowed in Windows paths #[test] fn sources_unicode_file_in_unicode_dir_with_spaces_2() { try_source_foo_with_single_quotes_in("e-$ èрт:fire_engine:♞中片-j", "source_test_10"); try_source_foo_with_double_quotes_in("e-$ èрт:fire_engine:♞中片-j", "source_test_11"); } #[ignore] #[test] fn sources_unicode_file_in_non_utf8_dir() { // How do I create non-UTF-8 path??? } #[ignore] #[test] fn can_source_dynamic_path() { Playground::setup("can_source_dynamic_path", |dirs, sandbox| { let foo_file = "foo.nu"; sandbox.with_files(&[FileWithContent(foo_file, "echo foo")]); let cmd = format!("let file = `{foo_file}`; source-env $file"); let actual = nu!(cwd: dirs.test(), &cmd); assert_eq!(actual.out, "foo"); }); } #[test] fn source_env_eval_export_env() { Playground::setup("source_env_eval_export_env", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "spam.nu", r#" export-env { $env.FOO = 'foo' } "#, )]); let inp = &[r#"source-env spam.nu"#, r#"$env.FOO"#]; let actual = nu!(cwd: dirs.test(), &inp.join("; ")); assert_eq!(actual.out, "foo"); }) } #[test] fn source_env_eval_export_env_hide() { Playground::setup("source_env_eval_export_env", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "spam.nu", r#" export-env { hide-env FOO } "#, )]); let inp = &[ r#"$env.FOO = 'foo'"#, r#"source-env spam.nu"#, r#"$env.FOO"#, ]; let actual = nu!(cwd: dirs.test(), &inp.join("; ")); assert!(actual.err.contains("not_found")); }) } #[test] fn source_env_do_cd() { Playground::setup("source_env_do_cd", |dirs, sandbox| { sandbox .mkdir("test1/test2") .with_files(&[FileWithContentToBeTrimmed( "test1/test2/spam.nu", r#" cd test1/test2 "#, )]); let inp = &[ r#"source-env test1/test2/spam.nu"#, r#"$env.PWD | path basename"#, ]; let actual = nu!(cwd: dirs.test(), &inp.join("; ")); assert_eq!(actual.out, "test2"); }) } #[test] fn source_env_do_cd_file_relative() { Playground::setup("source_env_do_cd_file_relative", |dirs, sandbox| { sandbox .mkdir("test1/test2") .with_files(&[FileWithContentToBeTrimmed( "test1/test2/spam.nu", r#" cd ($env.FILE_PWD | path join '..') "#, )]); let inp = &[ r#"source-env test1/test2/spam.nu"#, r#"$env.PWD | path basename"#, ]; let actual = nu!(cwd: dirs.test(), &inp.join("; ")); assert_eq!(actual.out, "test1"); }) } #[test] fn source_env_dont_cd_overlay() { Playground::setup("source_env_dont_cd_overlay", |dirs, sandbox| { sandbox .mkdir("test1/test2") .with_files(&[FileWithContentToBeTrimmed( "test1/test2/spam.nu", r#" overlay new spam cd test1/test2 overlay hide spam "#, )]); let inp = &[ r#"source-env test1/test2/spam.nu"#, r#"$env.PWD | path basename"#, ]; let actual = nu!(cwd: dirs.test(), &inp.join("; ")); assert_eq!(actual.out, "source_env_dont_cd_overlay"); }) } #[test] fn source_env_is_scoped() { Playground::setup("source_env_is_scoped", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "spam.nu", r#" def no-name-similar-to-this [] { 'no-name-similar-to-this' } alias nor-similar-to-this = echo 'nor-similar-to-this' "#, )]); let inp = &[r#"source-env spam.nu"#, r#"no-name-similar-to-this"#]; let actual = nu!(cwd: dirs.test(), &inp.join("; ")); assert!( actual .err .contains("Command `no-name-similar-to-this` not found") ); let inp = &[r#"source-env spam.nu"#, r#"nor-similar-to-this"#]; let actual = nu!(cwd: dirs.test(), &inp.join("; ")); assert!( actual .err .contains("Command `nor-similar-to-this` not found") ); }) } #[test] fn source_env_const_file() { Playground::setup("source_env_const_file", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "spam.nu", r#" $env.FOO = 'foo' "#, )]); let inp = &[ r#"const file = 'spam.nu'"#, r#"source-env $file"#, r#"$env.FOO"#, ]; let actual = nu!(cwd: dirs.test(), &inp.join("; ")); assert_eq!(actual.out, "foo"); }) } #[test] fn source_respects_early_return() { let actual = nu!(cwd: "tests/fixtures/formats", " source early_return.nu "); assert!(actual.err.is_empty()); } #[test] fn source_after_use_should_not_error() { Playground::setup("source_after_use", |dirs, sandbox| { sandbox.with_files(&[EmptyFile("spam.nu")]); let inp = &[r#"use spam.nu"#, r#"source spam.nu"#]; let actual = nu!(cwd: dirs.test(), &inp.join("; ")); assert!(actual.err.is_empty()); }) } #[test] fn use_after_source_should_not_error() { Playground::setup("use_after_source", |dirs, sandbox| { sandbox.with_files(&[EmptyFile("spam.nu")]); let inp = &[r#"source spam.nu"#, r#"use spam.nu"#]; let actual = nu!(cwd: dirs.test(), &inp.join("; ")); 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/for_.rs
crates/nu-command/tests/commands/for_.rs
use nu_test_support::nu; #[test] fn for_doesnt_auto_print_in_each_iteration() { let actual = nu!(" for i in 1..2 { $i }"); // 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 for_break_on_external_failed() { let actual = nu!(" for i in 1..2 { 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_for_should_break_running() { let actual = nu!(" for i in 1..2 { nu --testbin fail } print 3"); assert!(!actual.out.contains('3')); let actual = nu!(" let x = [1 2] for i in $x { nu --testbin fail } print 3"); assert!(!actual.out.contains('3')); } #[test] fn for_loops_dont_collect_source() { let actual = nu!(" for i in (seq 1 10 | each { print -n $in; $in}) { print -n $i if $i >= 5 { break } } "); assert_eq!(actual.out, "1122334455"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/sort_by.rs
crates/nu-command/tests/commands/sort_by.rs
use nu_test_support::nu; #[test] fn by_column() { let actual = nu!(cwd: "tests/fixtures/formats", r#" open cargo_sample.toml --raw | lines | skip 1 | first 4 | split column "=" | sort-by column0 | skip 1 | first | get column0 | str trim "#); assert_eq!(actual.out, "description"); } #[test] fn by_invalid_column() { let actual = nu!(cwd: "tests/fixtures/formats", r#" open cargo_sample.toml --raw | lines | skip 1 | first 4 | split column "=" | sort-by ColumnThatDoesNotExist | skip 1 | first | get column0 | str trim "#); assert!(actual.err.contains("Cannot find column")); assert!(actual.err.contains("value originates here")); } #[test] fn sort_by_empty() { let actual = nu!("[] | sort-by foo | to nuon"); assert_eq!(actual.out, "[]"); } #[test] fn ls_sort_by_name_sensitive() { let actual = nu!(cwd: "tests/fixtures/formats", " open sample-ls-output.json | sort-by name | select name | to json --raw "); let json_output = r#"[{"name":"B.txt"},{"name":"C"},{"name":"a.txt"}]"#; assert_eq!(actual.out, json_output); } #[test] fn ls_sort_by_name_insensitive() { let actual = nu!(cwd: "tests/fixtures/formats", " open sample-ls-output.json | sort-by -i name | select name | to json --raw "); let json_output = r#"[{"name":"a.txt"},{"name":"B.txt"},{"name":"C"}]"#; assert_eq!(actual.out, json_output); } #[test] fn ls_sort_by_type_name_sensitive() { let actual = nu!(cwd: "tests/fixtures/formats", " open sample-ls-output.json | sort-by type name | select name type | to json --raw "); let json_output = r#"[{"name":"C","type":"Dir"},{"name":"B.txt","type":"File"},{"name":"a.txt","type":"File"}]"#; assert_eq!(actual.out, json_output); } #[test] fn ls_sort_by_type_name_insensitive() { let actual = nu!(cwd: "tests/fixtures/formats", " open sample-ls-output.json | sort-by -i type name | select name type | to json --raw "); let json_output = r#"[{"name":"C","type":"Dir"},{"name":"a.txt","type":"File"},{"name":"B.txt","type":"File"}]"#; assert_eq!(actual.out, json_output); } #[test] fn no_column_specified_fails() { let actual = nu!("[2 0 1] | sort-by"); assert!(actual.err.contains("missing parameter")); } #[test] fn fail_on_non_iterator() { let actual = nu!("1 | sort-by"); 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/export.rs
crates/nu-command/tests/commands/export.rs
use nu_test_support::nu; #[test] fn export_command_help() { let actual = nu!("export -h"); assert!( actual .out .contains("Export definitions or environment variables from a module") ); } #[test] fn export_command_unexpected() { let actual = nu!("export foo"); assert!(actual.err.contains("unexpected export")); } #[test] fn export_alias_should_not_panic() { let actual = nu!("export alias"); assert!(actual.err.contains("Missing")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/length.rs
crates/nu-command/tests/commands/length.rs
use nu_test_support::fs::Stub::FileWithContent; use nu_test_support::nu; use nu_test_support::playground::Playground; #[test] fn length_columns_in_cal_table() { let actual = nu!("cal --as-table | columns | length"); assert_eq!(actual.out, "7"); } #[test] fn length_columns_no_rows() { let actual = nu!("echo [] | length"); assert_eq!(actual.out, "0"); } #[test] fn length_fails_on_echo_record() { let actual = nu!("echo {a:1 b:2} | length"); assert!(actual.err.contains("only_supports_this_input_type")); } #[test] fn length_byte_stream() { Playground::setup("length_bytes", |dirs, sandbox| { sandbox.mkdir("length_bytes"); sandbox.with_files(&[FileWithContent("data.txt", "😀")]); let actual = nu!(cwd: dirs.test(), "open data.txt | length"); assert_eq!(actual.out, "4"); }); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/roll.rs
crates/nu-command/tests/commands/roll.rs
use nu_test_support::nu; mod rows { use super::*; const TABLE: &str = r#"[ [service, status]; [ruby, DOWN] [db, DOWN] [nud, DOWN] [expected, HERE] ]"#; #[test] fn can_roll_down() { let actual = nu!(format!( r#" {TABLE} | roll down | first | get status "#, )); assert_eq!(actual.out, "HERE"); } #[test] fn can_roll_up() { let actual = nu!(format!( r#" {TABLE} | roll up --by 3 | first | get status "# )); assert_eq!(actual.out, "HERE"); } } mod columns { use super::*; const TABLE: &str = r#"[ [commit_author, origin, stars]; [ "Andres", EC, amarillito] [ "Darren", US, black] [ "JT", US, black] [ "Yehuda", US, black] [ "Jason", CA, gold] ]"#; #[test] fn can_roll_left() { let actual = nu!(format!( r#" {TABLE} | roll left | columns | str join "-" "# )); assert_eq!(actual.out, "origin-stars-commit_author"); } #[test] fn can_roll_right() { let actual = nu!(format!( r#" {TABLE} | roll right --by 2 | columns | str join "-" "# )); assert_eq!(actual.out, "origin-stars-commit_author"); } struct ThirtyTwo<'a>(usize, &'a str); #[test] fn can_roll_the_cells_only_keeping_the_header_names() { let four_bitstring = bitstring_to_nu_row_pipeline("00000100"); let expected_value = ThirtyTwo(32, "bit1-bit2-bit3-bit4-bit5-bit6-bit7-bit8"); let actual = nu!(format!( "{four_bitstring} | roll right --by 3 --cells-only | columns | str join '-' " )); assert_eq!(actual.out, expected_value.1); } #[test] fn four_in_bitstring_left_shifted_with_three_bits_should_be_32_in_decimal() { let four_bitstring = "00000100"; let expected_value = ThirtyTwo(32, "00100000"); assert_eq!( shift_three_bits_to_the_left_to_bitstring(four_bitstring), expected_value.0.to_string() ); } fn shift_three_bits_to_the_left_to_bitstring(bits: &str) -> String { // this pipeline takes the bitstring and outputs a nu row literal // for example the number 4 in bitstring: // // input: 00000100 // // output: // [ // [column1, column2, column3, column4, column5, column6, column7, column8]; // [ 0, 0, 0, 0, 0, 1, 0, 0] // ] // let bitstring_as_nu_row_pipeline = bitstring_to_nu_row_pipeline(bits); // this pipeline takes the nu bitstring row literal, computes it's // decimal value. let nu_row_literal_bitstring_to_decimal_value_pipeline = r#"transpose bit --ignore-titles | get bit | reverse | enumerate | each { |it| $it.item * (2 ** $it.index) } | math sum "#; println!( "{bitstring_as_nu_row_pipeline} | roll left --by 3 | {nu_row_literal_bitstring_to_decimal_value_pipeline}" ); nu!( format!("{bitstring_as_nu_row_pipeline} | roll left --by 3 | {nu_row_literal_bitstring_to_decimal_value_pipeline}") ).out } fn bitstring_to_nu_row_pipeline(bits: &str) -> String { format!( "echo '{}' | {}", bits, r#" split chars | each { |it| $it | into int } | rotate --ccw | rename bit1 bit2 bit3 bit4 bit5 bit6 bit7 bit8 "# ) } }
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.rs
crates/nu-command/tests/commands/seq.rs
use nu_test_support::nu; #[test] fn float_in_seq_leads_to_lists_of_floats() { let actual = nu!("seq 1.0 0.5 6 | describe"); assert_eq!(actual.out, "list<float> (stream)"); } #[test] fn ints_in_seq_leads_to_lists_of_ints() { let actual = nu!("seq 1 2 6 | describe"); assert_eq!(actual.out, "list<int> (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/job.rs
crates/nu-command/tests/commands/job.rs
use nu_test_support::nu; #[test] fn job_send_root_job_works() { let actual = nu!(r#" job spawn { 'beep' | job send 0 } job recv --timeout 10sec"#); assert_eq!(actual.out, "beep"); } #[test] fn job_send_background_job_works() { let actual = nu!(r#" let job = job spawn { job recv | job send 0 } 'boop' | job send $job job recv --timeout 10sec"#); assert_eq!(actual.out, "boop"); } #[test] fn job_send_to_self_works() { let actual = nu!(r#" "meep" | job send 0 job recv"#); assert_eq!(actual.out, "meep"); } #[test] fn job_send_to_self_from_background_works() { let actual = nu!(r#" job spawn { 'beep' | job send (job id) job recv | job send 0 } job recv --timeout 10sec"#); assert_eq!(actual.out, "beep"); } #[test] fn job_id_of_root_job_is_zero() { let actual = nu!(r#"job id"#); assert_eq!(actual.out, "0"); } #[test] fn job_id_of_background_jobs_works() { let actual = nu!(r#" let job1 = job spawn { job id | job send 0 } let id1 = job recv --timeout 5sec let job2 = job spawn { job id | job send 0 } let id2 = job recv --timeout 5sec let job3 = job spawn { job id | job send 0 } let id3 = job recv --timeout 5sec [($job1 == $id1) ($job2 == $id2) ($job3 == $id3)] | to nuon "#); assert_eq!(actual.out, "[true, true, true]"); } #[test] fn untagged_job_recv_accepts_tagged_messages() { let actual = nu!(r#" job spawn { "boop" | job send 0 --tag 123 } job recv --timeout 10sec "#); assert_eq!(actual.out, "boop"); } #[test] fn tagged_job_recv_filters_untagged_messages() { let actual = nu!(r#" job spawn { "boop" | job send 0 } job recv --tag 123 --timeout 1sec "#); assert_eq!(actual.out, ""); assert!(actual.err.contains("timeout")); } #[test] fn tagged_job_recv_filters_badly_tagged_messages() { let actual = nu!(r#" job spawn { "boop" | job send 0 --tag 321 } job recv --tag 123 --timeout 1sec "#); assert_eq!(actual.out, ""); assert!(actual.err.contains("timeout")); } #[test] fn tagged_job_recv_accepts_properly_tagged_messages() { let actual = nu!(r#" job spawn { "boop" | job send 0 --tag 123 } job recv --tag 123 --timeout 5sec "#); assert_eq!(actual.out, "boop"); } #[test] fn filtered_messages_are_not_erased() { let actual = nu!(r#" "msg1" | job send 0 --tag 123 "msg2" | job send 0 --tag 456 "msg3" | job send 0 --tag 789 let first = job recv --tag 789 --timeout 5sec let second = job recv --timeout 1sec let third = job recv --timeout 1sec [($first) ($second) ($third)] | to nuon "#); assert_eq!(actual.out, r#"["msg3", "msg1", "msg2"]"#); } #[test] fn job_recv_timeout_works() { let actual = nu!(r#" job spawn { sleep 2sec "boop" | job send 0 } job recv --timeout 1sec "#); assert_eq!(actual.out, ""); assert!(actual.err.contains("timeout")); } #[test] fn job_recv_timeout_zero_works() { let actual = nu!(r#" "hi there" | job send 0 job recv --timeout 0sec "#); assert_eq!(actual.out, "hi there"); } #[test] fn job_flush_clears_messages() { let actual = nu!(r#" "SALE!!!" | job send 0 "[HYPERLINK BLOCKED]" | job send 0 job flush job recv --timeout 1sec "#); assert_eq!(actual.out, ""); assert!(actual.err.contains("timeout")); } #[test] fn job_flush_clears_filtered_messages() { let actual = nu!(r#" "msg1" | job send 0 --tag 123 "msg2" | job send 0 --tag 456 "msg3" | job send 0 --tag 789 job recv --tag 789 --timeout 1sec job flush job recv --timeout 1sec "#); assert_eq!(actual.out, ""); assert!(actual.err.contains("timeout")); } #[test] fn job_flush_with_tag() { let actual = nu!(r#" "spam" | job send 0 --tag 404 "not" | str reverse | job send 0 --tag 505 "still alive" | job send 0 --tag 606 "spam" | job send 0 --tag 404 job recv --tag 505 --timeout 1sec job flush --tag 404 job recv --timeout 1sec "#); assert_eq!(actual.out, "still alive"); assert_eq!(actual.err, ""); } #[test] fn first_job_id_is_one() { let actual = nu!(r#"job spawn {} | to nuon"#); assert_eq!(actual.out, "1"); } #[test] fn job_list_adds_jobs_correctly() { let actual = nu!(format!( r#" let list0 = job list | get id; let job1 = job spawn {{ job recv }}; let list1 = job list | get id; let job2 = job spawn {{ job recv }}; let list2 = job list | get id; let job3 = job spawn {{ job recv }}; let list3 = job list | get id; [({}), ({}), ({}), ({})] | to nuon "#, "$list0 == []", "$list1 == [$job1]", "($list2 | sort) == ([$job1, $job2] | sort)", "($list3 | sort) == ([$job1, $job2, $job3] | sort)" )); assert_eq!(actual.out, "[true, true, true, true]"); } #[test] fn jobs_get_removed_from_list_after_termination() { let actual = nu!(format!( r#" let job = job spawn {{ job recv }}; let list0 = job list | get id; "die!" | job send $job sleep 0.2sec let list1 = job list | get id; [({}) ({})] | to nuon "#, "$list0 == [$job]", "$list1 == []", )); assert_eq!(actual.out, "[true, true]"); } // TODO: find way to communicate between process in windows // so these tests can fail less often #[test] fn job_list_shows_pids() { let actual = nu!(format!( r#" let job1 = job spawn {{ nu -c "sleep 1sec" | nu -c "sleep 2sec" }}; sleep 500ms; let list0 = job list | where id == $job1 | first | get pids; sleep 1sec; let list1 = job list | where id == $job1 | first | get pids; [({}), ({}), ({})] | to nuon "#, "($list0 | length) == 2", "($list1 | length) == 1", "$list1.0 in $list0", )); assert_eq!(actual.out, "[true, true, true]"); } #[test] fn killing_job_removes_it_from_table() { let actual = nu!(format!( r#" let job1 = job spawn {{ job recv }} let job2 = job spawn {{ job recv }} let job3 = job spawn {{ job recv }} let list_before = job list | get id job kill $job1 let list_after_kill_1 = job list | get id job kill $job2 let list_after_kill_2 = job list | get id job kill $job3 let list_after_kill_3 = job list | get id [({}) ({}) ({}) ({})] | to nuon "#, "($list_before | sort) == ([$job1 $job2 $job3] | sort)", "($list_after_kill_1 | sort) == ([$job2 $job3] | sort)", "($list_after_kill_2 | sort) == ([$job3] | sort)", "$list_after_kill_3 == []", )); assert_eq!(actual.out, "[true, true, true, true]"); } // this test is unreliable on the macOS CI, but it worked fine for a couple months. // still works on other operating systems. #[test] #[cfg(not(target_os = "macos"))] fn killing_job_kills_pids() { let actual = nu!(format!( r#" let job1 = job spawn {{ nu -c "sleep 1sec" | nu -c "sleep 1sec" }} sleep 25ms let pids = job list | where id == $job1 | get pids let child_pids_before = ps | where ppid == $nu.pid job kill $job1 sleep 25ms let child_pids_after = ps | where ppid == $nu.pid [({}) ({})] | to nuon "#, "($child_pids_before | length) == 2", "$child_pids_after == []", )); assert_eq!(actual.out, "[true, true]"); } #[test] fn exiting_nushell_kills_jobs() { let actual = nu!(r#" let result = nu -c "let job = job spawn { nu -c 'sleep 1sec' }; sleep 100ms; let child_pid = job list | where id == $job | get pids | first; [$nu.pid $child_pid] | to nuon" let info = $result | from nuon let child_pid = $info.0 let grandchild_pid = $info.1 ps | where pid == $grandchild_pid | filter { $in.ppid in [$child_pid, 1] } | length | to nuon "#); assert_eq!(actual.out, "0"); } #[cfg(unix)] #[test] fn jobs_get_group_id_right() { let actual = nu!(r#" let job1 = job spawn { nu -c "sleep 0.5sec" | nu -c "sleep 0.5sec"; } sleep 25ms let pids = job list | where id == $job1 | first | get pids let pid1 = $pids.0 let pid2 = $pids.1 let groups = ^ps -ax -o pid,pgid | from ssv -m 1 | update PID {|it| $it.PID | into int} | update PGID {|it| $it.PGID | into int} let my_group = $groups | where PID == $nu.pid | first | get PGID let group1 = $groups | where PID == $pid1 | first | get PGID let group2 = $groups | where PID == $pid2 | first | get PGID [($my_group != $group1) ($my_group != $group2) ($group1 == $group2)] | to nuon "#,); assert_eq!(actual.out, "[true, true, true]"); } #[test] fn job_extern_output_is_silent() { let actual = nu!(r#" job spawn { nu -c "'hi'" }; sleep 1sec"#); assert_eq!(actual.out, ""); assert_eq!(actual.err, ""); } #[test] fn job_print_is_not_silent() { let actual = nu!(r#" job spawn { print "hi" }; sleep 1sec"#); assert_eq!(actual.out, "hi"); assert_eq!(actual.err, ""); } #[test] fn job_extern_into_value_is_not_silent() { let actual = nu!(r#" job spawn { print (nu -c "'hi'") }; sleep 1sec"#); assert_eq!(actual.out, "hi"); assert_eq!(actual.err, ""); } #[test] fn job_extern_into_pipe_is_not_silent() { let actual = nu!(r#" job spawn { print (nu -c "10" | nu --stdin -c "($in | into int) + 1") } sleep 1sec"#); assert_eq!(actual.out, "11"); assert_eq!(actual.err, ""); } #[test] fn job_list_returns_no_tag_when_job_is_untagged() { let actual = nu!(r#" job spawn { sleep 10sec } job spawn { sleep 10sec } job spawn { sleep 10sec } ('tag' in (job list | columns)) | to nuon"#); assert_eq!(actual.out, "false"); assert_eq!(actual.err, ""); } #[test] fn job_list_returns_tag_when_job_is_spawned_with_tag() { let actual = nu!(r#" job spawn { sleep 10sec } --tag abc job list | where id == 1 | get tag.0 "#); assert_eq!(actual.out, "abc"); assert_eq!(actual.err, ""); } #[test] fn job_tag_modifies_untagged_job_tag() { let actual = nu!(r#" job spawn { sleep 10sec } job tag 1 beep job list | where id == 1 | get tag.0"#); assert_eq!(actual.out, "beep"); assert_eq!(actual.err, ""); } #[test] fn job_tag_modifies_tagged_job_tag() { let actual = nu!(r#" job spawn { sleep 10sec } --tag abc job tag 1 beep job list | where id == 1 | get tag.0"#); assert_eq!(actual.out, "beep"); 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/zip.rs
crates/nu-command/tests/commands/zip.rs
use nu_test_support::fs::Stub::FileWithContent; use nu_test_support::nu; use nu_test_support::playground::Playground; const ZIP_POWERED_TEST_ASSERTION_SCRIPT: &str = r#" export def expect [ left, --to-eq, right ] { $left | zip $right | all {|row| $row.name.0 == $row.name.1 and $row.commits.0 == $row.commits.1 } } "#; #[test] fn zips_two_tables() { Playground::setup("zip_test_1", |dirs, nu| { nu.with_files(&[FileWithContent( "zip_test.nu", &format!("{ZIP_POWERED_TEST_ASSERTION_SCRIPT}\n"), )]); let actual = nu!(format!( r#" use {} expect ; let contributors = ([ [name, commits]; [andres, 10] [ jt, 20] ]); let actual = ($contributors | upsert commits {{ |i| ($i.commits + 10) }}); expect $actual --to-eq [[name, commits]; [andres, 20] [jt, 30]] "#, dirs.test().join("zip_test.nu").display() )); assert_eq!(actual.out, "true"); }) } #[test] fn zips_two_lists() { let actual = nu!(r#" echo [0 2 4 6 8] | zip [1 3 5 7 9] | flatten | into string | str join '-' "#); assert_eq!(actual.out, "0-1-2-3-4-5-6-7-8-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/generate.rs
crates/nu-command/tests/commands/generate.rs
use nu_test_support::nu; #[test] fn generate_no_next_break() { let actual = nu!( "generate {|x| if $x == 3 { {out: $x}} else { {out: $x, next: ($x + 1)} }} 1 | to nuon" ); assert_eq!(actual.out, "[1, 2, 3]"); } #[test] fn generate_null_break() { let actual = nu!("generate {|x| if $x <= 3 { {out: $x, next: ($x + 1)} }} 1 | to nuon"); assert_eq!(actual.out, "[1, 2, 3]"); } #[test] fn generate_allows_empty_output() { let actual = nu!(r#" generate {|x| if $x == 1 { {next: ($x + 1)} } else if $x < 3 { {out: $x, next: ($x + 1)} } } 0 | to nuon "#); assert_eq!(actual.out, "[0, 2]"); } #[test] fn generate_allows_no_output() { let actual = nu!(r#" generate {|x| if $x < 3 { {next: ($x + 1)} } } 0 | to nuon "#); assert_eq!(actual.out, "[]"); } #[test] fn generate_allows_null_state() { let actual = nu!(r#" generate {|x| if $x == null { {out: "done"} } else if $x < 1 { {out: "going", next: ($x + 1)} } else { {out: "stopping", next: null} } } 0 | to nuon "#); assert_eq!(actual.out, "[going, stopping, done]"); } #[test] fn generate_allows_null_output() { let actual = nu!(r#" generate {|x| if $x == 3 { {out: "done"} } else { {out: null, next: ($x + 1)} } } 0 | to nuon "#); assert_eq!(actual.out, "[null, null, null, done]"); } #[test] fn generate_disallows_extra_keys() { let actual = nu!("generate {|x| {foo: bar, out: $x}} 0 "); assert!(actual.err.contains("Invalid block return")); } #[test] fn generate_disallows_list() { let actual = nu!("generate {|x| [$x, ($x + 1)]} 0 "); assert!(actual.err.contains("Invalid block return")); } #[test] fn generate_disallows_primitive() { let actual = nu!("generate {|x| 1} 0"); assert!(actual.err.contains("Invalid block return")); } #[test] fn generate_allow_default_parameter() { let actual = nu!(r#" generate {|x = 0| if $x == 3 { {out: "done"} } else { {out: null, next: ($x + 1)} } } | to nuon "#); assert_eq!(actual.out, "[null, null, null, done]"); // if initial is given, use initial value let actual = nu!(r#" generate {|x = 0| if $x == 3 { {out: "done"} } else { {out: null, next: ($x + 1)} } } 1 | to nuon "#); assert_eq!(actual.out, "[null, null, done]"); } #[test] fn generate_raise_error_on_no_default_parameter_closure_and_init_val() { let actual = nu!(r#" generate {|x| if $x == 3 { {out: "done"} } else { {out: null, next: ($x + 1)} } } | to nuon "#); assert!(actual.err.contains("The initial value is missing")); } #[test] fn generate_allows_pipeline_input() { let actual = nu!(r#"[1 2 3] | generate {|e, x=null| {out: $e, next: null}} | to nuon"#); assert_eq!(actual.out, "[1, 2, 3]"); } #[test] fn generate_with_input_is_streaming() { let actual = nu!(r#" 1..10 | each {|x| print -en $x; $x} | generate {|e, sum=0| let sum = $e + $sum; {out: $sum, next: $sum}} | first 5 | to nuon "#); assert_eq!(actual.out, "[1, 3, 6, 10, 15]"); assert_eq!(actual.err, "12345"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/nu_check.rs
crates/nu-command/tests/commands/nu_check.rs
use nu_test_support::fs::Stub::FileWithContentToBeTrimmed; use nu_test_support::nu; use nu_test_support::playground::Playground; #[test] fn parse_script_success() { Playground::setup("nu_check_test_1", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "script.nu", r#" greet "world" def greet [name] { echo "hello" $name } "#, )]); let actual = nu!(cwd: dirs.test(), " nu-check script.nu "); assert!(actual.err.is_empty()); }) } #[test] fn parse_script_with_wrong_type() { Playground::setup("nu_check_test_2", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "script.nu", r#" greet "world" def greet [name] { echo "hello" $name } "#, )]); let actual = nu!(cwd: dirs.test(), " nu-check --debug --as-module script.nu "); assert!(actual.err.contains("Failed to parse content")); }) } #[test] fn parse_script_failure() { Playground::setup("nu_check_test_3", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "script.nu", r#" greet "world" def greet [name { echo "hello" $name } "#, )]); let actual = nu!(cwd: dirs.test(), " nu-check --debug script.nu "); assert!(actual.err.contains("Unexpected end of code")); }) } #[test] fn parse_module_success() { Playground::setup("nu_check_test_4", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "foo.nu", r#" # foo.nu export def hello [name: string] { $"hello ($name)!" } export def hi [where: string] { $"hi ($where)!" } "#, )]); let actual = nu!(cwd: dirs.test(), " nu-check --as-module foo.nu "); assert!(actual.err.is_empty()); }) } #[test] fn parse_module_with_wrong_type() { Playground::setup("nu_check_test_5", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "foo.nu", r#" # foo.nu export def hello [name: string { $"hello ($name)!" } export def hi [where: string] { $"hi ($where)!" } "#, )]); let actual = nu!(cwd: dirs.test(), " nu-check --debug foo.nu "); assert!(actual.err.contains("Failed to parse content")); }) } #[test] fn parse_module_failure() { Playground::setup("nu_check_test_6", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "foo.nu", r#" # foo.nu export def hello [name: string { $"hello ($name)!" } export def hi [where: string] { $"hi ($where)!" } "#, )]); let actual = nu!(cwd: dirs.test(), " nu-check --debug --as-module foo.nu "); assert!(actual.err.contains("Unexpected end of code")); }) } #[test] fn file_not_exist() { Playground::setup("nu_check_test_7", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), " nu-check --as-module foo.nu "); assert!(actual.err.contains("nu::shell::io::file_not_found")); }) } #[test] fn parse_module_success_2() { Playground::setup("nu_check_test_10", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "foo.nu", r#" # foo.nu export-env { $env.MYNAME = "Arthur, King of the Britons" } "#, )]); let actual = nu!(cwd: dirs.test(), " nu-check --as-module foo.nu "); assert!(actual.err.is_empty()); }) } #[test] fn parse_script_success_with_raw_stream() { Playground::setup("nu_check_test_11", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "script.nu", r#" greet "world" def greet [name] { echo "hello" $name } "#, )]); let actual = nu!(cwd: dirs.test(), " open script.nu | nu-check "); assert!(actual.err.is_empty()); }) } #[test] fn parse_module_success_with_raw_stream() { Playground::setup("nu_check_test_12", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "foo.nu", r#" # foo.nu export def hello [name: string] { $"hello ($name)!" } export def hi [where: string] { $"hi ($where)!" } "#, )]); let actual = nu!(cwd: dirs.test(), " open foo.nu | nu-check --as-module "); assert!(actual.err.is_empty()); }) } #[test] fn parse_string_as_script_success() { Playground::setup("nu_check_test_13", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), r#" echo $'two(char nl)lines' | nu-check "#); assert!(actual.err.is_empty()); }) } #[test] fn parse_string_as_script() { Playground::setup("nu_check_test_14", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), r#" echo $'two(char nl)lines' | nu-check --debug --as-module "#); println!("the output is {}", actual.err); assert!(actual.err.contains("Failed to parse content")); }) } #[test] fn parse_module_success_with_internal_stream() { Playground::setup("nu_check_test_15", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "foo.nu", r#" # foo.nu export def hello [name: string] { $"hello ($name)!" } export def hi [where: string] { $"hi ($where)!" } "#, )]); let actual = nu!(cwd: dirs.test(), " open foo.nu | lines | nu-check --as-module "); assert!(actual.err.is_empty()); }) } #[test] fn parse_script_success_with_complex_internal_stream() { Playground::setup("nu_check_test_16", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "grep.nu", r#" #grep for nu def grep-nu [ search #search term entrada? #file or pipe # #Examples #grep-nu search file.txt #ls **/* | some_filter | grep-nu search #open file.txt | grep-nu search ] { if ($entrada | is-empty) { if ($in | column? name) { grep -ihHn $search ($in | get name) } else { ($in | into string) | grep -ihHn $search } } else { grep -ihHn $search $entrada } | lines | parse "{file}:{line}:{match}" | str trim | update match {|f| $f.match | nu-highlight } | rename "source file" "line number" } "#, )]); let actual = nu!(cwd: dirs.test(), " open grep.nu | lines | nu-check "); assert!(actual.err.is_empty()); }) } #[test] fn parse_script_failure_with_complex_internal_stream() { Playground::setup("nu_check_test_17", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "grep.nu", r#" #grep for nu def grep-nu [ search #search term entrada? #file or pipe # #Examples #grep-nu search file.txt #ls **/* | some_filter | grep-nu search #open file.txt | grep-nu search ] if ($entrada | is-empty) { if ($in | column? name) { grep -ihHn $search ($in | get name) } else { ($in | into string) | grep -ihHn $search } } else { grep -ihHn $search $entrada } | lines | parse "{file}:{line}:{match}" | str trim | update match {|f| $f.match | nu-highlight } | rename "source file" "line number" } "#, )]); let actual = nu!(cwd: dirs.test(), " open grep.nu | lines | nu-check "); assert_eq!(actual.out, "false".to_string()); }) } #[test] fn parse_script_success_with_complex_external_stream() { Playground::setup("nu_check_test_18", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "grep.nu", r#" #grep for nu def grep-nu [ search #search term entrada? #file or pipe # #Examples #grep-nu search file.txt #ls **/* | some_filter | grep-nu search #open file.txt | grep-nu search ] { if ($entrada | is-empty) { if ($in | column? name) { grep -ihHn $search ($in | get name) } else { ($in | into string) | grep -ihHn $search } } else { grep -ihHn $search $entrada } | lines | parse "{file}:{line}:{match}" | str trim | update match {|f| $f.match | nu-highlight } | rename "source file" "line number" } "#, )]); let actual = nu!(cwd: dirs.test(), " open grep.nu | nu-check "); assert!(actual.err.is_empty()); }) } #[test] fn parse_module_success_with_complex_external_stream() { Playground::setup("nu_check_test_19", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "grep.nu", r#" #grep for nu def grep-nu [ search #search term entrada? #file or pipe # #Examples #grep-nu search file.txt #ls **/* | some_filter | grep-nu search #open file.txt | grep-nu search ] { if ($entrada | is-empty) { if ($in | column? name) { grep -ihHn $search ($in | get name) } else { ($in | into string) | grep -ihHn $search } } else { grep -ihHn $search $entrada } | lines | parse "{file}:{line}:{match}" | str trim | update match {|f| $f.match | nu-highlight } | rename "source file" "line number" } "#, )]); let actual = nu!(cwd: dirs.test(), " open grep.nu | nu-check --debug --as-module "); assert!(actual.err.is_empty()); }) } #[test] fn parse_with_flag_success_for_complex_external_stream() { Playground::setup("nu_check_test_20", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "grep.nu", r#" #grep for nu def grep-nu [ search #search term entrada? #file or pipe # #Examples #grep-nu search file.txt #ls **/* | some_filter | grep-nu search #open file.txt | grep-nu search ] { if ($entrada | is-empty) { if ($in | column? name) { grep -ihHn $search ($in | get name) } else { ($in | into string) | grep -ihHn $search } } else { grep -ihHn $search $entrada } | lines | parse "{file}:{line}:{match}" | str trim | update match {|f| $f.match | nu-highlight } | rename "source file" "line number" } "#, )]); let actual = nu!(cwd: dirs.test(), " open grep.nu | nu-check --debug "); assert!(actual.err.is_empty()); }) } #[test] fn parse_with_flag_failure_for_complex_external_stream() { Playground::setup("nu_check_test_21", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "grep.nu", r#" #grep for nu def grep-nu search #search term entrada? #file or pipe # #Examples #grep-nu search file.txt #ls **/* | some_filter | grep-nu search #open file.txt | grep-nu search ] { if ($entrada | is-empty) { if ($in | column? name) { grep -ihHn $search ($in | get name) } else { ($in | into string) | grep -ihHn $search } } else { grep -ihHn $search $entrada } | lines | parse "{file}:{line}:{match}" | str trim | update match {|f| $f.match | nu-highlight } | rename "source file" "line number" } "#, )]); let actual = nu!(cwd: dirs.test(), " open grep.nu | nu-check --debug "); assert!(actual.err.contains("Failed to parse content")); }) } #[test] fn parse_with_flag_failure_for_complex_list_stream() { Playground::setup("nu_check_test_22", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "grep.nu", r#" #grep for nu def grep-nu search #search term entrada? #file or pipe # #Examples #grep-nu search file.txt #ls **/* | some_filter | grep-nu search #open file.txt | grep-nu search ] { if ($entrada | is-empty) { if ($in | column? name) { grep -ihHn $search ($in | get name) } else { ($in | into string) | grep -ihHn $search } } else { grep -ihHn $search $entrada } | lines | parse "{file}:{line}:{match}" | str trim | update match {|f| $f.match | nu-highlight } | rename "source file" "line number" } "#, )]); let actual = nu!(cwd: dirs.test(), " open grep.nu | lines | nu-check --debug "); assert!(actual.err.contains("Failed to parse content")); }) } #[test] fn parse_script_with_nested_scripts_success() { Playground::setup("nu_check_test_24", |dirs, sandbox| { sandbox .mkdir("lol") .with_files(&[FileWithContentToBeTrimmed( "lol/lol.nu", r#" source-env ../foo.nu use lol_shell.nu overlay use ../lol/lol_shell.nu "#, )]) .with_files(&[FileWithContentToBeTrimmed( "lol/lol_shell.nu", r#" export def ls [] { "lol" } "#, )]) .with_files(&[FileWithContentToBeTrimmed( "foo.nu", r#" $env.FOO = 'foo' "#, )]); let actual = nu!(cwd: dirs.test(), " nu-check lol/lol.nu "); assert_eq!(actual.out, "true"); }) } #[test] fn nu_check_respects_file_pwd() { Playground::setup("nu_check_test_25", |dirs, sandbox| { sandbox .mkdir("lol") .with_files(&[FileWithContentToBeTrimmed( "lol/lol.nu", r#" $env.RETURN = (nu-check ../foo.nu) "#, )]) .with_files(&[FileWithContentToBeTrimmed( "foo.nu", r#" echo 'foo' "#, )]); let actual = nu!(cwd: dirs.test(), " source-env lol/lol.nu; $env.RETURN "); assert_eq!(actual.out, "true"); }) } #[test] fn nu_check_module_dir() { Playground::setup("nu_check_test_26", |dirs, sandbox| { sandbox .mkdir("lol") .with_files(&[FileWithContentToBeTrimmed( "lol/mod.nu", r#" export module foo.nu export def main [] { 'lol' } "#, )]) .with_files(&[FileWithContentToBeTrimmed( "lol/foo.nu", r#" export def main [] { 'lol foo' } "#, )]); let actual = nu!(cwd: dirs.test(), "nu-check lol"); 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/exec.rs
crates/nu-command/tests/commands/exec.rs
use nu_test_support::nu; use nu_test_support::playground::Playground; #[test] fn basic_exec() { Playground::setup("test_exec_1", |dirs, _| { let actual = nu!(cwd: dirs.test(), r#" nu -n -c 'exec nu --testbin cococo a b c' "#); assert_eq!(actual.out, "a b c"); }) } #[test] fn exec_complex_args() { Playground::setup("test_exec_2", |dirs, _| { let actual = nu!(cwd: dirs.test(), r#" nu -n -c 'exec nu --testbin cococo b --bar=2 -sab --arwr - -DTEEE=aasd-290 -90 --' "#); assert_eq!(actual.out, "b --bar=2 -sab --arwr - -DTEEE=aasd-290 -90 --"); }) } #[test] fn exec_fail_batched_short_args() { Playground::setup("test_exec_3", |dirs, _| { let actual = nu!(cwd: dirs.test(), r#" nu -n -c 'exec nu --testbin cococo -ab 10' "#); assert_eq!(actual.out, ""); }) } #[test] fn exec_misc_values() { Playground::setup("test_exec_4", |dirs, _| { let actual = nu!(cwd: dirs.test(), r#" nu -n -c 'let x = "abc"; exec nu --testbin cococo $x ...[ a b c ]' "#); assert_eq!(actual.out, "abc a b c"); }) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/start.rs
crates/nu-command/tests/commands/start.rs
use super::*; use nu_engine::test_help::{convert_single_value_to_cmd_args, eval_block_with_input}; use nu_engine::{current_dir, eval_expression}; use nu_protocol::{ PipelineData, Span, Spanned, Type, Value, ast::Call, engine::{EngineState, Stack, StateWorkingSet}, }; use std::path::PathBuf; /// Create a minimal test engine state and stack to run commands against. fn create_test_context() -> (EngineState, Stack) { let mut engine_state = EngineState::new(); let mut stack = Stack::new(); // A working set is needed for storing definitions in the engine state. let _working_set = StateWorkingSet::new(&mut engine_state); // Add the `Start` command to the engine state so we can run it. let start_cmd = Start; engine_state.add_cmd(Box::new(start_cmd)); (engine_state, stack) } #[test] fn test_start_valid_url() { let (engine_state, mut stack) = create_test_context(); // For safety in tests, we won't actually open anything, // but we can still check that the command resolves as a URL // and attempts to run. Typically, you'd mock `open::commands` if needed. // Create call for: `start https://www.example.com` let path = "https://www.example.com".to_string(); let span = Span::test_data(); let call = Call::test( "start", // The arguments for `start` are just the path in this case vec![Value::string(path, span)], ); let result = Start.run(&engine_state, &mut stack, &call, PipelineData::empty); assert!( result.is_ok(), "Expected successful run with a valid URL, got error: {:?}", result.err() ); } #[test] fn test_start_valid_local_path() { let (engine_state, mut stack) = create_test_context(); // Here we'll simulate opening the current directory (`.`). let path = ".".to_string(); let span = Span::test_data(); let call = Call::test("start", vec![Value::string(path, span)]); let result = Start.run(&engine_state, &mut stack, &call, PipelineData::empty); // If the environment is correctly set, it should succeed. // If you're running in a CI environment or restricted environment // this might fail, so you may need to mock `open` calls. assert!( result.is_ok(), "Expected successful run opening current directory, got error: {:?}", result.err() ); } #[test] fn test_start_nonexistent_local_path() { let (engine_state, mut stack) = create_test_context(); // Create an obviously invalid path let path = "this_file_does_not_exist_hopefully.txt".to_string(); let span = Span::test_data(); let call = Call::test("start", vec![Value::string(path, span)]); let result = Start.run(&engine_state, &mut stack, &call, PipelineData::empty); // We expect an error since the file does not exist assert!( result.is_err(), "Expected an error for a non-existent file path" ); if let Err(ShellError::GenericError { error, .. }) = result { assert!( error.contains("Cannot find file or URL"), "Expected 'Cannot find file or URL' in error, found: {}", error ); } else { panic!("Unexpected error type, expected ShellError::GenericError"); } }
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_date.rs
crates/nu-command/tests/commands/seq_date.rs
use nu_test_support::nu; #[test] fn fails_on_datetime_input() { let actual = nu!("seq date --begin-date (date now)"); assert!(actual.err.contains("Type mismatch")) } #[test] fn fails_when_increment_not_integer_or_duration() { let actual = nu!("seq date --begin-date 2020-01-01 --increment 1.1"); assert!( actual .err .contains("expected one of a list of accepted shapes: [Duration, 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/histogram.rs
crates/nu-command/tests/commands/histogram.rs
use nu_test_support::nu; const SAMPLE_INPUT: &str = /* lang=nu */ r#"[ [first_name, last_name, rusty_at]; [Andrés, Robalino, Ecuador], [JT, Turner, "Estados Unidos"], [Yehuda, Katz, "Estados Unidos"] ]"#; #[test] fn summarizes_by_column_given() { let actual = nu!(format!( r#" {SAMPLE_INPUT} | histogram rusty_at countries --percentage-type relative | where rusty_at == "Ecuador" | get countries | get 0 "# )); assert_eq!( actual.out, "**************************************************" ); // 50% } #[test] fn summarizes_by_column_given_with_normalize_percentage() { let actual = nu!(format!( r#" {SAMPLE_INPUT} | histogram rusty_at countries | where rusty_at == "Ecuador" | get countries | get 0 "# )); assert_eq!(actual.out, "*********************************"); // 33% } #[test] fn summarizes_by_values() { let actual = nu!(format!( r#" {SAMPLE_INPUT} | get rusty_at | histogram | where value == "Estados Unidos" | get count | get 0 "# )); assert_eq!(actual.out, "2"); } #[test] fn help() { let help_command = nu!("help histogram"); let help_short = nu!("histogram -h"); let help_long = nu!("histogram --help"); assert_eq!(help_short.out, help_command.out); assert_eq!(help_long.out, help_command.out); } #[test] fn count() { let actual = nu!(" echo [[bit]; [1] [0] [0] [0] [0] [0] [0] [1] [1]] | histogram bit --percentage-type relative | sort-by count | reject frequency | to json "); let bit_json = r#"[ { "bit": 1, "count": 3, "quantile": 0.5, "percentage": "50.00%" }, { "bit": 0, "count": 6, "quantile": 1.0, "percentage": "100.00%" }]"#; assert_eq!(actual.out, bit_json); } #[test] fn count_with_normalize_percentage() { let actual = nu!(" echo [[bit]; [1] [0] [0] [0] [0] [0] [0] [1]] | histogram bit --percentage-type normalize | sort-by count | reject frequency | to json "); let bit_json = r#"[ { "bit": 1, "count": 2, "quantile": 0.25, "percentage": "25.00%" }, { "bit": 0, "count": 6, "quantile": 0.75, "percentage": "75.00%" }]"#; assert_eq!(actual.out, bit_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/print.rs
crates/nu-command/tests/commands/print.rs
use nu_test_support::nu; #[test] fn print_to_stdout() { let actual = nu!("print 'hello world'"); assert!(actual.out.contains("hello world")); assert!(actual.err.is_empty()); } #[test] fn print_to_stderr() { let actual = nu!("print -e 'hello world'"); assert!(actual.out.is_empty()); assert!(actual.err.contains("hello world")); } #[test] fn print_raw() { let actual = nu!("0x[41 42 43] | print --raw"); assert_eq!(actual.out, "ABC"); } #[test] fn print_raw_stream() { let actual = nu!("[0x[66] 0x[6f 6f]] | bytes collect | print --raw"); assert_eq!(actual.out, "foo"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/every.rs
crates/nu-command/tests/commands/every.rs
use nu_test_support::fs::Stub::EmptyFile; use nu_test_support::nu; use nu_test_support::playground::Playground; #[test] fn gets_all_rows_by_every_zero() { Playground::setup("every_test_1", |dirs, sandbox| { sandbox.with_files(&[ EmptyFile("amigos.txt"), EmptyFile("arepas.clu"), EmptyFile("los.txt"), EmptyFile("tres.txt"), ]); let actual = nu!(cwd: dirs.test(), " ls | get name | every 0 | to json --raw "); assert_eq!( actual.out, r#"["amigos.txt","arepas.clu","los.txt","tres.txt"]"# ); }) } #[test] fn gets_no_rows_by_every_skip_zero() { Playground::setup("every_test_2", |dirs, sandbox| { sandbox.with_files(&[ EmptyFile("amigos.txt"), EmptyFile("arepas.clu"), EmptyFile("los.txt"), EmptyFile("tres.txt"), ]); let actual = nu!(cwd: dirs.test(), " ls | get name | every 0 --skip | to json --raw "); assert_eq!(actual.out, "[]"); }) } #[test] fn gets_all_rows_by_every_one() { Playground::setup("every_test_3", |dirs, sandbox| { sandbox.with_files(&[ EmptyFile("amigos.txt"), EmptyFile("arepas.clu"), EmptyFile("los.txt"), EmptyFile("tres.txt"), ]); let actual = nu!(cwd: dirs.test(), " ls | get name | every 1 | to json --raw "); assert_eq!( actual.out, r#"["amigos.txt","arepas.clu","los.txt","tres.txt"]"# ); }) } #[test] fn gets_no_rows_by_every_skip_one() { Playground::setup("every_test_4", |dirs, sandbox| { sandbox.with_files(&[ EmptyFile("amigos.txt"), EmptyFile("arepas.clu"), EmptyFile("los.txt"), EmptyFile("tres.txt"), ]); let actual = nu!(cwd: dirs.test(), " ls | get name | every 1 --skip | to json --raw "); assert_eq!(actual.out, "[]"); }) } #[test] fn gets_first_row_by_every_too_much() { Playground::setup("every_test_5", |dirs, sandbox| { sandbox.with_files(&[ EmptyFile("amigos.txt"), EmptyFile("arepas.clu"), EmptyFile("los.txt"), EmptyFile("tres.txt"), ]); let actual = nu!(cwd: dirs.test(), " ls | get name | every 999 "); let expected = nu!( cwd: dirs.test(), "echo [ amigos.txt ]"); assert_eq!(actual.out, expected.out); }) } #[test] fn gets_all_rows_except_first_by_every_skip_too_much() { Playground::setup("every_test_6", |dirs, sandbox| { sandbox.with_files(&[ EmptyFile("amigos.txt"), EmptyFile("arepas.clu"), EmptyFile("los.txt"), EmptyFile("tres.txt"), ]); let actual = nu!(cwd: dirs.test(), " ls | get name | every 999 --skip | to json --raw "); assert_eq!(actual.out, r#"["arepas.clu","los.txt","tres.txt"]"#); }) } #[test] fn gets_every_third_row() { Playground::setup("every_test_7", |dirs, sandbox| { sandbox.with_files(&[ EmptyFile("amigos.txt"), EmptyFile("arepas.clu"), EmptyFile("los.txt"), EmptyFile("quatro.txt"), EmptyFile("tres.txt"), ]); let actual = nu!(cwd: dirs.test(), " ls | get name | every 3 | to json --raw "); assert_eq!(actual.out, r#"["amigos.txt","quatro.txt"]"#); }) } #[test] fn skips_every_third_row() { Playground::setup("every_test_8", |dirs, sandbox| { sandbox.with_files(&[ EmptyFile("amigos.txt"), EmptyFile("arepas.clu"), EmptyFile("los.txt"), EmptyFile("quatro.txt"), EmptyFile("tres.txt"), ]); let actual = nu!(cwd: dirs.test(), " ls | get name | every 3 --skip | to json --raw "); assert_eq!(actual.out, r#"["arepas.clu","los.txt","tres.txt"]"#); }) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/inspect.rs
crates/nu-command/tests/commands/inspect.rs
use nu_test_support::nu; #[test] fn inspect_with_empty_pipeline() { let actual = nu!("inspect"); assert!(actual.err.contains("no input value was piped in")); } #[test] fn inspect_with_empty_list() { let actual = nu!("[] | inspect"); assert!(actual.out.contains("empty list")); } #[test] fn inspect_with_empty_record() { let actual = nu!("{} | inspect"); assert!(actual.out.contains("empty record")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/detect_columns.rs
crates/nu-command/tests/commands/detect_columns.rs
use nu_test_support::{nu, playground::Playground}; #[test] fn detect_columns_with_legacy() { let cases = [( "$\"c1 c2 c3 c4 c5(char nl)a b c d e\"", "[[c1,c2,c3,c4,c5]; [a,b,c,d,e]]", )]; Playground::setup("detect_columns_test_1", |dirs, _| { for case in cases.into_iter() { let out = nu!( cwd: dirs.test(), format!( "({} | detect columns) == {}", case.0, case.1 ) ); assert_eq!( out.out, "true", "({} | detect columns) == {}", case.0, case.1 ); } }); } #[test] fn detect_columns_with_legacy_and_flag_c() { let cases = [ ( "$\"c1 c2 c3 c4 c5(char nl)a b c d e\"", "[[c1,c3,c4,c5]; ['a b',c,d,e]]", "0..1", ), ( "$\"c1 c2 c3 c4 c5(char nl)a b c d e\"", "[[c1,c2,c3,c4]; [a,b,c,'d e']]", "(-2)..(-1)", ), ( "$\"c1 c2 c3 c4 c5(char nl)a b c d e\"", "[[c1,c2,c3]; [a,b,'c d e']]", "2..", ), ]; Playground::setup("detect_columns_test_1", |dirs, _| { for case in cases.into_iter() { let out = nu!( cwd: dirs.test(), format!( "({} | detect columns --combine-columns {}) == {}", case.0, case.2, case.1, ) ); assert_eq!( out.out, "true", "({} | detect columns --combine-columns {}) == {}", case.0, case.2, case.1 ); } }); } #[test] fn detect_columns_with_flag_c() { let body = r#""total 284K drwxr-xr-x 2 root root 4.0K Mar 20 08:28 = drwxr-xr-x 4 root root 4.0K Mar 20 08:18 ~ -rw-r--r-- 1 root root 3.0K Mar 20 07:23 ~asdf ""#; let expected = r#"[ ['column0', 'column1', 'column2', 'column3', 'column4', 'column5', 'column7', 'column8']; ['drwxr-xr-x', '2', 'root', 'root', '4.0K', 'Mar 20', '08:28', '='], ['drwxr-xr-x', '4', 'root', 'root', '4.0K', 'Mar 20', '08:18', '~'], ['-rw-r--r--', '1', 'root', 'root', '3.0K', 'Mar 20', '07:23', '~asdf'] ]"#; let range = "5..6"; let cmd = format!("({body} | detect columns -c {range} -s 1 --no-headers) == {expected}",); println!("debug cmd: {cmd}"); Playground::setup("detect_columns_test_1", |dirs, _| { let out = nu!( cwd: dirs.test(), cmd, ); println!("{}", out.out); assert_eq!(out.out, "true"); }) } #[test] fn detect_columns_may_fail() { let out = nu!(r#""meooooow cat\nkitty kitty woof" | try { detect columns } catch { "failed" }"#); assert_eq!(out.out, "failed"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/wrap.rs
crates/nu-command/tests/commands/wrap.rs
use nu_test_support::nu; #[test] fn wrap_rows_into_a_row() { let sample = r#"[ [first_name, last_name]; [Andrés, Robalino], [JT, Turner], [Yehuda, Katz] ]"#; let actual = nu!(format!( " {sample} | wrap caballeros | get caballeros | get 0 | get last_name " )); assert_eq!(actual.out, "Robalino"); } #[test] fn wrap_rows_into_a_table() { let sample = r#"[ [first_name, last_name]; [Andrés, Robalino], [JT, Turner], [Yehuda, Katz] ]"#; let actual = nu!(format!( " {sample} | get last_name | wrap caballero | get 2 | get caballero " )); assert_eq!(actual.out, "Katz"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/get.rs
crates/nu-command/tests/commands/get.rs
use nu_test_support::fs::Stub::FileWithContent; use nu_test_support::nu; use nu_test_support::playground::Playground; #[test] fn simple_get_record() { let actual = nu!(r#"({foo: 'bar'} | get foo) == "bar""#); assert_eq!(actual.out, "true"); } #[test] fn simple_get_list() { let actual = nu!(r#"([{foo: 'bar'}] | get foo) == [bar]"#); assert_eq!(actual.out, "true"); } #[test] fn fetches_a_row() { Playground::setup("get_test_1", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" nu_party_venue = "zion" "#, )]); let actual = nu!( cwd: dirs.test(), "open sample.toml | get nu_party_venue"); assert_eq!(actual.out, "zion"); }) } #[test] fn fetches_by_index() { Playground::setup("get_test_2", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [package] name = "nu" version = "0.4.1" authors = ["Yehuda Katz <wycats@gmail.com>", "JT Turner <547158+jntrnr@users.noreply.github.com>", "Andrés N. Robalino <andres@androbtech.com>"] description = "When arepas shells are tasty and fun." "#, )]); let actual = nu!( cwd: dirs.test(), "open sample.toml | get package.authors.2"); assert_eq!(actual.out, "Andrés N. Robalino <andres@androbtech.com>"); }) } #[test] fn fetches_by_column_path() { Playground::setup("get_test_3", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [package] name = "nu" "#, )]); let actual = nu!( cwd: dirs.test(), "open sample.toml | get package.name"); assert_eq!(actual.out, "nu"); }) } #[test] fn column_paths_are_either_double_quoted_or_regular_unquoted_words_separated_by_dot() { Playground::setup("get_test_4", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [package] 9999 = ["Yehuda Katz <wycats@gmail.com>", "JT Turner <jtd.turner@gmail.com>", "Andrés N. Robalino <andres@androbtech.com>"] description = "When arepas shells are tasty and fun." "#, )]); let actual = nu!( cwd: dirs.test(), r#"open sample.toml | get package."9999" | length"#); assert_eq!(actual.out, "3"); }) } #[test] fn fetches_more_than_one_column_path() { Playground::setup("get_test_5", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [[fortune_tellers]] name = "Andrés N. Robalino" arepas = 1 [[fortune_tellers]] name = "JT" arepas = 1 [[fortune_tellers]] name = "Yehuda Katz" arepas = 1 "#, )]); let actual = nu!(cwd: dirs.test(), " open sample.toml | get fortune_tellers.2.name fortune_tellers.0.name fortune_tellers.1.name | get 2 "); assert_eq!(actual.out, "JT"); }) } #[test] fn errors_fetching_by_column_not_present() { Playground::setup("get_test_6", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [tacos] sentence_words = ["Yo", "quiero", "tacos"] [pizzanushell] sentence-words = ["I", "want", "pizza"] "#, )]); let actual = nu!( cwd: dirs.test(), "open sample.toml | get taco"); assert!(actual.err.contains("Name not found"),); assert!(actual.err.contains("did you mean 'tacos'"),); }) } #[test] fn errors_fetching_by_column_using_a_number() { Playground::setup("get_test_7", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [spanish_lesson] 0 = "can only be fetched with 0 double quoted." "#, )]); let actual = nu!( cwd: dirs.test(), "open sample.toml | get spanish_lesson.0"); assert!(actual.err.contains("Type mismatch"),); }) } #[test] fn errors_fetching_by_index_out_of_bounds() { Playground::setup("get_test_8", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [spanish_lesson] sentence_words = ["Yo", "quiero", "taconushell"] "#, )]); let actual = nu!( cwd: dirs.test(), " open sample.toml | get spanish_lesson.sentence_words.3 "); assert!(actual.err.contains("Row number too large (max: 2)"),); assert!(actual.err.contains("too large"),); }) } #[test] fn errors_fetching_by_accessing_empty_list() { let actual = nu!("[] | get 3"); assert!(actual.err.contains("Row number too large (empty content)"),); } #[test] fn quoted_column_access() { let actual = nu!(r#"'[{"foo bar": {"baz": 4}}]' | from json | get "foo bar".baz.0 "#); assert_eq!(actual.out, "4"); } #[test] fn get_does_not_delve_too_deep_in_nested_lists() { let actual = nu!("[[{foo: bar}]] | get foo"); assert!(actual.err.contains("cannot find column")); } #[test] fn ignore_errors_works() { let actual = nu!(r#" let path = "foo"; {} | get -o $path | to nuon "#); assert_eq!(actual.out, "null"); } #[test] fn ignore_multiple() { let actual = nu!(r#"[[a];[b]] | get -o c d | to nuon"#); assert_eq!(actual.out, "[[null], [null]]"); } #[test] fn test_const() { let actual = nu!(r#"const x = [1 2 3] | get 1; $x"#); 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/to_text.rs
crates/nu-command/tests/commands/to_text.rs
use nu_test_support::nu; const LINE_LEN: usize = if cfg!(target_os = "windows") { 2 } else { 1 }; #[test] fn list() { // Using `str length` since nu! strips newlines, grr let actual = nu!(r#"[] | to text | str length"#); assert_eq!(actual.out, "0"); let actual = nu!(r#"[a] | to text | str length"#); assert_eq!(actual.out, (1 + LINE_LEN).to_string()); let actual = nu!(r#"[a b] | to text | str length"#); assert_eq!(actual.out, (2 * (1 + LINE_LEN)).to_string()); } // The output should be the same when `to text` gets a ListStream instead of a Value::List. #[test] fn list_stream() { let actual = nu!(r#"[] | each {} | to text | str length"#); assert_eq!(actual.out, "0"); let actual = nu!(r#"[a] | each {} | to text | str length"#); assert_eq!(actual.out, (1 + LINE_LEN).to_string()); let actual = nu!(r#"[a b] | each {} | to text | str length"#); assert_eq!(actual.out, (2 * (1 + LINE_LEN)).to_string()); } #[test] fn list_no_newline() { let actual = nu!(r#"[] | to text -n | str length"#); assert_eq!(actual.out, "0"); let actual = nu!(r#"[a] | to text -n | str length"#); assert_eq!(actual.out, "1"); let actual = nu!(r#"[a b] | to text -n | str length"#); assert_eq!(actual.out, (2 + LINE_LEN).to_string()); } // The output should be the same when `to text` gets a ListStream instead of a Value::List. #[test] fn list_stream_no_newline() { let actual = nu!(r#"[] | each {} | to text -n | str length"#); assert_eq!(actual.out, "0"); let actual = nu!(r#"[a] | each {} | to text -n | str length"#); assert_eq!(actual.out, "1"); let actual = nu!(r#"[a b] | each {} | to text -n | str length"#); assert_eq!(actual.out, (2 + LINE_LEN).to_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/mktemp.rs
crates/nu-command/tests/commands/mktemp.rs
use nu_path::AbsolutePath; use nu_test_support::nu; use nu_test_support::playground::Playground; #[test] fn creates_temp_file() { Playground::setup("mktemp_test_1", |dirs, _| { let output = nu!( cwd: dirs.test(), "mktemp" ); let loc = AbsolutePath::try_new(&output.out).unwrap(); println!("{loc:?}"); assert!(loc.exists()); }) } #[test] fn creates_temp_file_with_suffix() { Playground::setup("mktemp_test_2", |dirs, _| { let output = nu!( cwd: dirs.test(), "mktemp --suffix .txt tempfileXXX" ); let loc = AbsolutePath::try_new(&output.out).unwrap(); assert!(loc.exists()); assert!(loc.is_file()); assert!(output.out.ends_with(".txt")); assert!(output.out.starts_with(dirs.test().to_str().unwrap())); }) } #[test] fn creates_temp_directory() { Playground::setup("mktemp_test_3", |dirs, _| { let output = nu!( cwd: dirs.test(), "mktemp -d" ); let loc = AbsolutePath::try_new(&output.out).unwrap(); assert!(loc.exists()); assert!(loc.is_dir()); }) } #[test] fn doesnt_create_temp_file() { Playground::setup("mktemp_test_1", |dirs, _| { let output = nu!( cwd: dirs.test(), "mktemp --dry" ); let loc = AbsolutePath::try_new(&output.out).unwrap(); println!("{loc:?}"); assert!(!loc.exists()); }) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/loop_.rs
crates/nu-command/tests/commands/loop_.rs
use nu_test_support::nu; #[test] fn loop_doesnt_auto_print_in_each_iteration() { let actual = nu!(" mut total = 0; loop { if $total == 3 { break; } else { $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 loop_break_on_external_failed() { let actual = nu!(" mut total = 0; loop { if $total == 3 { break; } else { $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_loop_should_break_running() { let actual = nu!(" mut total = 0; loop { if $total == 3 { break; } else { $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/continue_.rs
crates/nu-command/tests/commands/continue_.rs
use nu_test_support::nu; #[test] fn continue_for_loop() { let actual = nu!("for i in 1..10 { if $i == 2 { continue }; print $i }"); assert_eq!(actual.out, "1345678910"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/str_/into_string.rs
crates/nu-command/tests/commands/str_/into_string.rs
use nu_test_support::fs::Stub::FileWithContentToBeTrimmed; use nu_test_support::nu; use nu_test_support::playground::Playground; #[test] fn from_range() { let actual = nu!(r#" echo 1..5 | into string | to json -r "#); assert_eq!(actual.out, "[\"1\",\"2\",\"3\",\"4\",\"5\"]"); } #[test] fn from_number() { let actual = nu!(r#" echo 5 | into string "#); assert_eq!(actual.out, "5"); } #[test] fn from_float() { let actual = nu!(r#" echo 1.5 | into string "#); assert_eq!(actual.out, "1.5"); } #[test] fn from_boolean() { let actual = nu!(r#" echo true | into string "#); assert_eq!(actual.out, "true"); } #[test] fn from_cell_path() { let actual = nu!(r#" $.test | into string "#); assert_eq!(actual.out, "$.test"); } #[test] fn from_string() { let actual = nu!(r#" echo "one" | into string "#); assert_eq!(actual.out, "one"); } #[test] fn from_filename() { Playground::setup("from_filename", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "sample.toml", r#" [dependency] name = "nu" "#, )]); let actual = nu!( cwd: dirs.test(), "ls sample.toml | get name | into string | get 0" ); assert_eq!(actual.out, "sample.toml"); }) } #[test] fn from_filesize() { Playground::setup("from_filesize", |dirs, sandbox| { sandbox.with_files(&[FileWithContentToBeTrimmed( "sample.toml", r#" [dependency] name = "nu" "#, )]); let actual = nu!( cwd: dirs.test(), "ls sample.toml | get size | into string | get 0" ); let expected = if cfg!(windows) { "27 B" } else { "25 B" }; assert_eq!(actual.out, expected); }) } #[test] fn from_float_correct_trailing_zeros() { let actual = nu!(r#" 1.23000 | into string -d 3 "#); assert!(actual.out.contains("1.230")); } #[test] fn from_int_float_correct_trailing_zeros() { let actual = nu!(r#" 1.00000 | into string -d 3 "#); assert!(actual.out.contains("1.000")); } #[test] fn from_int_float_trim_trailing_zeros() { let actual = nu!(r#" 1.00000 | into string | $"($in) flat" "#); assert!(actual.out.contains("1 flat")); // "1" would match "1.0" } #[test] fn from_table() { let actual = nu!(r#" echo '[{"name": "foo", "weight": 32.377}, {"name": "bar", "weight": 15.2}]' | from json | into string weight -d 2 "#); assert!(actual.out.contains("32.38")); assert!(actual.out.contains("15.20")); } #[test] fn from_nothing() { let actual = nu!(r#" null | into string "#); assert_eq!(actual.out, ""); } #[test] fn int_into_string() { let actual = nu!(r#" 10 | into string "#); assert_eq!(actual.out, "10"); } #[test] fn int_into_string_decimals_0() { let actual = nu!(locale: "en_US.UTF-8", r#" 10 | into string --decimals 0 "#); assert_eq!(actual.out, "10"); } #[test] fn int_into_string_decimals_1() { let actual = nu!(locale: "en_US.UTF-8", r#" 10 | into string --decimals 1 "#); assert_eq!(actual.out, "10.0"); } #[test] fn int_into_string_decimals_10() { let actual = nu!(locale: "en_US.UTF-8", r#" 10 | into string --decimals 10 "#); assert_eq!(actual.out, "10.0000000000"); } #[test] fn int_into_string_decimals_respects_system_locale_de() { // Set locale to `de_DE`, which uses `,` (comma) as decimal separator let actual = nu!(locale: "de_DE.UTF-8", r#" 10 | into string --decimals 1 "#); assert_eq!(actual.out, "10,0"); } #[test] fn int_into_string_decimals_respects_system_locale_en() { // Set locale to `en_US`, which uses `.` (period) as decimal separator let actual = nu!(locale: "en_US.UTF-8", r#" 10 | into string --decimals 1 "#); assert_eq!(actual.out, "10.0"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/str_/mod.rs
crates/nu-command/tests/commands/str_/mod.rs
mod into_string; mod join; use nu_test_support::fs::Stub::FileWithContent; use nu_test_support::nu; use nu_test_support::playground::Playground; #[test] fn trims() { Playground::setup("str_test_1", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [dependency] name = "nu " "#, )]); let actual = nu!( cwd: dirs.test(), "open sample.toml | str trim dependency.name | get dependency.name" ); assert_eq!(actual.out, "nu"); }) } #[test] fn error_trim_multiple_chars() { let actual = nu!(r#" echo "does it work now?!" | str trim --char "?!" "#); assert!(actual.err.contains("char")); } #[test] fn capitalizes() { Playground::setup("str_test_2", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [dependency] name = "nu" "#, )]); let actual = nu!( cwd: dirs.test(), "open sample.toml | str capitalize dependency.name | get dependency.name" ); assert_eq!(actual.out, "Nu"); }) } #[test] fn downcases() { Playground::setup("str_test_3", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [dependency] name = "LIGHT" "#, )]); let actual = nu!( cwd: dirs.test(), "open sample.toml | str downcase dependency.name | get dependency.name" ); assert_eq!(actual.out, "light"); }) } #[test] fn non_ascii_downcase() { let actual = nu!("'ὈΔΥΣΣΕΎΣ' | str downcase"); assert_eq!(actual.out, "ὀδυσσεύς"); } #[test] fn upcases() { Playground::setup("str_test_4", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [package] name = "nushell" "#, )]); let actual = nu!( cwd: dirs.test(), "open sample.toml | str upcase package.name | get package.name" ); assert_eq!(actual.out, "NUSHELL"); }) } #[test] fn non_ascii_upcase() { let actual = nu!("'ὀδυσσεύς' | str upcase"); assert_eq!(actual.out, "ὈΔΥΣΣΕΎΣ"); } #[test] #[ignore = "Playgrounds are not supported in nu-cmd-extra"] fn camelcases() { Playground::setup("str_test_3", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [dependency] name = "THIS_IS_A_TEST" "#, )]); let actual = nu!( cwd: dirs.test(), "open sample.toml | str camel-case dependency.name | get dependency.name" ); assert_eq!(actual.out, "thisIsATest"); }) } #[test] fn converts_to_int() { let actual = nu!(r#" echo '[{number_as_string: "1"}]' | from json | into int number_as_string | rename number | where number == 1 | get number.0 "#); assert_eq!(actual.out, "1"); } #[test] fn converts_to_float() { let actual = nu!(r#" echo "3.1, 0.0415" | split row "," | into float | math sum "#); assert_eq!(actual.out, "3.1415"); } #[test] fn find_and_replaces() { Playground::setup("str_test_6", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [fortune.teller] phone = "1-800-KATZ" "#, )]); let actual = nu!(cwd: dirs.test(), r#" open sample.toml | str replace KATZ "5289" fortune.teller.phone | get fortune.teller.phone "#); assert_eq!(actual.out, "1-800-5289"); }) } #[test] fn find_and_replaces_without_passing_field() { Playground::setup("str_test_7", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [fortune.teller] phone = "1-800-KATZ" "#, )]); let actual = nu!(cwd: dirs.test(), r#" open sample.toml | get fortune.teller.phone | str replace KATZ "5289" "#); assert_eq!(actual.out, "1-800-5289"); }) } #[test] fn regex_error_in_pattern() { Playground::setup("str_test_8", |dirs, _sandbox| { let actual = nu!(cwd: dirs.test(), r#" 'source string' | str replace -r 'source \Ufoo' "destination" "#); let err = actual.err; let expecting_str = "Incorrect value"; assert!( err.contains(expecting_str), "Error should contain '{expecting_str}', but was: {err}" ); }) } #[test] fn find_and_replaces_with_closure() { let actual = nu!(r#" 'source string' | str replace 'str' { str upcase } "#); assert_eq!(actual.out, "source STRing"); } #[test] fn find_and_replaces_regex_with_closure() { let actual = nu!(r#" 'source string' | str replace -r 's(..)ing' {|capture| $"($capture) from ($in)" } "#); assert_eq!(actual.out, "source tr from string"); } #[test] fn find_and_replaces_closure_error() { let actual = nu!(r#" 'source string' | str replace 'str' { 1 / 0 } "#); let err = actual.err; let expecting_str = "division by zero"; assert!( err.contains(expecting_str), "Error should contain '{expecting_str}', but was: {err}" ); } #[test] fn find_and_replaces_regex_closure_error() { let actual = nu!(r#" 'source string' | str replace -r 'str' { 1 / 0 } "#); let err = actual.err; let expecting_str = "division by zero"; assert!( err.contains(expecting_str), "Error should contain '{expecting_str}', but was: {err}" ); } #[test] fn find_and_replaces_closure_type_mismatch() { let actual = nu!(r#" 'source string' | str replace 'str' { 42 } "#); let err = actual.err; let expecting_str = "nu::shell::type_mismatch"; assert!( err.contains(expecting_str), "Error should contain '{expecting_str}', but was: {err}" ); } #[test] fn find_and_replaces_regex_closure_type_mismatch() { let actual = nu!(r#" 'source string' | str replace -r 'str' { 42 } "#); let err = actual.err; let expecting_str = "nu::shell::type_mismatch"; assert!( err.contains(expecting_str), "Error should contain '{expecting_str}', but was: {err}" ); } #[test] fn substrings_the_input() { Playground::setup("str_test_8", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [fortune.teller] phone = "1-800-ROBALINO" "#, )]); let actual = nu!(cwd: dirs.test(), r#" open sample.toml | str substring 6..14 fortune.teller.phone | get fortune.teller.phone "#); assert_eq!(actual.out, "ROBALINO"); }) } #[test] fn substring_empty_if_start_index_is_greater_than_end_index() { Playground::setup("str_test_9", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [fortune.teller] phone = "1-800-ROBALINO" "#, )]); let actual = nu!(cwd: dirs.test(), r#" open sample.toml | str substring 6..4 fortune.teller.phone | get fortune.teller.phone "#); assert_eq!(actual.out, "") }) } #[test] fn substrings_the_input_and_returns_the_string_if_end_index_exceeds_length() { Playground::setup("str_test_10", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [package] name = "nu-arepas" "#, )]); let actual = nu!(cwd: dirs.test(), r#" open sample.toml | str substring 0..999 package.name | get package.name "#); assert_eq!(actual.out, "nu-arepas"); }) } #[test] fn substrings_the_input_and_returns_blank_if_start_index_exceeds_length() { Playground::setup("str_test_11", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [package] name = "nu-arepas" "#, )]); let actual = nu!(cwd: dirs.test(), r#" open sample.toml | str substring 50..999 package.name | get package.name "#); assert_eq!(actual.out, ""); }) } #[test] fn substrings_the_input_and_treats_start_index_as_zero_if_blank_start_index_given() { Playground::setup("str_test_12", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [package] name = "nu-arepas" "#, )]); let actual = nu!(cwd: dirs.test(), r#" open sample.toml | str substring ..1 package.name | get package.name "#); assert_eq!(actual.out, "nu"); }) } #[test] fn substrings_the_input_and_treats_end_index_as_length_if_blank_end_index_given() { Playground::setup("str_test_13", |dirs, sandbox| { sandbox.with_files(&[FileWithContent( "sample.toml", r#" [package] name = "nu-arepas" "#, )]); let actual = nu!(cwd: dirs.test(), r#" open sample.toml | str substring 3.. package.name | get package.name "#); assert_eq!(actual.out, "arepas"); }) } #[test] fn substring_by_negative_index() { Playground::setup("str_test_13", |dirs, _| { let actual = nu!( cwd: dirs.test(), "'apples' | str substring 0..-1", ); assert_eq!(actual.out, "apples"); let actual = nu!( cwd: dirs.test(), "'apples' | str substring 0..<-1", ); assert_eq!(actual.out, "apple"); }) } #[test] fn substring_of_empty_string() { let actual = nu!("'' | str substring ..0"); assert_eq!(actual.err, ""); assert_eq!(actual.out, ""); } #[test] fn substring_drops_content_type() { let actual = nu!(format!( "open {} | str substring 0..2 | metadata | get content_type? | describe", file!(), )); assert_eq!(actual.out, "nothing"); } #[test] fn str_reverse() { let actual = nu!(r#" echo "nushell" | str reverse "#); assert!(actual.out.contains("llehsun")); } #[test] fn test_redirection_trim() { let actual = nu!(r#" let x = (nu --testbin cococo niceone); $x | str trim | str length "#); assert_eq!(actual.out, "7"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/str_/join.rs
crates/nu-command/tests/commands/str_/join.rs
use nu_test_support::nu; #[test] fn test_1() { let actual = nu!(r#" echo 1..5 | into string | str join "#); assert_eq!(actual.out, "12345"); } #[test] fn test_2() { let actual = nu!(r#" echo [a b c d] | str join "<sep>" "#); assert_eq!(actual.out, "a<sep>b<sep>c<sep>d"); } #[test] fn test_stream() { let actual = nu!("[a b c d] | filter {true} | str join ."); assert_eq!(actual.out, "a.b.c.d"); } #[test] fn test_stream_type() { let actual = nu!("[a b c d] | filter {true} | str join . | describe -n"); assert_eq!(actual.out, "string (stream)"); } #[test] fn construct_a_path() { let actual = nu!(r#" echo [sample txt] | str join "." "#); assert_eq!(actual.out, "sample.txt"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/take/until.rs
crates/nu-command/tests/commands/take/until.rs
use nu_test_support::nu; #[test] fn condition_is_met() { let sample = r#"[ ["Chicken Collection", "29/04/2020", "30/04/2020", "31/04/2020"]; ["Yellow Chickens", "", "", ""], [Andrés, 1, 1, 1], [JT, 1, 1, 1], [Jason, 1, 1, 1], [Yehuda, 1, 1, 1], ["Blue Chickens", "", "", ""], [Andrés, 1, 1, 2], [JT, 1, 1, 2], [Jason, 1, 1, 2], [Yehuda, 1, 1, 2], ["Red Chickens", "", "", ""], [Andrés, 1, 1, 3], [JT, 1, 1, 3], [Jason, 1, 1, 3], [Yehuda, 1, 1, 3] ]"#; let actual = nu!(format!( r#" {sample} | skip while {{|row| $row."Chicken Collection" != "Blue Chickens" }} | take until {{|row| $row."Chicken Collection" == "Red Chickens" }} | skip 1 | into int "31/04/2020" | get "31/04/2020" | math sum "# )); assert_eq!(actual.out, "8"); } #[test] fn fail_on_non_iterator() { let actual = nu!("1 | take until {|row| $row == 2}"); 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/take/rows.rs
crates/nu-command/tests/commands/take/rows.rs
use nu_test_support::nu; #[test] fn rows() { let sample = r#" [[name, lucky_code]; [Andrés, 1], [JT , 1], [Jason , 2], [Yehuda, 1]]"#; let actual = nu!(format!( r#" {sample} | take 3 | get lucky_code | math sum "# )); assert_eq!(actual.out, "4"); } #[test] fn rows_with_no_arguments_should_lead_to_error() { let actual = nu!("[1 2 3] | take"); assert!(actual.err.contains("missing_positional")); } #[test] fn fails_on_string() { let actual = nu!(r#""foo bar" | take 2"#); assert!(actual.err.contains("command doesn't support")); } #[test] fn takes_bytes() { let actual = nu!("(0x[aa bb cc] | take 2) == 0x[aa bb]"); assert_eq!(actual.out, "true"); } #[test] fn takes_bytes_from_stream() { let actual = nu!("(1.. | each { 0x[aa bb cc] } | bytes collect | take 2) == 0x[aa bb]"); assert_eq!(actual.out, "true"); } #[test] // covers a situation where `take` used to behave strangely on list<binary> input fn works_with_binary_list() { let actual = nu!(r#" ([0x[01 11]] | take 1 | get 0) == 0x[01 11] "#); assert_eq!(actual.out, "true"); } #[test] fn takes_bytes_and_drops_content_type() { let actual = nu!(format!( "open {} | take 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/take/while_.rs
crates/nu-command/tests/commands/take/while_.rs
use nu_test_support::nu; #[test] fn condition_is_met() { let sample = r#"[ ["Chicken Collection", "29/04/2020", "30/04/2020", "31/04/2020"]; ["Yellow Chickens", "", "", ""], [Andrés, 1, 1, 1], [JT, 1, 1, 1], [Jason, 1, 1, 1], [Yehuda, 1, 1, 1], ["Blue Chickens", "", "", ""], [Andrés, 1, 1, 2], [JT, 1, 1, 2], [Jason, 1, 1, 2], [Yehuda, 1, 1, 2], ["Red Chickens", "", "", ""], [Andrés, 1, 1, 3], [JT, 1, 1, 3], [Jason, 1, 1, 3], [Yehuda, 1, 1, 3] ]"#; let actual = nu!(format!( r#" {sample} | skip 1 | take while {{|row| $row."Chicken Collection" != "Blue Chickens"}} | into int "31/04/2020" | get "31/04/2020" | math sum "# )); assert_eq!(actual.out, "4"); } #[test] fn fail_on_non_iterator() { let actual = nu!("1 | take while {|row| $row == 2}"); 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/take/mod.rs
crates/nu-command/tests/commands/take/mod.rs
mod rows; mod until; mod while_;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/query/db.rs
crates/nu-command/tests/commands/query/db.rs
use nu_test_support::nu; #[cfg(feature = "sqlite")] #[test] fn can_query_single_table() { let actual = nu!(cwd: "tests/fixtures/formats", r#" open sample.db | query db "select * from strings" | where x =~ ell | length "#); assert_eq!(actual.out, "4"); } #[cfg(feature = "sqlite")] #[test] fn invalid_sql_fails() { let actual = nu!(cwd: "tests/fixtures/formats", r#" open sample.db | query db "select *asdfasdf" "#); assert!(actual.err.contains("syntax error")); } #[cfg(feature = "sqlite")] #[test] fn invalid_input_fails() { let actual = nu!(cwd: "tests/fixtures/formats", r#" "foo" | query db "select * from asdf" "#); assert!(actual.err.contains("can't convert 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/query/mod.rs
crates/nu-command/tests/commands/query/mod.rs
mod db;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/base/base32hex.rs
crates/nu-command/tests/commands/base/base32hex.rs
use nu_test_support::nu; #[test] fn canonical() { super::test_canonical("base32hex"); super::test_canonical("base32hex --nopad"); } #[test] fn const_() { super::test_const("base32hex"); super::test_const("base32hex --nopad"); } #[test] fn encode() { let text = "Ș̗͙̂̏o̲̲̗͗̌͊m̝̊̓́͂ë̡̦̞̤́̌̈́̀ ̥̝̪̎̿ͅf̧̪̻͉͗̈́̍̆u̮̝͌̈́ͅn̹̞̈́̊k̮͇̟͎̂͘y̧̲̠̾̆̕ͅ ̙͖̭͔̂̐t̞́́͘e̢̨͕̽x̥͋t͍̑̔͝"; let encoded = "AF685J4FPIJCP5UDJ5NSR5UCHJ6OLJ5IPIPCP5RDPI5CP4UCG76O5J4TCN6O9J4CPM2CP06CKR6A3J4UPII21J4EPIVSR1ECKN69RJ5ACR6PFJC4PI6SP1MCLB6BNJ57PM4NBJCCPM2CPBMCJN6OARMDGJ68LJ5PPIF6NJCOPI1CPBMDGV69VJCEF76BTJ4LPI3CR1ECMB6AFJ5043685J4GPICSR5MCLN6P8T6CG76PHJ41PIF6BJ5TPIHCR5ECL1SCR2UCKLQCP4ECIJ6PRJCD"; let outcome = nu!(format!("'{text}' | encode base32hex --nopad")); assert_eq!(outcome.out, encoded); } #[test] fn decode_string() { let text = "Very important data"; let encoded = "APIN4U90D5MN0RRIEHGMST10CHGN8O8="; let outcome = nu!(format!("'{encoded}' | decode base32hex | decode")); assert_eq!(outcome.out, text); } #[test] fn decode_pad_nopad() { let text = "®lnnE¾ˆë"; let encoded_pad = "OAN6ORJE8N1BTIS6OELG===="; let encoded_nopad = "OAN6ORJE8N1BTIS6OELG"; let outcome = nu!(format!("'{encoded_pad}' | decode base32hex | decode")); assert_eq!(outcome.out, text); let outcome = nu!(format!( "'{encoded_nopad}' | decode base32hex --nopad | decode" )); assert_eq!(outcome.out, text); } #[test] fn reject_pad_nopad() { let encoded_nopad = "D1KG"; let encoded_pad = "D1KG===="; let outcome = nu!(format!("'{encoded_nopad}' | decode base32hex")); assert!(!outcome.err.is_empty()); let outcome = nu!(format!("'{encoded_pad}' | decode base32hex --nopad")); assert!(!outcome.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/base/base64.rs
crates/nu-command/tests/commands/base/base64.rs
use nu_test_support::nu; #[test] fn canonical() { super::test_canonical("base64"); super::test_canonical("base64 --url"); super::test_canonical("base64 --nopad"); super::test_canonical("base64 --url --nopad"); } #[test] fn const_() { super::test_const("base64"); super::test_const("base64 --url"); super::test_const("base64 --nopad"); super::test_const("base64 --url --nopad"); } #[test] fn encode() { let text = "Ș̗͙̂̏o̲̲̗͗̌͊m̝̊̓́͂ë̡̦̞̤́̌̈́̀ ̥̝̪̎̿ͅf̧̪̻͉͗̈́̍̆u̮̝͌̈́ͅn̹̞̈́̊k̮͇̟͎̂͘y̧̲̠̾̆̕ͅ ̙͖̭͔̂̐t̞́́͘e̢̨͕̽x̥͋t͍̑̔͝"; let encoded = "U8yCzI/MpsyXzZlvzZfMjM2KzLLMssyXbcyKzJPMgc2CzJ1lzYTMjM2EzIDMpsyhzJ7MpCDMjsy/zYXMpcydzKpmzZfNhMyNzIbMqsy7zKfNiXXNjM2EzK7Mnc2Fbs2EzIrMucyea82YzILMrs2HzJ/NjnnMvsyVzIbNhcyyzKfMoCDMgsyQzJnNlsytzZR0zIHNmMyBzJ5lzL3Mos2VzKh4zYvMpXTMkcyUzZ3NjQ=="; let outcome = nu!(format!("'{text}' | encode base64")); assert_eq!(outcome.out, encoded); } #[test] fn decode_string() { let text = "Very important data"; let encoded = "VmVyeSBpbXBvcnRhbnQgZGF0YQ=="; let outcome = nu!(format!("'{encoded}' | decode base64 | decode")); assert_eq!(outcome.out, text); } #[test] fn decode_pad_nopad() { let text = "”¥.ä@°bZö¢"; let encoded_pad = "4oCdwqUuw6RAwrBiWsO2wqI="; let encoded_nopad = "4oCdwqUuw6RAwrBiWsO2wqI"; let outcome = nu!(format!("'{encoded_pad}' | decode base64 | decode")); assert_eq!(outcome.out, text); let outcome = nu!(format!( "'{encoded_nopad}' | decode base64 --nopad | decode" )); assert_eq!(outcome.out, text); } #[test] fn decode_url() { let text = "p:gטݾ߫t+?"; let encoded = "cDpn15jdvt+rdCs/"; let encoded_url = "cDpn15jdvt-rdCs_"; let outcome = nu!(format!("'{encoded}' | decode base64 | decode")); assert_eq!(outcome.out, text); let outcome = nu!(format!("'{encoded_url}' | decode base64 --url | decode")); assert_eq!(outcome.out, text); } #[test] fn reject_pad_nopad() { let encoded_nopad = "YQ"; let encoded_pad = "YQ=="; let outcome = nu!(format!("'{encoded_nopad}' | decode base64")); assert!(!outcome.err.is_empty()); let outcome = nu!(format!("'{encoded_pad}' | decode base64 --nopad")); assert!(!outcome.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/base/hex.rs
crates/nu-command/tests/commands/base/hex.rs
use nu_test_support::nu; #[test] fn canonical() { super::test_canonical("hex"); } #[test] fn const_() { super::test_const("hex"); } #[test] fn encode() { let text = "Ș̗͙̂̏o̲̲̗͗̌͊m̝̊̓́͂ë̡̦̞̤́̌̈́̀ ̥̝̪̎̿ͅf̧̪̻͉͗̈́̍̆u̮̝͌̈́ͅn̹̞̈́̊k̮͇̟͎̂͘y̧̲̠̾̆̕ͅ ̙͖̭͔̂̐t̞́́͘e̢̨͕̽x̥͋t͍̑̔͝"; let encoded = "53CC82CC8FCCA6CC97CD996FCD97CC8CCD8ACCB2CCB2CC976DCC8ACC93CC81CD82CC9D65CD84CC8CCD84CC80CCA6CCA1CC9ECCA420CC8ECCBFCD85CCA5CC9DCCAA66CD97CD84CC8DCC86CCAACCBBCCA7CD8975CD8CCD84CCAECC9DCD856ECD84CC8ACCB9CC9E6BCD98CC82CCAECD87CC9FCD8E79CCBECC95CC86CD85CCB2CCA7CCA020CC82CC90CC99CD96CCADCD9474CC81CD98CC81CC9E65CCBDCCA2CD95CCA878CD8BCCA574CC91CC94CD9DCD8D"; let outcome = nu!(format!("'{text}' | encode hex")); assert_eq!(outcome.out, encoded); } #[test] fn decode_string() { let text = "Very important data"; let encoded = "5665727920696D706F7274616E742064617461"; let outcome = nu!(format!("'{encoded}' | decode hex | decode")); assert_eq!(outcome.out, text); } #[test] fn decode_case_mixing() { let text = "®lnnE¾ˆë"; let mixed_encoded = "c2aE6c6e6E45C2BeCB86c3ab"; let outcome = nu!(format!("'{mixed_encoded}' | decode hex | decode")); assert_eq!(outcome.out, 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/base/mod.rs
crates/nu-command/tests/commands/base/mod.rs
use data_encoding::HEXUPPER; use rand::prelude::*; use rand::random_range; use rand_chacha::ChaCha8Rng; use nu_test_support::nu; mod base32; mod base32hex; mod base64; mod hex; /// Generate a few random binaries. fn random_bytes() -> Vec<String> { const NUM: usize = 32; let mut rng = ChaCha8Rng::seed_from_u64(4); (0..NUM) .map(|_| { let length = random_range(0..512); let mut bytes = vec![0u8; length]; rng.fill_bytes(&mut bytes); HEXUPPER.encode(&bytes) }) .collect() } pub fn test_canonical(cmd: &str) { for value in random_bytes() { let outcome = nu!(format!( "0x[{value}] | encode {cmd} | decode {cmd} | to nuon" )); let nuon_value = format!("0x[{value}]"); assert_eq!(outcome.out, nuon_value); } } pub fn test_const(cmd: &str) { for value in random_bytes() { let outcome = nu!(format!( r#"const out = (0x[{value}] | encode {cmd} | decode {cmd} | encode hex); $out"# )); assert_eq!(outcome.out, value); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/base/base32.rs
crates/nu-command/tests/commands/base/base32.rs
use nu_test_support::nu; #[test] fn canonical() { super::test_canonical("base32"); super::test_canonical("base32 --nopad"); } #[test] fn const_() { super::test_const("base32"); super::test_const("base32 --nopad"); } #[test] fn encode() { let text = "Ș̗͙̂̏o̲̲̗͗̌͊m̝̊̓́͂ë̡̦̞̤́̌̈́̀ ̥̝̪̎̿ͅf̧̪̻͉͗̈́̍̆u̮̝͌̈́ͅn̹̞̈́̊k̮͇̟͎̂͘y̧̲̠̾̆̕ͅ ̙͖̭͔̂̐t̞́́͘e̢̨͕̽x̥͋t͍̑̔͝"; let encoded = "KPGIFTEPZSTMZF6NTFX43F6MRTGYVTFSZSZMZF3NZSFMZE6MQHGYFTE5MXGYJTEMZWCMZAGMU3GKDTE6ZSSCBTEOZS743BOMUXGJ3TFKM3GZPTMEZSG4ZBWMVLGLXTFHZWEXLTMMZWCMZLWMTXGYK3WNQTGIVTFZZSPGXTMYZSBMZLWNQ7GJ7TMOPHGL5TEVZSDM3BOMWLGKPTFAEDGIFTEQZSM43FWMVXGZI5GMQHGZRTEBZSPGLTF5ZSRM3FOMVB4M3C6MUV2MZEOMSTGZ3TMN"; let outcome = nu!(format!("'{text}' | encode base32 --nopad")); assert_eq!(outcome.out, encoded); } #[test] fn decode_string() { let text = "Very important data"; let encoded = "KZSXE6JANFWXA33SORQW45BAMRQXIYI="; let outcome = nu!(format!("'{encoded}' | decode base32 | decode")); assert_eq!(outcome.out, text); } #[test] fn decode_pad_nopad() { let text = "®lnnE¾ˆë"; let encoded_pad = "YKXGY3TOIXBL5S4GYOVQ===="; let encoded_nopad = "YKXGY3TOIXBL5S4GYOVQ"; let outcome = nu!(format!("'{encoded_pad}' | decode base32 | decode")); assert_eq!(outcome.out, text); let outcome = nu!(format!( "'{encoded_nopad}' | decode base32 --nopad | decode" )); assert_eq!(outcome.out, text); } #[test] fn reject_pad_nopad() { let encoded_nopad = "ME"; let encoded_pad = "ME======"; let outcome = nu!(format!("'{encoded_nopad}' | decode base32")); assert!(!outcome.err.is_empty()); let outcome = nu!(format!("'{encoded_pad}' | decode base32 --nopad")); assert!(!outcome.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/date/mod.rs
crates/nu-command/tests/commands/date/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/commands/date/format.rs
crates/nu-command/tests/commands/date/format.rs
use nu_test_support::nu; #[test] fn formatter_not_valid() { let actual = nu!(r#" date now | format date '%N' "#); assert!(actual.err.contains("invalid format")); } #[test] fn test_j_q_format_specifiers() { let actual = nu!(r#" "2021-10-22 20:00:12 +01:00" | format date '%J_%Q' "#); assert_eq!(actual.out, "20211022_200012"); } #[test] fn test_j_q_format_specifiers_current_time() { let actual = nu!(r#" date now | format date '%J_%Q' | str length "#); // Should be exactly 15 characters: YYYYMMDD_HHMMSS assert_eq!(actual.out, "15"); } #[test] fn test_j_format_specifier_date_only() { let actual = nu!(r#" "2021-10-22 20:00:12 +01:00" | format date '%J' "#); assert_eq!(actual.out, "20211022"); } #[test] fn test_q_format_specifier_time_only() { let actual = nu!(r#" "2021-10-22 20:00:12 +01:00" | format date '%Q' "#); assert_eq!(actual.out, "200012"); } #[test] fn fails_without_input() { let actual = nu!(r#" format date "%c" "#); assert!(actual.err.contains("Pipeline empty")); } #[test] fn locale_format_respect_different_locale() { let actual = nu!(locale: "en_US", r#" "2021-10-22 20:00:12 +01:00" | format date "%c" "#); assert!(actual.out.contains("Fri 22 Oct 2021 08:00:12 PM +01:00")); let actual = nu!(locale: "en_GB", r#" "2021-10-22 20:00:12 +01:00" | format date "%c" "#); assert!(actual.out.contains("Fri 22 Oct 2021 20:00:12 +01:00")); let actual = nu!(locale: "de_DE", r#" "2021-10-22 20:00:12 +01:00" | format date "%c" "#); assert!(actual.out.contains("Fr 22 Okt 2021 20:00:12 +01:00")); let actual = nu!(locale: "zh_CN", r#" "2021-10-22 20:00:12 +01:00" | format date "%c" "#); assert!(actual.out.contains("2021年10月22日 星期五 20时00分12秒")); let actual = nu!(locale: "ja_JP", r#" "2021-10-22 20:00:12 +01:00" | format date "%c" "#); assert!(actual.out.contains("2021年10月22日 20時00分12秒")); let actual = nu!(locale: "fr_FR", r#" "2021-10-22 20:00:12 +01:00" | format date "%c" "#); assert!(actual.out.contains("ven. 22 oct. 2021 20:00:12 +01:00")); } #[test] fn locale_with_different_format_specifiers() { let actual = nu!(locale: "en_US", r#" "Thu, 26 Oct 2023 22:52:14 +0200" | format date "%x %X" "#); assert!(actual.out.contains("10/26/2023 10:52:14 PM")); let actual = nu!(locale: "nl_NL", r#" "Thu, 26 Oct 2023 22:52:14 +0200" | format date "%x %X" "#); assert!(actual.out.contains("26-10-23 22:52:14")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/abs.rs
crates/nu-command/tests/commands/math/abs.rs
use nu_test_support::nu; #[test] fn const_abs() { let actual = nu!("const ABS = -5.5 | math abs; $ABS"); assert_eq!(actual.out, "5.5"); } #[test] fn can_abs_range_into_list() { let actual = nu!("-1.5..-10.5 | math abs"); let expected = nu!("1.5..10.5"); assert_eq!(actual.out, expected.out); } #[test] fn cannot_abs_infinite_range() { let actual = nu!("0.. | math abs"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/median.rs
crates/nu-command/tests/commands/math/median.rs
use nu_test_support::nu; #[test] fn median_numbers_with_even_rows() { let actual = nu!(r#" echo [10 6 19 21 4] | math median "#); assert_eq!(actual.out, "10") } #[test] fn median_numbers_with_odd_rows() { let actual = nu!(r#" echo [3 8 9 12 12 15] | math median "#); assert_eq!(actual.out, "10.5") } #[test] fn median_mixed_numbers() { let actual = nu!(r#" echo [-11.5 -13.5 10] | math median "#); assert_eq!(actual.out, "-11.5") } #[test] fn const_median() { let actual = nu!("const MEDIAN = [1 3 5] | math median; $MEDIAN"); assert_eq!(actual.out, "3"); } #[test] fn cannot_median_infinite_range() { let actual = nu!("0.. | math median"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/log.rs
crates/nu-command/tests/commands/math/log.rs
use nu_test_support::nu; #[test] fn const_log() { let actual = nu!("const LOG = 16 | math log 2; $LOG"); assert_eq!(actual.out, "4.0"); } #[test] fn can_log_range_into_list() { let actual = nu!("1..5 | math log 2"); let expected = nu!("[1 2 3 4 5] | math log 2"); assert_eq!(actual.out, expected.out); } #[test] fn cannot_log_infinite_range() { let actual = nu!("1.. | math log 2"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/sum.rs
crates/nu-command/tests/commands/math/sum.rs
use nu_test_support::nu; use std::str::FromStr; #[test] fn all() { let sample = r#"{ meals: [ {description: "1 large egg", calories: 90}, {description: "1 cup white rice", calories: 250}, {description: "1 tablespoon fish oil", calories: 108} ] }"#; let actual = nu!(format!( r#" {sample} | get meals | get calories | math sum "# )); assert_eq!(actual.out, "448"); } #[test] #[allow(clippy::unreadable_literal)] #[allow(clippy::float_cmp)] fn compute_sum_of_individual_row() -> Result<(), String> { let answers_for_columns = [ ("cpu", 88.257434), ("mem", 3032375296.), ("virtual", 102579965952.), ]; for (column_name, expected_value) in answers_for_columns { let actual = nu!( cwd: "tests/fixtures/formats/", format!("open sample-ps-output.json | select {column_name} | math sum | get {column_name}") ); let result = f64::from_str(&actual.out).map_err(|_| String::from("Failed to parse float."))?; assert_eq!(result, expected_value); } Ok(()) } #[test] #[allow(clippy::unreadable_literal)] #[allow(clippy::float_cmp)] fn compute_sum_of_table() -> Result<(), String> { let answers_for_columns = [ ("cpu", 88.257434), ("mem", 3032375296.), ("virtual", 102579965952.), ]; for (column_name, expected_value) in answers_for_columns { let actual = nu!( cwd: "tests/fixtures/formats/", format!("open sample-ps-output.json | select cpu mem virtual | math sum | get {column_name}") ); let result = f64::from_str(&actual.out).map_err(|_| String::from("Failed to parse float."))?; assert_eq!(result, expected_value); } Ok(()) } #[test] fn sum_of_a_row_containing_a_table_is_an_error() { let actual = nu!( cwd: "tests/fixtures/formats/", "open sample-sys-output.json | math sum" ); assert!(actual.err.contains("can't convert record")); } #[test] fn const_sum() { let actual = nu!("const SUM = [1 3] | math sum; $SUM"); assert_eq!(actual.out, "4"); } #[test] fn cannot_sum_infinite_range() { let actual = nu!("0.. | math sum"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/product.rs
crates/nu-command/tests/commands/math/product.rs
use nu_test_support::nu; #[test] fn const_product() { let actual = nu!("const PROD = [1 3 5] | math product; $PROD"); assert_eq!(actual.out, "15"); } #[test] fn cannot_product_infinite_range() { let actual = nu!("0.. | math product"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/max.rs
crates/nu-command/tests/commands/math/max.rs
use nu_test_support::nu; #[test] fn const_max() { let actual = nu!("const MAX = [1 3 5] | math max; $MAX"); assert_eq!(actual.out, "5"); } #[test] fn cannot_max_infinite_range() { let actual = nu!("0.. | math max"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/round.rs
crates/nu-command/tests/commands/math/round.rs
use nu_test_support::nu; #[test] fn can_round_very_large_numbers() { let actual = nu!("18.1372544780074142289927665486772012345 | math round"); assert_eq!(actual.out, "18") } #[test] fn can_round_very_large_numbers_with_precision() { let actual = nu!("18.13725447800741422899276654867720121457878988 | math round --precision 10"); assert_eq!(actual.out, "18.137254478") } #[test] fn can_round_integer_with_negative_precision() { let actual = nu!("123 | math round --precision -1"); assert_eq!(actual.out, "120.0") } #[test] fn can_round_float_with_negative_precision() { let actual = nu!("123.3 | math round --precision -1"); assert_eq!(actual.out, "120.0") } #[test] fn fails_with_wrong_input_type() { let actual = nu!("\"not_a_number\" | math round"); assert!(actual.err.contains("command doesn't support")) } #[test] fn const_round() { let actual = nu!("const ROUND = 18.345 | math round; $ROUND"); assert_eq!(actual.out, "18"); } #[test] fn can_round_range_into_list() { let actual = nu!("(1.0)..(1.2)..(2.0) | math round"); let expected = nu!("[1 1 1 2 2 2]"); assert_eq!(actual.out, expected.out); } #[test] fn cannot_round_infinite_range() { let actual = nu!("0.. | math round"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/min.rs
crates/nu-command/tests/commands/math/min.rs
use nu_test_support::nu; #[test] fn const_min() { let actual = nu!("const MIN = [1 3 5] | math min; $MIN"); assert_eq!(actual.out, "1"); } #[test] fn cannot_min_infinite_range() { let actual = nu!("0.. | math min"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/variance.rs
crates/nu-command/tests/commands/math/variance.rs
use nu_test_support::nu; #[test] fn const_variance() { let actual = nu!("const VAR = [1 2 3 4 5] | math variance; $VAR"); assert_eq!(actual.out, "2.0"); } #[test] fn can_variance_range() { let actual = nu!("0..5 | math variance"); let expected = nu!("[0 1 2 3 4 5] | math variance"); assert_eq!(actual.out, expected.out); } #[test] fn cannot_variance_infinite_range() { let actual = nu!("0.. | math variance"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/mod.rs
crates/nu-command/tests/commands/math/mod.rs
mod abs; mod avg; mod ceil; mod floor; mod log; mod max; mod median; mod min; mod mode; mod product; mod round; mod sqrt; mod stddev; mod sum; mod variance; use nu_test_support::nu; #[test] fn one_arg() { let actual = nu!(r#" 1 "#); assert_eq!(actual.out, "1"); } #[test] fn add() { let actual = nu!(r#" 1 + 1 "#); assert_eq!(actual.out, "2"); } #[test] fn add_compound() { let actual = nu!(r#" 1 + 2 + 2 "#); assert_eq!(actual.out, "5"); } #[test] fn precedence_of_operators() { let actual = nu!(r#" 1 + 2 * 2 "#); assert_eq!(actual.out, "5"); } #[test] fn precedence_of_operators2() { let actual = nu!(r#" 1 + 2 * 2 + 1 "#); assert_eq!(actual.out, "6"); } #[test] fn precedence_of_operators3() { let actual = nu!(r#" 5 - 5 * 10 + 5 "#); assert_eq!(actual.out, "-40"); } #[test] fn precedence_of_operators4() { let actual = nu!(r#" 5 - (5 * 10) + 5 "#); assert_eq!(actual.out, "-40"); } #[test] fn division_of_ints() { let actual = nu!(r#" 4 / 2 "#); assert_eq!(actual.out, "2.0"); } #[test] fn division_of_ints2() { let actual = nu!(r#" 1 / 4 "#); assert_eq!(actual.out, "0.25"); } #[test] fn error_zero_division_int_int() { let actual = nu!(r#" 1 / 0 "#); assert!(actual.err.contains("division by zero")); } #[test] fn error_zero_division_float_int() { let actual = nu!(r#" 1.0 / 0 "#); assert!(actual.err.contains("division by zero")); } #[test] fn error_zero_division_int_float() { let actual = nu!(r#" 1 / 0.0 "#); assert!(actual.err.contains("division by zero")); } #[test] fn error_zero_division_float_float() { let actual = nu!(r#" 1.0 / 0.0 "#); assert!(actual.err.contains("division by zero")); } #[test] fn floor_division_of_ints() { let actual = nu!(r#" 5 // 2 "#); assert_eq!(actual.out, "2"); } #[test] fn floor_division_of_ints2() { let actual = nu!(r#" -3 // 2 "#); assert_eq!(actual.out, "-2"); } #[test] fn floor_division_of_floats() { let actual = nu!(r#" -3.0 // 2.0 "#); assert_eq!(actual.out, "-2.0"); } #[test] fn error_zero_floor_division_int_int() { let actual = nu!(r#" 1 // 0 "#); assert!(actual.err.contains("division by zero")); } #[test] fn error_zero_floor_division_float_int() { let actual = nu!(r#" 1.0 // 0 "#); assert!(actual.err.contains("division by zero")); } #[test] fn error_zero_floor_division_int_float() { let actual = nu!(r#" 1 // 0.0 "#); assert!(actual.err.contains("division by zero")); } #[test] fn error_zero_floor_division_float_float() { let actual = nu!(r#" 1.0 // 0.0 "#); assert!(actual.err.contains("division by zero")); } #[test] fn proper_precedence_history() { let actual = nu!(r#" 2 / 2 / 2 + 1 "#); assert_eq!(actual.out, "1.5"); } #[test] fn parens_precedence() { let actual = nu!(r#" 4 * (6 - 3) "#); assert_eq!(actual.out, "12"); } #[test] fn modulo() { let actual = nu!(r#" 9 mod 2 "#); assert_eq!(actual.out, "1"); } #[test] fn floor_div_mod() { let actual = nu!("let q = 8 // -3; let r = 8 mod -3; 8 == $q * -3 + $r"); assert_eq!(actual.out, "true"); let actual = nu!("let q = -8 // 3; let r = -8 mod 3; -8 == $q * 3 + $r"); assert_eq!(actual.out, "true"); } #[test] fn floor_div_mod_overflow() { let actual = nu!(format!("{} // -1", i64::MIN)); assert!(actual.err.contains("overflow")); let actual = nu!(format!("{} mod -1", i64::MIN)); assert!(actual.err.contains("overflow")); } #[test] fn floor_div_mod_zero() { let actual = nu!("1 // 0"); assert!(actual.err.contains("zero")); let actual = nu!("1 mod 0"); assert!(actual.err.contains("zero")); } #[test] fn floor_div_mod_large_num() { let actual = nu!(format!("{} // {}", i64::MAX, i64::MAX / 2)); assert_eq!(actual.out, "2"); let actual = nu!(format!("{} mod {}", i64::MAX, i64::MAX / 2)); assert_eq!(actual.out, "1"); } #[test] fn unit_multiplication_math() { let actual = nu!("1MB * 2"); assert_eq!(actual.out, "2.0 MB"); } #[test] fn unit_multiplication_float_math() { let actual = nu!("1MB * 1.2"); assert_eq!(actual.out, "1.2 MB"); } #[test] fn unit_float_floor_division_math() { let actual = nu!("1MB // 3.0"); assert_eq!(actual.out, "333.3 kB"); } #[test] fn unit_division_math() { let actual = nu!("1MB / 4"); assert_eq!(actual.out, "250.0 kB"); } #[test] fn unit_float_division_math() { let actual = nu!("1MB / 3.2"); assert_eq!(actual.out, "312.5 kB"); } #[test] fn duration_math() { let actual = nu!(r#" 1wk + 1day "#); assert_eq!(actual.out, "1wk 1day"); } #[test] fn duration_decimal_math() { let actual = nu!(r#" 5.5day + 0.5day "#); assert_eq!(actual.out, "6day"); } #[test] fn duration_math_with_nanoseconds() { let actual = nu!(r#" 1wk + 10ns "#); assert_eq!(actual.out, "1wk 10ns"); } #[test] fn duration_decimal_math_with_nanoseconds() { let actual = nu!(r#" 1.5wk + 10ns "#); assert_eq!(actual.out, "1wk 3day 12hr 10ns"); } #[test] fn duration_decimal_math_with_all_units() { let actual = nu!(r#" 1wk + 3day + 8hr + 10min + 16sec + 121ms + 11us + 12ns "#); assert_eq!(actual.out, "1wk 3day 8hr 10min 16sec 121ms 11µs 12ns"); } #[test] fn duration_decimal_dans_test() { let actual = nu!(r#" 3.14sec "#); assert_eq!(actual.out, "3sec 140ms"); } #[test] fn duration_math_with_negative() { let actual = nu!(r#" 1day - 1wk "#); assert_eq!(actual.out, "-6day"); } #[test] fn compound_comparison() { let actual = nu!(r#" 4 > 3 and 2 > 1 "#); assert_eq!(actual.out, "true"); } #[test] fn compound_comparison2() { let actual = nu!(r#" 4 < 3 or 2 > 1 "#); assert_eq!(actual.out, "true"); } #[test] fn compound_where() { let actual = nu!(r#" echo '[{"a": 1, "b": 1}, {"a": 2, "b": 1}, {"a": 2, "b": 2}]' | from json | where a == 2 and b == 1 | to json -r "#); assert_eq!(actual.out, r#"[{"a":2,"b":1}]"#); } #[test] fn compound_where_paren() { let actual = nu!(r#" echo '[{"a": 1, "b": 1}, {"a": 2, "b": 1}, {"a": 2, "b": 2}]' | from json | where ($it.a == 2 and $it.b == 1) or $it.b == 2 | to json -r "#); assert_eq!(actual.out, r#"[{"a":2,"b":1},{"a":2,"b":2}]"#); } // TODO: these ++ tests are not really testing *math* functionality, maybe find another place for them #[test] fn concat_lists() { let actual = nu!(r#" [1 3] ++ [5 6] | to nuon "#); assert_eq!(actual.out, "[1, 3, 5, 6]"); } #[test] fn concat_tables() { let actual = nu!(r#" [[a b]; [1 2]] ++ [[c d]; [10 11]] | to nuon "#); assert_eq!(actual.out, "[{a: 1, b: 2}, {c: 10, d: 11}]"); } #[test] fn concat_strings() { let actual = nu!(r#" "foo" ++ "bar" "#); assert_eq!(actual.out, "foobar"); } #[test] fn concat_binary_values() { let actual = nu!(r#" 0x[01 02] ++ 0x[03 04] | to nuon "#); assert_eq!(actual.out, "0x[01020304]"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/sqrt.rs
crates/nu-command/tests/commands/math/sqrt.rs
use nu_test_support::nu; #[test] fn can_sqrt_numbers() { let actual = nu!("echo [0.25 2 4] | math sqrt | math sum"); assert_eq!(actual.out, "3.914213562373095"); } #[test] fn can_sqrt_irrational() { let actual = nu!("echo 2 | math sqrt"); assert_eq!(actual.out, "1.4142135623730951"); } #[test] fn can_sqrt_perfect_square() { let actual = nu!("echo 4 | math sqrt"); assert_eq!(actual.out, "2.0"); } #[test] fn const_sqrt() { let actual = nu!("const SQRT = 4 | math sqrt; $SQRT"); assert_eq!(actual.out, "2.0"); } #[test] fn can_sqrt_range() { let actual = nu!("0..5 | math sqrt"); let expected = nu!("[0 1 2 3 4 5] | math sqrt"); assert_eq!(actual.out, expected.out); } #[test] fn cannot_sqrt_infinite_range() { let actual = nu!("0.. | math sqrt"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/ceil.rs
crates/nu-command/tests/commands/math/ceil.rs
use nu_test_support::nu; #[test] fn const_ceil() { let actual = nu!("const CEIL = 1.5 | math ceil; $CEIL"); assert_eq!(actual.out, "2"); } #[test] fn can_ceil_range_into_list() { let actual = nu!("(1.8)..(3.8) | math ceil"); let expected = nu!("[2 3 4]"); assert_eq!(actual.out, expected.out); } #[test] fn cannot_ceil_infinite_range() { let actual = nu!("0.. | math ceil"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/avg.rs
crates/nu-command/tests/commands/math/avg.rs
use nu_test_support::nu; #[test] fn can_average_numbers() { let actual = nu!(cwd: "tests/fixtures/formats", r#" open sgml_description.json | get glossary.GlossDiv.GlossList.GlossEntry.Sections | math avg "#); assert_eq!(actual.out, "101.5") } #[test] fn can_average_bytes() { let actual = nu!("[100kb, 10b, 100mib] | math avg | to json -r"); assert_eq!(actual.out, "34985870"); } #[test] fn can_average_range() { let actual = nu!("0..5 | math avg"); assert_eq!(actual.out, "2.5"); } #[test] fn cannot_average_infinite_range() { let actual = nu!("0.. | math avg"); assert!(actual.err.contains("nu::shell::incorrect_value")); } #[test] fn const_avg() { let actual = nu!("const AVG = [1 3 5] | math avg; $AVG"); assert_eq!(actual.out, "3.0"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/mode.rs
crates/nu-command/tests/commands/math/mode.rs
use nu_test_support::nu; #[test] fn const_avg() { let actual = nu!("const MODE = [1 3 3 5] | math mode; $MODE"); assert_eq!(actual.out, "╭───┬───╮│ 0 │ 3 │╰───┴───╯"); } #[test] fn cannot_mode_range() { let actual = nu!("0..5 | math mode"); assert!(actual.err.contains("nu::parser::input_type_mismatch")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/floor.rs
crates/nu-command/tests/commands/math/floor.rs
use nu_test_support::nu; #[test] fn const_floor() { let actual = nu!("const FLOOR = 15.5 | math floor; $FLOOR"); assert_eq!(actual.out, "15"); } #[test] fn can_floor_range_into_list() { let actual = nu!("(1.8)..(3.8) | math floor"); let expected = nu!("[1 2 3]"); assert_eq!(actual.out, expected.out); } #[test] fn cannot_floor_infinite_range() { let actual = nu!("0.. | math floor"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/math/stddev.rs
crates/nu-command/tests/commands/math/stddev.rs
use nu_test_support::nu; #[test] fn const_avg() { let actual = nu!("const SDEV = [1 2] | math stddev; $SDEV"); assert_eq!(actual.out, "0.5"); } #[test] fn can_stddev_range() { let actual = nu!("0..5 | math stddev"); let expected = nu!("[0 1 2 3 4 5] | math stddev"); assert_eq!(actual.out, expected.out); } #[test] fn cannot_stddev_infinite_range() { let actual = nu!("0.. | math stddev"); assert!(actual.err.contains("nu::shell::incorrect_value")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/skip/skip_.rs
crates/nu-command/tests/commands/skip/skip_.rs
use nu_test_support::nu; #[test] fn skips_bytes() { let actual = nu!("(0x[aa bb cc] | skip 2) == 0x[cc]"); assert_eq!(actual.out, "true"); } #[test] fn skips_bytes_from_stream() { let actual = nu!("([0 1] | each { 0x[aa bb cc] } | bytes collect | skip 2) == 0x[cc aa bb cc]"); assert_eq!(actual.out, "true"); } #[test] fn fail_on_non_iterator() { let actual = nu!("1 | skip 2"); assert!(actual.err.contains("command doesn't support")); } #[test] fn skips_bytes_and_drops_content_type() { let actual = nu!(format!( "open {} | skip 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/skip/until.rs
crates/nu-command/tests/commands/skip/until.rs
use nu_test_support::nu; #[test] fn condition_is_met() { let sample = r#"[ ["Chicken Collection", "29/04/2020", "30/04/2020", "31/04/2020"]; ["Yellow Chickens", "", "", ""], [Andrés, 0, 0, 1], [JT, 0, 0, 1], [Jason, 0, 0, 1], [Yehuda, 0, 0, 1], ["Blue Chickens", "", "", ""], [Andrés, 0, 0, 2], [JT, 0, 0, 2], [Jason, 0, 0, 2], [Yehuda, 0, 0, 2], ["Red Chickens", "", "", ""], [Andrés, 0, 0, 1], [JT, 0, 0, 1], [Jason, 0, 0, 1], [Yehuda, 0, 0, 3] ]"#; let actual = nu!(format!( r#" {sample} | skip until {{|row| $row."Chicken Collection" == "Red Chickens" }} | skip 1 | into int "31/04/2020" | get "31/04/2020" | math sum "# )); assert_eq!(actual.out, "6"); } #[test] fn fail_on_non_iterator() { let actual = nu!("1 | skip until {|row| $row == 2}"); 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/skip/while_.rs
crates/nu-command/tests/commands/skip/while_.rs
use nu_test_support::nu; #[test] fn condition_is_met() { let sample = r#"[ ["Chicken Collection", "29/04/2020", "30/04/2020", "31/04/2020"]; ["Yellow Chickens", "", "", ""], [Andrés, 0, 0, 1], [JT, 0, 0, 1], [Jason, 0, 0, 1], [Yehuda, 0, 0, 1], ["Blue Chickens", "", "", ""], [Andrés, 0, 0, 2], [JT, 0, 0, 2], [Jason, 0, 0, 2], [Yehuda, 0, 0, 2], ["Red Chickens", "", "", ""], [Andrés, 0, 0, 1], [JT, 0, 0, 1], [Jason, 0, 0, 1], [Yehuda, 0, 0, 3] ]"#; let actual = nu!(format!( r#" {sample} | skip while {{|row| $row."Chicken Collection" != "Red Chickens" }} | skip 1 | into int "31/04/2020" | get "31/04/2020" | math sum "# )); assert_eq!(actual.out, "6"); } #[test] fn fail_on_non_iterator() { let actual = nu!("1 | skip while {|row| $row == 2}"); 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/skip/mod.rs
crates/nu-command/tests/commands/skip/mod.rs
mod skip_; mod until; mod while_;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/conversions/mod.rs
crates/nu-command/tests/commands/conversions/mod.rs
mod into;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/conversions/into/record.rs
crates/nu-command/tests/commands/conversions/into/record.rs
use nu_test_support::nu; #[test] fn doesnt_accept_mixed_type_list_as_input() { let actual = nu!("[{foo: bar} [quux baz]] | into record"); assert!(!actual.status.success()); assert!(actual.err.contains("type_mismatch")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/conversions/into/mod.rs
crates/nu-command/tests/commands/conversions/into/mod.rs
mod binary; mod int; mod record;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/conversions/into/binary.rs
crates/nu-command/tests/commands/conversions/into/binary.rs
use nu_test_support::nu; #[test] fn sets_stream_from_internal_command_as_binary() { let result = nu!("seq 1 10 | to text | into binary | describe"); assert_eq!("binary (stream)", result.out); } #[test] fn sets_stream_from_external_command_as_binary() { let result = nu!("^nu --testbin cococo | into binary | describe"); assert_eq!("binary (stream)", 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/conversions/into/int.rs
crates/nu-command/tests/commands/conversions/into/int.rs
use nu_test_support::nu; #[test] fn convert_back_and_forth() { let actual = nu!(r#"1 | into binary | into int"#); assert_eq!(actual.out, "1"); } #[test] fn convert_into_int_little_endian() { let actual = nu!(r#"0x[01 00 00 00 00 00 00 00] | into int --endian little"#); assert_eq!(actual.out, "1"); let actual = nu!(r#"0x[00 00 00 00 00 00 00 01] | into int --endian little"#); assert_eq!(actual.out, "72057594037927936"); } #[test] fn convert_into_int_big_endian() { let actual = nu!(r#"0x[00 00 00 00 00 00 00 01] | into int --endian big"#); assert_eq!(actual.out, "1"); let actual = nu!(r#"0x[01 00 00 00 00 00 00 00] | into int --endian big"#); assert_eq!(actual.out, "72057594037927936"); } #[test] fn convert_into_signed_int_little_endian() { let actual = nu!(r#"0x[ff 00 00 00 00 00 00 00] | into int --endian little --signed"#); assert_eq!(actual.out, "255"); let actual = nu!(r#"0x[00 00 00 00 00 00 00 ff] | into int --endian little --signed"#); assert_eq!(actual.out, "-72057594037927936"); } #[test] fn convert_into_signed_int_big_endian() { let actual = nu!(r#"0x[00 00 00 00 00 00 00 ff] | into int --endian big"#); assert_eq!(actual.out, "255"); let actual = nu!(r#"0x[ff 00 00 00 00 00 00 00] | into int --endian big"#); assert_eq!(actual.out, "-72057594037927936"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/hash_/mod.rs
crates/nu-command/tests/commands/hash_/mod.rs
use nu_test_support::nu; #[test] fn base64_defaults_to_encoding_with_standard_character_type() { let actual = nu!(r#" echo 'username:password' | encode base64 "#); assert_eq!(actual.out, "dXNlcm5hbWU6cGFzc3dvcmQ="); } #[test] fn base64_defaults_to_encoding_with_nopad() { let actual = nu!(r#" echo 'username:password' | encode base64 --nopad "#); assert_eq!(actual.out, "dXNlcm5hbWU6cGFzc3dvcmQ"); } #[test] fn base64_decode_value() { let actual = nu!(r#" echo 'YWJjeHl6' | decode base64 | decode "#); assert_eq!(actual.out, "abcxyz"); } #[test] fn base64_decode_with_nopad() { let actual = nu!(r#" echo 'R29vZCBsdWNrIHRvIHlvdQ' | decode base64 --nopad | decode "#); assert_eq!(actual.out, "Good luck to you"); } #[test] fn base64_decode_with_url() { let actual = nu!(r#" echo 'vu7_' | decode base64 --url | decode "#); assert_eq!(actual.out, "¾îÿ"); } #[test] fn error_invalid_decode_value() { let actual = nu!(r#" echo "this should not be a valid encoded value" | decode base64 "#); assert!(actual.err.contains("nu::shell::incorrect_value")); } #[test] fn md5_works_with_file() { let actual = nu!(cwd: "tests/fixtures/formats", r#" open sample.db --raw | hash md5 "#); assert_eq!(actual.out, "4de97601d232c427977ef11db396c951"); } #[test] fn sha256_works_with_file() { let actual = nu!(cwd: "tests/fixtures/formats", r#" open sample.db --raw | hash sha256 "#); assert_eq!( actual.out, "2f5050e7eea415c1f3d80b5d93355efd15043ec9157a2bb167a9e73f2ae651f2" ); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/url/parse.rs
crates/nu-command/tests/commands/url/parse.rs
use nu_test_support::nu; #[test] fn url_parse_simple() { let actual = nu!(r#" ( "https://www.abc.com" | url parse ) == { scheme: 'https', username: '', password: '', host: 'www.abc.com', port: '', path: '/', query: '', fragment: '', params: [] } "#); assert_eq!(actual.out, "true"); } #[test] fn url_parse_with_port() { let actual = nu!(r#" ( "https://www.abc.com:8011" | url parse ) == { scheme: 'https', username: '', password: '', host: 'www.abc.com', port: '8011', path: '/', query: '', fragment: '', params: [] } "#); assert_eq!(actual.out, "true"); } #[test] fn url_parse_with_path() { let actual = nu!(r#" ( "http://www.abc.com:8811/def/ghj" | url parse ) == { scheme: 'http', username: '', password: '', host: 'www.abc.com', port: '8811', path: '/def/ghj', query: '', fragment: '', params: [] } "#); assert_eq!(actual.out, "true"); } #[test] fn url_parse_with_params() { let actual = nu!(r#" ( "http://www.abc.com:8811/def/ghj?param1=11&param2=" | url parse ) == { scheme: 'http', username: '', password: '', host: 'www.abc.com', port: '8811', path: '/def/ghj', query: 'param1=11&param2=', fragment: '', params: [[key, value]; ["param1", "11"], ["param2", ""]] } "#); assert_eq!(actual.out, "true"); } #[test] fn url_parse_with_duplicate_params() { let actual = nu!(r#" ( "http://www.abc.com:8811/def/ghj?param1=11&param2=&param1=22" | url parse ) == { scheme: 'http', username: '', password: '', host: 'www.abc.com', port: '8811', path: '/def/ghj', query: 'param1=11&param2=&param1=22', fragment: '', params: [[key, value]; ["param1", "11"], ["param2", ""], ["param1", "22"]] } "#); assert_eq!(actual.out, "true"); } #[test] fn url_parse_with_fragment() { let actual = nu!(r#" ( "http://www.abc.com:8811/def/ghj?param1=11&param2=#hello-fragment" | url parse ) == { scheme: 'http', username: '', password: '', host: 'www.abc.com', port: '8811', path: '/def/ghj', query: 'param1=11&param2=', fragment: 'hello-fragment', params: [[key, value]; ["param1", "11"], ["param2", ""]] } "#); assert_eq!(actual.out, "true"); } #[test] fn url_parse_with_username_and_password() { let actual = nu!(r#" ( "http://user123:password567@www.abc.com:8811/def/ghj?param1=11&param2=#hello-fragment" | url parse ) == { scheme: 'http', username: 'user123', password: 'password567', host: 'www.abc.com', port: '8811', path: '/def/ghj', query: 'param1=11&param2=', fragment: 'hello-fragment', params: [[key, value]; ["param1", "11"], ["param2", ""]] } "#); assert_eq!(actual.out, "true"); } #[test] fn url_parse_error_empty_url() { let actual = nu!(r#""" | url parse"#); assert!(actual.err.contains( "Incomplete or incorrect URL. Expected a full URL, e.g., https://www.example.com" )); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/url/decode.rs
crates/nu-command/tests/commands/url/decode.rs
use nu_test_support::nu; #[test] fn url_decode_simple() { let actual = nu!(r#"'a%20b' | url decode"#); assert_eq!(actual.out, "a b"); } #[test] fn url_decode_special_characters() { let actual = nu!(r#"'%21%40%23%24%25%C2%A8%26%2A%2D%2B%3B%2C%7B%7D%5B%5D%28%29' | url decode"#); assert_eq!(actual.out, r#"!@#$%¨&*-+;,{}[]()"#); } #[test] fn url_decode_error_invalid_utf8() { let actual = nu!(r#"'%99' | url decode"#); assert!(actual.err.contains("invalid utf-8 sequence")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/url/mod.rs
crates/nu-command/tests/commands/url/mod.rs
mod decode; mod join; mod parse;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/url/join.rs
crates/nu-command/tests/commands/url/join.rs
use nu_test_support::nu; #[test] fn url_join_simple() { let actual = nu!(r#" { "scheme": "http", "username": "", "password": "", "host": "localhost", "port": "", } | url join "#); assert_eq!(actual.out, "http://localhost"); } #[test] fn url_join_with_only_user() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "", "host": "localhost", "port": "", } | url join "#); assert_eq!(actual.out, "http://usr@localhost"); } #[test] fn url_join_with_only_pwd() { let actual = nu!(r#" { "scheme": "http", "username": "", "password": "pwd", "host": "localhost", "port": "", } | url join "#); assert_eq!(actual.out, "http://localhost"); } #[test] fn url_join_with_user_and_pwd() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "port": "", } | url join "#); assert_eq!(actual.out, "http://usr:pwd@localhost"); } #[test] fn url_join_with_query() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "query": "par_1=aaa&par_2=bbb" "port": "", } | url join "#); assert_eq!(actual.out, "http://usr:pwd@localhost?par_1=aaa&par_2=bbb"); } #[test] fn url_join_with_params() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "params": { "par_1": "aaa", "par_2": "bbb" }, "port": "1234", } | url join "#); assert_eq!( actual.out, "http://usr:pwd@localhost:1234?par_1=aaa&par_2=bbb" ); } #[test] fn url_join_with_same_query_and_params() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "query": "par_1=aaa&par_2=bbb", "params": { "par_1": "aaa", "par_2": "bbb" }, "port": "1234", } | url join "#); assert_eq!( actual.out, "http://usr:pwd@localhost:1234?par_1=aaa&par_2=bbb" ); } #[test] fn url_join_with_different_query_and_params() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "query": "par_1=aaa&par_2=bbb", "params": { "par_1": "aaab", "par_2": "bbb" }, "port": "1234", } | url join "#); assert!( actual .err .contains("Mismatch, query string from params is: ?par_1=aaab&par_2=bbb") ); assert!( actual .err .contains("instead query is: ?par_1=aaa&par_2=bbb") ); let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "params": { "par_1": "aaab", "par_2": "bbb" }, "query": "par_1=aaa&par_2=bbb", "port": "1234", } | url join "#); assert!( actual .err .contains("Mismatch, query param is: par_1=aaa&par_2=bbb") ); assert!( actual .err .contains("instead query string from params is: ?par_1=aaab&par_2=bbb") ); } #[test] fn url_join_with_invalid_params() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "params": "aaa", "port": "1234", } | url join "#); assert!( actual .err .contains("Key params has to be a record or a table") ); } #[test] fn url_join_with_port() { let actual = nu!(r#" { "scheme": "http", "host": "localhost", "port": "1234", } | url join "#); assert_eq!(actual.out, "http://localhost:1234"); let actual = nu!(r#" { "scheme": "http", "host": "localhost", "port": 1234, } | url join "#); assert_eq!(actual.out, "http://localhost:1234"); } #[test] fn url_join_with_invalid_port() { let actual = nu!(r#" { "scheme": "http", "host": "localhost", "port": "aaaa", } | url join "#); assert!( actual .err .contains("Port parameter should represent an unsigned int") ); let actual = nu!(r#" { "scheme": "http", "host": "localhost", "port": [], } | url join "#); assert!( actual .err .contains("Port parameter should be an unsigned int or a string representing it") ); } #[test] fn url_join_with_missing_scheme() { let actual = nu!(r#" { "host": "localhost" } | url join "#); assert!(actual.err.contains("missing parameter: scheme")); } #[test] fn url_join_with_missing_host() { let actual = nu!(r#" { "scheme": "https" } | url join "#); assert!(actual.err.contains("missing parameter: host")); } #[test] fn url_join_with_fragment() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "fragment": "frag", "port": "1234", } | url join "#); assert_eq!(actual.out, "http://usr:pwd@localhost:1234#frag"); } #[test] fn url_join_with_fragment_and_params() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "params": { "par_1": "aaa", "par_2": "bbb" }, "port": "1234", "fragment": "frag" } | url join "#); assert_eq!( actual.out, "http://usr:pwd@localhost:1234?par_1=aaa&par_2=bbb#frag" ); } #[test] fn url_join_with_empty_params() { let actual = nu!(r#" { "scheme": "https", "host": "localhost", "path": "/foo", "params": {} } | url join "#); assert_eq!(actual.out, "https://localhost/foo"); } #[test] fn url_join_with_list_in_params() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "params": { "par_1": "aaa", "par_2": ["bbb", "ccc"] }, "port": "1234", } | url join "#); assert_eq!( actual.out, "http://usr:pwd@localhost:1234?par_1=aaa&par_2=bbb&par_2=ccc" ); } #[test] fn url_join_with_params_table() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "params": [ ["key", "value"]; ["par_1", "aaa"], ["par_2", "bbb"], ["par_1", "ccc"], ["par_2", "ddd"], ], "port": "1234", } | url join "#); assert_eq!( actual.out, "http://usr:pwd@localhost:1234?par_1=aaa&par_2=bbb&par_1=ccc&par_2=ddd" ); } #[test] fn url_join_with_params_invalid_table() { let actual = nu!(r#" { "scheme": "http", "username": "usr", "password": "pwd", "host": "localhost", "params": ( [ { key: foo, value: bar } "not a record" ] ), "port": "1234", } | url join "#); assert!(actual.err.contains("expected a table")); assert!( actual .err .contains("not a table, contains non-record values") ); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/assignment/concat.rs
crates/nu-command/tests/commands/assignment/concat.rs
use nu_test_support::nu; #[test] fn concat_assign_list_int() { let actual = nu!(r#" mut a = [1 2]; $a ++= [3 4]; $a == [1 2 3 4] "#); assert_eq!(actual.out, "true") } #[test] fn concat_assign_list_string() { let actual = nu!(r#" mut a = [a b]; $a ++= [c d]; $a == [a b c d] "#); assert_eq!(actual.out, "true") } #[test] fn concat_assign_any() { let actual = nu!(r#" mut a = [1 2 a]; $a ++= [b 3]; $a == [1 2 a b 3] "#); assert_eq!(actual.out, "true") } #[test] fn concat_assign_both_empty() { let actual = nu!(r#" mut a = []; $a ++= []; $a == [] "#); assert_eq!(actual.out, "true") } #[test] fn concat_assign_string() { let actual = nu!(r#" mut a = 'hello'; $a ++= ' world'; $a == 'hello world' "#); assert_eq!(actual.out, "true") } #[test] fn concat_assign_type_mismatch() { let actual = nu!(r#" mut a = []; $a ++= 'str' "#); assert!( actual .err .contains("nu::parser::operator_incompatible_types") ); } #[test] fn concat_assign_runtime_type_mismatch() { let actual = nu!(r#" mut a = []; $a ++= if true { 'str' } "#); assert!( actual .err .contains("nu::shell::operator_incompatible_types") ); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/assignment/mod.rs
crates/nu-command/tests/commands/assignment/mod.rs
mod concat;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/bytes/collect.rs
crates/nu-command/tests/commands/bytes/collect.rs
use nu_test_support::nu; #[test] fn test_stream() { let actual = nu!(" [0x[01] 0x[02] 0x[03] 0x[04]] | filter {true} | bytes collect 0x[aa aa] | encode hex "); assert_eq!(actual.out, "01AAAA02AAAA03AAAA04"); } #[test] fn test_stream_type() { let actual = nu!(" [0x[01] 0x[02] 0x[03] 0x[04]] | filter {true} | bytes collect 0x[00] | describe -n "); assert_eq!(actual.out, "binary (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/bytes/mod.rs
crates/nu-command/tests/commands/bytes/mod.rs
mod at; mod collect; mod length;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/bytes/at.rs
crates/nu-command/tests/commands/bytes/at.rs
use nu_test_support::nu; #[test] pub fn returns_error_for_relative_range_on_infinite_stream() { let actual = nu!("nu --testbin iecho 3 | bytes at ..-3"); assert!( actual.err.contains( "Relative range values cannot be used with streams that don't have a known length" ), "Expected error message for negative range with infinite stream" ); } #[test] pub fn returns_bytes_for_fixed_range_on_infinite_stream_including_end() { let actual = nu!("nu --testbin iecho 3 | bytes at ..10 | decode"); assert_eq!( actual.out, "333333", "Expected bytes from index 0 to 10, but got different output" ); let actual = nu!("nu --testbin iecho 3 | bytes at ..10 | decode"); assert_eq!( actual.out, "333333", "Expected bytes from index 0 to 10, but got different output" ); } #[test] pub fn returns_bytes_for_fixed_range_on_infinite_stream_excluding_end() { let actual = nu!("nu --testbin iecho 3 | bytes at ..<9 | decode"); assert_eq!( actual.out, "33333", "Expected bytes from index 0 to 8, but got different output" ); } #[test] pub fn test_string_returns_correct_slice_for_simple_positive_slice() { let actual = nu!("\"Hello World\" | encode utf8 | bytes at ..4 | decode"); assert_eq!(actual.out, "Hello"); } #[test] pub fn test_string_returns_correct_slice_for_negative_start() { let actual = nu!("\"Hello World\" | encode utf8 | bytes at (-5)..10 | decode"); assert_eq!(actual.out, "World"); } #[test] pub fn test_string_returns_correct_slice_for_negative_end() { let actual = nu!("\"Hello World\" | encode utf8 | bytes at ..-7 | decode"); assert_eq!(actual.out, "Hello"); } #[test] pub fn test_string_returns_correct_slice_for_empty_slice() { let actual = nu!("\"Hello World\" | encode utf8 | bytes at 5..<5 | decode"); assert_eq!(actual.out, ""); } #[test] pub fn test_string_returns_correct_slice_for_out_of_bounds() { let actual = nu!("\"Hello World\" | encode utf8 | bytes at ..20 | decode"); assert_eq!(actual.out, "Hello World"); } #[test] pub fn test_string_returns_correct_slice_for_invalid_range() { let actual = nu!("\"Hello World\" | encode utf8 | bytes at 11..5 | decode"); assert_eq!(actual.out, ""); } #[test] pub fn test_string_returns_correct_slice_for_max_end() { let actual = nu!("\"Hello World\" | encode utf8 | bytes at 6..<11 | decode"); assert_eq!(actual.out, "World"); } #[test] pub fn test_drops_content_type() { let actual = nu!(format!( "open {} | bytes at 3..5 | metadata | get content_type? | describe", file!(), )); assert_eq!(actual.out, "nothing", "Expected content_type to be dropped"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/bytes/length.rs
crates/nu-command/tests/commands/bytes/length.rs
use nu_test_support::nu; #[test] pub fn test_basic_non_const_success() { let actual = nu!("let a = 0x[00 00 00]; $a | bytes length"); assert_eq!( actual.out, "3", "Expected the length of 0x[00 00 00] to be 3 at non-const time, but got something else" ); } #[test] pub fn test_basic_const_success() { let actual = nu!("const a = 0x[00 00 00] | bytes length; $a"); assert_eq!( actual.out, "3", "Expected the length of 0x[00 00 00] to be 3 at const time, but got something else" ); } #[test] pub fn test_array_non_const_success() { let actual = nu!("let a = [0x[00 00 00] 0x[00]]; $a | bytes length | to nuon --raw"); assert_eq!( actual.out, "[3,1]", "Expected the length of [0x[00 00 00], 0x[00]] to be [3, 1] at non-const time, but got something else" ); } #[test] pub fn test_array_const_success() { let actual = nu!("const a = [0x[00 00 00] 0x[00]] | bytes length; $a | to nuon --raw"); assert_eq!( actual.out, "[3,1]", "Expected the length of [0x[00 00 00], 0x[00]] to be [3, 1] at const time, but got something else" ); } #[test] pub fn test_table_non_const_success() { let actual = nu!("let a = [[a]; [0x[00]] [0x[]] [0x[11 ff]]]; $a | bytes length a | to json --raw"); assert_eq!( actual.out, r#"[{"a":1},{"a":0},{"a":2}]"#, "Failed to update table cell-paths with bytes length at non-const time" ); } #[test] pub fn test_table_const_success() { let actual = nu!("const a = [[a]; [0x[00]] [0x[]] [0x[11 ff]]] | bytes length a; $a | to json --raw"); assert_eq!( actual.out, r#"[{"a":1},{"a":0},{"a":2}]"#, "Failed to update table cell-paths with bytes length at non-const time" ); } #[test] pub fn test_non_const_invalid_input() { let actual = nu!("let a = 0; $a | bytes length"); assert!( actual.err.contains("command doesn't support int input"), "Expected error message when feeding bytes length non-bytes input at non-const time" ); } #[test] pub fn test_const_invalid_input() { let actual = nu!("const a = 0 | bytes length"); assert!( actual.err.contains("command doesn't support int input"), "Expected error message when feeding bytes length non-bytes input at const time" ); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/network/port.rs
crates/nu-command/tests/commands/network/port.rs
use nu_test_support::nu; use std::net::TcpListener; use std::sync::mpsc; #[test] fn port_with_invalid_range() { let actual = nu!("port 4000 3999"); assert!(actual.err.contains("Invalid range")) } #[test] fn port_with_already_usage() { let retry_times = 10; for _ in 0..retry_times { let (tx, rx) = mpsc::sync_channel(0); // let system pick a free port for us. let free_port = { let listener = TcpListener::bind("127.0.0.1:0").expect("failed to pick a port"); listener.local_addr().unwrap().port() }; let handler = std::thread::spawn(move || { let _listener = TcpListener::bind(format!("127.0.0.1:{free_port}")); let _ = rx.recv(); }); let actual = nu!(format!("port {free_port} {free_port}")); let _ = tx.send(true); // make sure that the thread is closed and we release the port. handler.join().unwrap(); // check for error kind str. if actual.err.contains("nu::shell::io::addr_in_use") { return; } } panic!("already check port report AddrInUse for several times, but still failed."); } #[test] fn port_from_system_given() { let actual = nu!("port"); // check that we can get an integer port from system. assert!(actual.out.parse::<u16>().unwrap() > 0) } #[test] fn port_out_of_range() { let actual = nu!("port 65536 99999"); assert!(actual.err.contains("can't convert usize to u16")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/network/mod.rs
crates/nu-command/tests/commands/network/mod.rs
mod http; mod port;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/network/http/put.rs
crates/nu-command/tests/commands/network/http/put.rs
use std::{thread, time::Duration}; use mockito::Server; use nu_test_support::nu; #[test] fn http_put_is_success() { let mut server = Server::new(); let _mock = server.mock("PUT", "/").match_body("foo").create(); let actual = nu!(format!(r#"http put {url} "foo""#, url = server.url())); assert!(actual.out.is_empty()) } #[test] fn http_put_is_success_pipeline() { let mut server = Server::new(); let _mock = server.mock("PUT", "/").match_body("foo").create(); let actual = nu!(format!(r#""foo" | http put {url} "#, url = server.url())); assert!(actual.out.is_empty()) } #[test] fn http_put_failed_due_to_server_error() { let mut server = Server::new(); let _mock = server.mock("PUT", "/").with_status(400).create(); let actual = nu!(format!(r#"http put {url} "body""#, url = server.url())); assert!(actual.err.contains("Bad request (400)")) } #[test] fn http_put_failed_due_to_missing_body() { let mut server = Server::new(); let _mock = server.mock("PUT", "/").create(); let actual = nu!(format!(r#"http put {url}"#, url = server.url())); assert!( actual .err .contains("Data must be provided either through pipeline or positional argument") ) } #[test] fn http_put_failed_due_to_unexpected_body() { let mut server = Server::new(); let _mock = server.mock("PUT", "/").match_body("foo").create(); let actual = nu!(format!(r#"http put {url} "bar""#, url = server.url())); assert!(actual.err.contains("Cannot make request")) } #[test] fn http_put_follows_redirect() { let mut server = Server::new(); let _mock = server.mock("GET", "/bar").with_body("bar").create(); let _mock = server .mock("PUT", "/foo") .with_status(301) .with_header("Location", "/bar") .create(); let actual = nu!(format!("http put {url}/foo putbody", url = server.url())); assert_eq!(&actual.out, "bar"); } #[test] fn http_put_redirect_mode_manual() { let mut server = Server::new(); let _mock = server .mock("PUT", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http put --redirect-mode manual {url}/foo putbody", url = server.url() )); assert_eq!(&actual.out, "foo"); } #[test] fn http_put_redirect_mode_error() { let mut server = Server::new(); let _mock = server .mock("PUT", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http put --redirect-mode error {url}/foo putbody", url = server.url() )); assert!(&actual.err.contains("nu::shell::network_failure")); assert!(&actual.err.contains( "Redirect encountered when redirect handling mode was 'error' (301 Moved Permanently)" )); } #[test] fn http_put_timeout() { let mut server = Server::new(); let _mock = server .mock("PUT", "/") .with_chunked_body(|w| { thread::sleep(Duration::from_secs(10)); w.write_all(b"Delayed response!") }) .create(); let actual = nu!(format!( "http put --max-time 100ms {url} putbody", url = server.url() )); assert!(&actual.err.contains("nu::shell::io::timed_out")); assert!(&actual.err.contains("Timed 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/network/http/options.rs
crates/nu-command/tests/commands/network/http/options.rs
use std::{thread, time::Duration}; use mockito::Server; use nu_test_support::nu; #[test] fn http_options_is_success() { let mut server = Server::new(); let _mock = server .mock("OPTIONS", "/") .with_header("Allow", "OPTIONS, GET") .create(); let actual = nu!(format!(r#"http options {url}"#, url = server.url())); assert!(!actual.out.is_empty()) } #[test] fn http_options_failed_due_to_server_error() { let mut server = Server::new(); let _mock = server.mock("OPTIONS", "/").with_status(400).create(); let actual = nu!(format!(r#"http options {url}"#, url = server.url())); assert!(actual.err.contains("Bad request (400)")) } #[test] fn http_options_timeout() { let mut server = Server::new(); let _mock = server .mock("OPTIONS", "/") .with_chunked_body(|w| { thread::sleep(Duration::from_secs(10)); w.write_all(b"Delayed response!") }) .create(); let actual = nu!(format!( "http options --max-time 100ms {url}", url = server.url() )); assert!(&actual.err.contains("nu::shell::io::timed_out")); assert!(&actual.err.contains("Timed 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/network/http/mod.rs
crates/nu-command/tests/commands/network/http/mod.rs
use nu_test_support::nu; use rstest::*; mod delete; mod get; mod head; mod options; mod patch; mod post; mod put; #[rstest] #[case::delete("delete")] #[case::get("get")] #[case::head("head")] #[case::options("options")] #[case::patch("patch")] #[case::post("post")] #[case::put("put")] #[case::delete_uppercase("DELETE")] #[case::get_uppercase("GET")] #[case::head_uppercase("HEAD")] #[case::options_uppercase("OPTIONS")] #[case::patch_uppercase("PATCH")] #[case::post_uppercase("POST")] #[case::put_uppercase("PUT")] fn disallow_dynamic_http_methods(#[case] method: &str) { assert!( nu!(format!("let method = '{method}'; http $method example.com")) .err .contains(&format!( "Prefer to use `http {}` directly", method.to_lowercase() )) ); } #[test] fn helpful_dns_error_for_unknown_domain() { let outcome = nu!("http get gibberish"); assert!(outcome.err.contains("nu::shell::network::dns")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/network/http/head.rs
crates/nu-command/tests/commands/network/http/head.rs
use mockito::Server; use nu_test_support::nu; #[test] fn http_head_is_success() { let mut server = Server::new(); let _mock = server.mock("HEAD", "/").with_header("foo", "bar").create(); let actual = nu!(format!(r#"http head {url}"#, url = server.url())); assert!(actual.out.contains("foo")); assert!(actual.out.contains("bar")); } #[test] fn http_head_failed_due_to_server_error() { let mut server = Server::new(); let _mock = server.mock("HEAD", "/").with_status(400).create(); let actual = nu!(format!(r#"http head {url}"#, url = server.url())); assert!( actual.err.contains("Bad request (400)"), "Unexpected error: {:?}", actual.err ) } #[test] fn http_head_follows_redirect() { let mut server = Server::new(); let _mock = server .mock("HEAD", "/bar") .with_header("bar", "bar") .create(); let _mock = server .mock("HEAD", "/foo") .with_status(301) .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http head {url}/foo | (where name == bar).0.value", url = server.url() )); assert_eq!(&actual.out, "bar"); } #[test] fn http_head_redirect_mode_manual() { let mut server = Server::new(); let _mock = server .mock("HEAD", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http head --redirect-mode manual {url}/foo | (where name == location).0.value", url = server.url() )); assert_eq!(&actual.out, "/bar"); } #[test] fn http_head_redirect_mode_error() { let mut server = Server::new(); let _mock = server .mock("HEAD", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http head --redirect-mode error {url}/foo", url = server.url() )); assert!(&actual.err.contains("nu::shell::network_failure")); assert!(&actual.err.contains( "Redirect encountered when redirect handling mode was 'error' (301 Moved Permanently)" )); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/network/http/post.rs
crates/nu-command/tests/commands/network/http/post.rs
use std::{thread, time::Duration}; use mockito::{Matcher, Server, ServerOpts}; use nu_test_support::nu; #[test] fn http_post_is_success() { let mut server = Server::new(); let _mock = server.mock("POST", "/").match_body("foo").create(); let actual = nu!(format!(r#"http post {url} "foo""#, url = server.url())); assert!(actual.out.is_empty()) } #[test] fn http_post_is_success_pipeline() { let mut server = Server::new(); let _mock = server.mock("POST", "/").match_body("foo").create(); let actual = nu!(format!(r#""foo" | http post {url}"#, url = server.url())); assert!(actual.out.is_empty()) } #[test] fn http_post_failed_due_to_server_error() { let mut server = Server::new(); let _mock = server.mock("POST", "/").with_status(400).create(); let actual = nu!(format!(r#"http post {url} "body""#, url = server.url())); assert!(actual.err.contains("Bad request (400)")) } #[test] fn http_post_failed_due_to_missing_body() { let mut server = Server::new(); let _mock = server.mock("POST", "/").create(); let actual = nu!(format!(r#"http post {url}"#, url = server.url())); assert!( actual .err .contains("Data must be provided either through pipeline or positional argument") ) } #[test] fn http_post_failed_due_to_unexpected_body() { let mut server = Server::new(); let _mock = server.mock("POST", "/").match_body("foo").create(); let actual = nu!(format!(r#"http post {url} "bar""#, url = server.url())); assert!(actual.err.contains("Cannot make request")) } const JSON: &str = r#"{ "foo": "bar" }"#; #[test] fn http_post_json_is_success() { let mut server = Server::new(); let mock = server.mock("POST", "/").match_body(JSON).create(); let actual = nu!(format!( r#"http post -t 'application/json' {url} {{foo: 'bar'}}"#, url = server.url() )); mock.assert(); assert!(actual.out.is_empty(), "Unexpected output {:?}", actual.out) } #[test] fn http_post_json_string_is_success() { let mut server = Server::new(); let mock = server.mock("POST", "/").match_body(JSON).create(); let actual = nu!(format!( r#"http post -t 'application/json' {url} '{{"foo":"bar"}}'"#, url = server.url() )); mock.assert(); assert!(actual.out.is_empty()) } const JSON_LIST: &str = r#"[ { "foo": "bar" } ]"#; #[test] fn http_post_json_list_is_success() { let mut server = Server::new(); let mock = server.mock("POST", "/").match_body(JSON_LIST).create(); let actual = nu!(format!( r#"http post -t 'application/json' {url} [{{foo: "bar"}}]"#, url = server.url() )); mock.assert(); assert!(actual.out.is_empty()) } #[test] fn http_post_json_int_is_success() { let mut server = Server::new(); let mock = server.mock("POST", "/").match_body(r#"50"#).create(); let actual = nu!(format!( r#"http post -t 'application/json' {url} 50"#, url = server.url() )); mock.assert(); assert!(actual.out.is_empty()) } #[test] fn http_post_json_raw_string_is_success() { let mut server = Server::new(); let mock = server.mock("POST", "/").match_body(r#""test""#).create(); let actual = nu!(format!( r#"http post -t 'application/json' {url} "test""#, url = server.url() )); mock.assert(); assert!(actual.out.is_empty()) } #[test] fn http_post_follows_redirect() { let mut server = Server::new(); let _mock = server.mock("GET", "/bar").with_body("bar").create(); let _mock = server .mock("POST", "/foo") .with_status(301) .with_header("Location", "/bar") .create(); let actual = nu!(format!("http post {url}/foo postbody", url = server.url())); assert_eq!(&actual.out, "bar"); } #[test] fn http_post_redirect_mode_manual() { let mut server = Server::new(); let _mock = server .mock("POST", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http post --redirect-mode manual {url}/foo postbody", url = server.url() )); assert_eq!(&actual.out, "foo"); } #[test] fn http_post_redirect_mode_error() { let mut server = Server::new(); let _mock = server .mock("POST", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http post --redirect-mode error {url}/foo postbody", url = server.url() )); assert!(&actual.err.contains("nu::shell::network_failure")); assert!(&actual.err.contains( "Redirect encountered when redirect handling mode was 'error' (301 Moved Permanently)" )); } #[test] fn http_post_multipart_is_success() { let mut server = Server::new_with_opts(ServerOpts { assert_on_drop: true, ..Default::default() }); let _mock = server .mock("POST", "/") .match_header( "content-type", Matcher::Regex("multipart/form-data; boundary=.*".to_string()), ) .match_body(Matcher::AllOf(vec![ Matcher::Regex(r#"(?m)^Content-Disposition: form-data; name="foo""#.to_string()), Matcher::Regex(r#"(?m)^Content-Type: application/octet-stream"#.to_string()), Matcher::Regex(r#"(?m)^Content-Length: 3"#.to_string()), Matcher::Regex(r#"(?m)^bar"#.to_string()), ])) .with_status(200) .create(); let actual = nu!(format!( "http post --content-type multipart/form-data {url} {{foo: ('bar' | into binary) }}", url = server.url() )); assert!(actual.out.is_empty()) } #[test] fn http_post_timeout() { let mut server = Server::new(); let _mock = server .mock("POST", "/") .with_chunked_body(|w| { thread::sleep(Duration::from_secs(10)); w.write_all(b"Delayed response!") }) .create(); let actual = nu!(format!( "http post --max-time 100ms {url} postbody", url = server.url() )); assert!(&actual.err.contains("nu::shell::io::timed_out")); assert!(&actual.err.contains("Timed 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/network/http/get.rs
crates/nu-command/tests/commands/network/http/get.rs
use std::{thread, time::Duration}; use mockito::Server; use nu_test_support::nu; #[test] fn http_get_is_success() { let mut server = Server::new(); let _mock = server.mock("GET", "/").with_body("foo").create(); let actual = nu!(format!(r#"http get {url}"#, url = server.url())); assert_eq!(actual.out, "foo") } #[test] fn http_get_failed_due_to_server_error() { let mut server = Server::new(); let _mock = server.mock("GET", "/").with_status(400).create(); let actual = nu!(format!(r#"http get {url}"#, url = server.url())); assert!(actual.err.contains("Bad request (400)")) } #[test] fn http_get_with_accept_errors() { let mut server = Server::new(); let _mock = server .mock("GET", "/") .with_status(400) .with_body("error body") .create(); let actual = nu!(format!(r#"http get -e {url}"#, url = server.url())); assert!(actual.out.contains("error body")) } #[test] fn http_get_with_accept_errors_and_full_raw_response() { let mut server = Server::new(); let _mock = server .mock("GET", "/") .with_status(400) .with_body("error body") .create(); let actual = nu!(format!( r#" http get -e -f {url} | $"($in.status) => ($in.body)" "#, url = server.url() )); assert!(actual.out.contains("400 => error body")) } #[test] fn http_get_with_accept_errors_and_full_json_response() { let mut server = Server::new(); let _mock = server .mock("GET", "/") .with_status(400) .with_header("content-type", "application/json") .with_body( r#" {"msg": "error body"} "#, ) .create(); let actual = nu!(format!( r#" http get -e -f {url} | $"($in.status) => ($in.body.msg)" "#, url = server.url() )); assert!(actual.out.contains("400 => error body")) } #[test] fn http_get_with_custom_headers_as_records() { let mut server = Server::new(); let mock1 = server .mock("GET", "/") .match_header("content-type", "application/json") .with_body(r#"{"hello": "world"}"#) .create(); let mock2 = server .mock("GET", "/") .match_header("content-type", "text/plain") .with_body("world") .create(); let _json_response = nu!(format!( "http get -H {{content-type: application/json}} {url}", url = server.url() )); let _text_response = nu!(format!( "http get -H {{content-type: text/plain}} {url}", url = server.url() )); mock1.assert(); mock2.assert(); } #[test] fn http_get_full_response() { let mut server = Server::new(); let _mock = server.mock("GET", "/").with_body("foo").create(); let actual = nu!(format!( "http get --full {url} --headers [foo bar] | to json", url = server.url() )); let output: serde_json::Value = serde_json::from_str(&actual.out).unwrap(); assert_eq!(output["status"], 200); assert_eq!(output["body"], "foo"); // There's only one request header, we can get it by index assert_eq!(output["headers"]["request"][0]["name"], "foo"); assert_eq!(output["headers"]["request"][0]["value"], "bar"); // ... and multiple response headers, so have to search by name let header = output["headers"]["response"] .as_array() .unwrap() .iter() .find(|e| e["name"] == "connection") .unwrap(); assert_eq!(header["value"], "close"); } #[test] fn http_get_follows_redirect() { let mut server = Server::new(); let _mock = server.mock("GET", "/bar").with_body("bar").create(); let _mock = server .mock("GET", "/foo") .with_status(301) .with_header("Location", "/bar") .create(); let actual = nu!(format!("http get {url}/foo", url = server.url())); assert_eq!(&actual.out, "bar"); } #[test] fn http_get_redirect_mode_manual() { let mut server = Server::new(); let _mock = server .mock("GET", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http get --redirect-mode manual {url}/foo", url = server.url() )); assert_eq!(&actual.out, "foo"); } #[test] fn http_get_redirect_mode_error() { let mut server = Server::new(); let _mock = server .mock("GET", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http get --redirect-mode error {url}/foo", url = server.url() )); assert!(&actual.err.contains("nu::shell::network_failure")); assert!(&actual.err.contains( "Redirect encountered when redirect handling mode was 'error' (301 Moved Permanently)" )); } // These tests require network access; they use badssl.com which is a Google-affiliated site for testing various SSL errors. // Revisit this if these tests prove to be flaky or unstable. // // These tests are flaky and cause CI to fail somewhat regularly. See PR #12010. #[test] #[ignore = "unreliable test"] fn http_get_expired_cert_fails() { let actual = nu!("http get https://expired.badssl.com/"); assert!(actual.err.contains("network_failure")); } #[test] #[ignore = "unreliable test"] fn http_get_expired_cert_override() { let actual = nu!("http get --insecure https://expired.badssl.com/"); assert!(actual.out.contains("<html>")); } #[test] #[ignore = "unreliable test"] fn http_get_self_signed_fails() { let actual = nu!("http get https://self-signed.badssl.com/"); assert!(actual.err.contains("network_failure")); } #[test] #[ignore = "unreliable test"] fn http_get_self_signed_override() { let actual = nu!("http get --insecure https://self-signed.badssl.com/"); assert!(actual.out.contains("<html>")); } #[test] fn http_get_with_invalid_mime_type() { let mut server = Server::new(); let _mock = server .mock("GET", "/foo.nuon") .with_status(200) // `what&ever` is not a parseable MIME type .with_header("content-type", "what&ever") .with_body("[1 2 3]") .create(); // but `from nuon` is a known command in nu, so we take `foo.{ext}` and pass it to `from {ext}` let actual = nu!(format!( r#"http get {url}/foo.nuon | to json --raw"#, url = server.url() )); assert_eq!(actual.out, "[1,2,3]"); } #[test] fn http_get_with_unknown_mime_type() { let mut server = Server::new(); let _mock = server .mock("GET", "/foo") .with_status(200) // `application/nuon` is not an IANA-registered MIME type .with_header("content-type", "application/nuon") .with_body("[1 2 3]") .create(); // but `from nuon` is a known command in nu, so we take `{garbage}/{whatever}` and pass it to `from {whatever}` let actual = nu!(format!( r#" http get {url}/foo | to json --raw "#, url = server.url() )); assert_eq!(actual.out, "[1,2,3]"); } #[test] fn http_get_timeout() { let mut server = Server::new(); let _mock = server .mock("GET", "/") .with_chunked_body(|w| { thread::sleep(Duration::from_secs(10)); w.write_all(b"Delayed response!") }) .create(); let actual = nu!(format!( "http get --max-time 100ms {url}", url = server.url() )); assert!( &actual.err.contains("nu::shell::io::timed_out"), "unexpected error: {:?}", actual.err ); assert!( &actual.err.contains("Timed out"), "unexpected error: {:?}", actual.err ); } #[test] fn http_get_response_metadata() { let mut server = Server::new(); let _mock = server .mock("GET", "/") .with_status(200) .with_header("x-custom-header", "test-value") .with_body("success") .create(); let actual = nu!(format!( r#"http get --raw {url} | metadata | get http_response | get status"#, url = server.url() )); assert_eq!(actual.out, "200"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/network/http/delete.rs
crates/nu-command/tests/commands/network/http/delete.rs
use std::{thread, time::Duration}; use mockito::Server; use nu_test_support::nu; #[test] fn http_delete_is_success() { let mut server = Server::new(); let _mock = server.mock("DELETE", "/").create(); let actual = nu!(format!(r#"http delete {url}"#, url = server.url())); assert!(actual.out.is_empty()) } #[test] fn http_delete_is_success_pipeline() { let mut server = Server::new(); let _mock = server.mock("DELETE", "/").create(); let actual = nu!(format!(r#""foo" | http delete {url}"#, url = server.url())); assert!(actual.out.is_empty()) } #[test] fn http_delete_failed_due_to_server_error() { let mut server = Server::new(); let _mock = server.mock("DELETE", "/").with_status(400).create(); let actual = nu!(format!(r#"http delete {url}"#, url = server.url())); assert!( actual.err.contains("Bad request (400)"), "unexpected error: {:?}", actual.err ) } #[test] fn http_delete_follows_redirect() { let mut server = Server::new(); let _mock = server.mock("GET", "/bar").with_body("bar").create(); let _mock = server .mock("DELETE", "/foo") .with_status(301) .with_header("Location", "/bar") .create(); let actual = nu!(format!("http delete {url}/foo", url = server.url())); assert_eq!(&actual.out, "bar"); } #[test] fn http_delete_redirect_mode_manual() { let mut server = Server::new(); let _mock = server .mock("DELETE", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http delete --redirect-mode manual {url}/foo", url = server.url() )); assert_eq!(&actual.out, "foo"); } #[test] fn http_delete_redirect_mode_error() { let mut server = Server::new(); let _mock = server .mock("DELETE", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http delete --redirect-mode error {url}/foo", url = server.url() )); assert!(&actual.err.contains("nu::shell::network_failure")); assert!(&actual.err.contains( "Redirect encountered when redirect handling mode was 'error' (301 Moved Permanently)" )); } #[test] fn http_delete_timeout() { let mut server = Server::new(); let _mock = server .mock("DELETE", "/") .with_chunked_body(|w| { thread::sleep(Duration::from_secs(10)); w.write_all(b"Delayed response!") }) .create(); let actual = nu!(format!( "http delete --max-time 100ms {url}", url = server.url() )); assert!( &actual.err.contains("nu::shell::io::timed_out"), "unexpected error : {:?}", actual.err ); assert!( &actual.err.contains("Timed out"), "unexpected error : {:?}", 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/network/http/patch.rs
crates/nu-command/tests/commands/network/http/patch.rs
use std::{thread, time::Duration}; use mockito::Server; use nu_test_support::nu; #[test] fn http_patch_is_success() { let mut server = Server::new(); let _mock = server.mock("PATCH", "/").match_body("foo").create(); let actual = nu!(format!(r#"http patch {url} "foo""#, url = server.url())); assert!(actual.out.is_empty()) } #[test] fn http_patch_is_success_pipeline() { let mut server = Server::new(); let _mock = server.mock("PATCH", "/").match_body("foo").create(); let actual = nu!(format!(r#""foo" | http patch {url}"#, url = server.url())); assert!(actual.out.is_empty()) } #[test] fn http_patch_failed_due_to_server_error() { let mut server = Server::new(); let _mock = server.mock("PATCH", "/").with_status(400).create(); let actual = nu!(format!(r#"http patch {url} "body""#, url = server.url())); assert!(actual.err.contains("Bad request (400)")) } #[test] fn http_patch_failed_due_to_missing_body() { let mut server = Server::new(); let _mock = server.mock("PATCH", "/").create(); let actual = nu!(format!(r#"http patch {url}"#, url = server.url())); assert!( actual .err .contains("Data must be provided either through pipeline or positional argument") ) } #[test] fn http_patch_failed_due_to_unexpected_body() { let mut server = Server::new(); let _mock = server.mock("PATCH", "/").match_body("foo").create(); let actual = nu!(format!(r#"http patch {url} "bar""#, url = server.url())); assert!(actual.err.contains("Cannot make request")) } #[test] fn http_patch_follows_redirect() { let mut server = Server::new(); let _mock = server.mock("GET", "/bar").with_body("bar").create(); let _mock = server .mock("PATCH", "/foo") .with_status(301) .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http patch {url}/foo patchbody", url = server.url() )); assert_eq!(&actual.out, "bar"); } #[test] fn http_patch_redirect_mode_manual() { let mut server = Server::new(); let _mock = server .mock("PATCH", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http patch --redirect-mode manual {url}/foo patchbody", url = server.url() )); assert_eq!(&actual.out, "foo"); } #[test] fn http_patch_redirect_mode_error() { let mut server = Server::new(); let _mock = server .mock("PATCH", "/foo") .with_status(301) .with_body("foo") .with_header("Location", "/bar") .create(); let actual = nu!(format!( "http patch --redirect-mode error {url}/foo patchbody", url = server.url() )); assert!(&actual.err.contains("nu::shell::network_failure")); assert!(&actual.err.contains( "Redirect encountered when redirect handling mode was 'error' (301 Moved Permanently)" )); } #[test] fn http_patch_timeout() { let mut server = Server::new(); let _mock = server .mock("PATCH", "/") .with_chunked_body(|w| { thread::sleep(Duration::from_secs(10)); w.write_all(b"Delayed response!") }) .create(); let actual = nu!(format!( "http patch --max-time 100ms {url} patchbody", url = server.url() )); assert!(&actual.err.contains("nu::shell::io::timed_out")); assert!(&actual.err.contains("Timed 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/database/query_db.rs
crates/nu-command/tests/commands/database/query_db.rs
use nu_test_support::{nu, nu_repl_code, playground::Playground}; // Multiple nu! calls don't persist state, so we can't store it in a function const DATABASE_INIT: &str = r#"stor open | query db "CREATE TABLE IF NOT EXISTS test_db ( name TEXT, age INTEGER, height REAL, serious BOOLEAN, created_at DATETIME, largest_file INTEGER, time_slept INTEGER, null_field TEXT, data BLOB )""#; #[test] fn data_types() { Playground::setup("empty", |_, _| { let results = nu!(nu_repl_code(&[ DATABASE_INIT, // Add row with our data types r#"stor open | query db "INSERT INTO test_db VALUES ( 'nimurod', 20, 6.0, true, date('2024-03-23T00:15:24-03:00'), 72400000, 1000000, NULL, x'68656c6c6f' )" "#, // Query our table with the row we just added to get its nushell types r#" stor open | query db "SELECT * FROM test_db" | first | values | each { describe } | str join "-" "# ])); // Assert data types match. Booleans are mapped to "numeric" due to internal SQLite representations: // https://www.sqlite.org/datatype3.html // They are simply 1 or 0 in practice, but the column could contain any valid SQLite value assert_eq!( results.out, "string-int-float-int-string-int-int-nothing-binary" ); }); } #[test] fn ordered_params() { Playground::setup("empty", |_, _| { let results = nu!(nu_repl_code(&[ DATABASE_INIT, // Add row with our data types r#"(stor open | query db "INSERT INTO test_db VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" -p [ 'nimurod', 20, 6.0, true, ('2024-03-23T00:15:24-03:00' | into datetime), 72.4mb, 1ms, null, ("hello" | into binary) ] )"#, // Query our nu values and types r#" let values = (stor open | query db "SELECT * FROM test_db" | first | values); ($values | str join '-') + "_" + ($values | each { describe } | str join '-') "# ])); assert_eq!( results.out, "nimurod-20-6.0-1-2024-03-23 00:15:24-03:00-72400000-1000000--[104, 101, 108, 108, 111]_\ string-int-float-int-string-int-int-nothing-binary" ); }); } #[test] fn named_params() { Playground::setup("empty", |_, _| { let results = nu!(nu_repl_code(&[ DATABASE_INIT, // Add row with our data types. query db should support all possible named parameters // @-prefixed, $-prefixed, and :-prefixed // But :prefix is the "blessed" way to do it, and as such, the only one that's // promoted to from a bare word `key: value` property in the record // In practice, users should not use @param or $param r#"(stor open | query db "INSERT INTO test_db VALUES (:name, :age, @height, $serious, :created_at, :largest_file, :time_slept, :null_field, :data)" -p { name: 'nimurod', ':age': 20, '@height': 6.0, '$serious': true, created_at: ('2024-03-23T00:15:24-03:00' | into datetime), largest_file: 72.4mb, time_slept: 1ms, null_field: null, data: ("hello" | into binary) } )"#, // Query our nu values and types r#" let values = (stor open | query db "SELECT * FROM test_db" | first | values); ($values | str join '-') + "_" + ($values | each { describe } | str join '-') "# ])); assert_eq!( results.out, "nimurod-20-6.0-1-2024-03-23 00:15:24-03:00-72400000-1000000--[104, 101, 108, 108, 111]_\ string-int-float-int-string-int-int-nothing-binary" ); }); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/database/mod.rs
crates/nu-command/tests/commands/database/mod.rs
mod into_sqlite; mod query_db;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/tests/commands/database/into_sqlite.rs
crates/nu-command/tests/commands/database/into_sqlite.rs
use chrono::{DateTime, FixedOffset}; use nu_path::AbsolutePathBuf; use nu_protocol::{Span, Value, ast::PathMember, casing::Casing, engine::EngineState, record}; use nu_test_support::{ fs::{Stub, line_ending}, nu, playground::{Dirs, Playground}, }; use rand::{ Rng, SeedableRng, distr::{Alphanumeric, SampleString, StandardUniform}, prelude::Distribution, random_range, rngs::StdRng, }; use std::io::Write; #[test] fn into_sqlite_schema() { Playground::setup("schema", |dirs, _| { let testdb = make_sqlite_db( &dirs, r#"[ [somebool, someint, somefloat, somefilesize, someduration, somedate, somestring, somebinary]; [true, 1, 2.0, 1kb, 1sec, "2023-09-10 11:30:00", "foo", ("binary" | into binary)], [false, 2, 3.0, 2mb, 4wk, "2020-09-10 12:30:00", "bar", ("wut" | into binary)], ]"#, ); let conn = rusqlite::Connection::open(testdb).unwrap(); let mut stmt = conn.prepare("SELECT * FROM pragma_table_info(?1)").unwrap(); let actual_rows: Vec<_> = stmt .query_and_then(["main"], |row| -> rusqlite::Result<_, rusqlite::Error> { let name: String = row.get("name").unwrap(); let col_type: String = row.get("type").unwrap(); Ok((name, col_type)) }) .unwrap() .map(|row| row.unwrap()) .collect(); let expected_rows = vec![ ("somebool".into(), "BOOLEAN".into()), ("someint".into(), "INTEGER".into()), ("somefloat".into(), "REAL".into()), ("somefilesize".into(), "INTEGER".into()), ("someduration".into(), "BIGINT".into()), ("somedate".into(), "TEXT".into()), ("somestring".into(), "TEXT".into()), ("somebinary".into(), "BLOB".into()), ]; assert_eq!(expected_rows, actual_rows); }); } #[test] fn into_sqlite_values() { Playground::setup("values", |dirs, _| { insert_test_rows( &dirs, r#"[ [somebool, someint, somefloat, somefilesize, someduration, somedate, somestring, somebinary, somenull]; [true, 1, 2.0, 1kb, 1sec, "2023-09-10T11:30:00-00:00", "foo", ("binary" | into binary), 1], [false, 2, 3.0, 2mb, 4wk, "2020-09-10T12:30:00-00:00", "bar", ("wut" | into binary), null], ]"#, None, vec![ TestRow( true, 1, 2.0, 1000, 1000000000, DateTime::parse_from_rfc3339("2023-09-10T11:30:00-00:00").unwrap(), "foo".into(), b"binary".to_vec(), rusqlite::types::Value::Integer(1), ), TestRow( false, 2, 3.0, 2000000, 2419200000000000, DateTime::parse_from_rfc3339("2020-09-10T12:30:00-00:00").unwrap(), "bar".into(), b"wut".to_vec(), rusqlite::types::Value::Null, ), ], ); }); } /// When we create a new table, we use the first row to infer the schema of the /// table. In the event that a column is null, we can't know what type the row /// should be, so we just assume TEXT. #[test] fn into_sqlite_values_first_column_null() { Playground::setup("values", |dirs, _| { insert_test_rows( &dirs, r#"[ [somebool, someint, somefloat, somefilesize, someduration, somedate, somestring, somebinary, somenull]; [false, 2, 3.0, 2mb, 4wk, "2020-09-10T12:30:00-00:00", "bar", ("wut" | into binary), null], [true, 1, 2.0, 1kb, 1sec, "2023-09-10T11:30:00-00:00", "foo", ("binary" | into binary), 1], ]"#, None, vec![ TestRow( false, 2, 3.0, 2000000, 2419200000000000, DateTime::parse_from_rfc3339("2020-09-10T12:30:00-00:00").unwrap(), "bar".into(), b"wut".to_vec(), rusqlite::types::Value::Null, ), TestRow( true, 1, 2.0, 1000, 1000000000, DateTime::parse_from_rfc3339("2023-09-10T11:30:00-00:00").unwrap(), "foo".into(), b"binary".to_vec(), rusqlite::types::Value::Text("1".into()), ), ], ); }); } /// If the DB / table already exist, then the insert should end up with the /// right data types no matter if the first row is null or not. #[test] fn into_sqlite_values_first_column_null_preexisting_db() { Playground::setup("values", |dirs, _| { insert_test_rows( &dirs, r#"[ [somebool, someint, somefloat, somefilesize, someduration, somedate, somestring, somebinary, somenull]; [true, 1, 2.0, 1kb, 1sec, "2023-09-10T11:30:00-00:00", "foo", ("binary" | into binary), 1], [false, 2, 3.0, 2mb, 4wk, "2020-09-10T12:30:00-00:00", "bar", ("wut" | into binary), null], ]"#, None, vec![ TestRow( true, 1, 2.0, 1000, 1000000000, DateTime::parse_from_rfc3339("2023-09-10T11:30:00-00:00").unwrap(), "foo".into(), b"binary".to_vec(), rusqlite::types::Value::Integer(1), ), TestRow( false, 2, 3.0, 2000000, 2419200000000000, DateTime::parse_from_rfc3339("2020-09-10T12:30:00-00:00").unwrap(), "bar".into(), b"wut".to_vec(), rusqlite::types::Value::Null, ), ], ); insert_test_rows( &dirs, r#"[ [somebool, someint, somefloat, somefilesize, someduration, somedate, somestring, somebinary, somenull]; [true, 3, 5.0, 3.1mb, 1wk, "2020-09-10T12:30:00-00:00", "baz", ("huh" | into binary), null], [true, 3, 5.0, 3.1mb, 1wk, "2020-09-10T12:30:00-00:00", "baz", ("huh" | into binary), 3], ]"#, None, vec![ TestRow( true, 1, 2.0, 1000, 1000000000, DateTime::parse_from_rfc3339("2023-09-10T11:30:00-00:00").unwrap(), "foo".into(), b"binary".to_vec(), rusqlite::types::Value::Integer(1), ), TestRow( false, 2, 3.0, 2000000, 2419200000000000, DateTime::parse_from_rfc3339("2020-09-10T12:30:00-00:00").unwrap(), "bar".into(), b"wut".to_vec(), rusqlite::types::Value::Null, ), TestRow( true, 3, 5.0, 3100000, 604800000000000, DateTime::parse_from_rfc3339("2020-09-10T12:30:00-00:00").unwrap(), "baz".into(), b"huh".to_vec(), rusqlite::types::Value::Null, ), TestRow( true, 3, 5.0, 3100000, 604800000000000, DateTime::parse_from_rfc3339("2020-09-10T12:30:00-00:00").unwrap(), "baz".into(), b"huh".to_vec(), rusqlite::types::Value::Integer(3), ), ], ); }); } /// Opening a preexisting database should append to it #[test] fn into_sqlite_existing_db_append() { Playground::setup("existing_db_append", |dirs, _| { // create a new DB with only one row insert_test_rows( &dirs, r#"[ [somebool, someint, somefloat, somefilesize, someduration, somedate, somestring, somebinary, somenull]; [true, 1, 2.0, 1kb, 1sec, "2023-09-10T11:30:00-00:00", "foo", ("binary" | into binary), null], ]"#, None, vec![TestRow( true, 1, 2.0, 1000, 1000000000, DateTime::parse_from_rfc3339("2023-09-10T11:30:00-00:00").unwrap(), "foo".into(), b"binary".to_vec(), rusqlite::types::Value::Null, )], ); // open the same DB again and write one row insert_test_rows( &dirs, r#"[ [somebool, someint, somefloat, somefilesize, someduration, somedate, somestring, somebinary, somenull]; [false, 2, 3.0, 2mb, 4wk, "2020-09-10T12:30:00-00:00", "bar", ("wut" | into binary), null], ]"#, None, // it should have both rows vec![ TestRow( true, 1, 2.0, 1000, 1000000000, DateTime::parse_from_rfc3339("2023-09-10T11:30:00-00:00").unwrap(), "foo".into(), b"binary".to_vec(), rusqlite::types::Value::Null, ), TestRow( false, 2, 3.0, 2000000, 2419200000000000, DateTime::parse_from_rfc3339("2020-09-10T12:30:00-00:00").unwrap(), "bar".into(), b"wut".to_vec(), rusqlite::types::Value::Null, ), ], ); }); } /// Test inserting a good number of randomly generated rows to test an actual /// streaming pipeline instead of a simple value #[test] fn into_sqlite_big_insert() { let engine_state = EngineState::new(); // don't serialize closures let serialize_types = false; Playground::setup("big_insert", |dirs, playground| { const NUM_ROWS: usize = 10_000; const NUON_FILE_NAME: &str = "data.nuon"; let nuon_path = dirs.test().join(NUON_FILE_NAME); playground.with_files(&[Stub::EmptyFile(&nuon_path.to_string_lossy())]); let mut expected_rows = Vec::new(); let mut nuon_file = std::fs::OpenOptions::new() .write(true) .open(&nuon_path) .unwrap(); // write the header for row in std::iter::repeat_with(TestRow::random).take(NUM_ROWS) { let mut value: Value = row.clone().into(); // HACK: Convert to a string to get around this: https://github.com/nushell/nushell/issues/9186 value .upsert_cell_path( &[PathMember::String { val: "somedate".into(), span: Span::unknown(), optional: false, casing: Casing::Sensitive, }], Box::new(|dateval| { Value::string(dateval.coerce_string().unwrap(), dateval.span()) }), ) .unwrap(); let nuon = nuon::to_nuon( &engine_state, &value, nuon::ToStyle::Default, Some(Span::unknown()), serialize_types, ) .unwrap() + &line_ending(); nuon_file.write_all(nuon.as_bytes()).unwrap(); expected_rows.push(row); } insert_test_rows( &dirs, &format!( "open --raw {} | lines | each {{ from nuon }}", nuon_path.to_string_lossy() ), None, expected_rows, ); }); } /// empty in, empty out #[test] fn into_sqlite_empty() { Playground::setup("empty", |dirs, _| { insert_test_rows(&dirs, r#"[]"#, Some("SELECT * FROM sqlite_schema;"), vec![]); }); } #[derive(Debug, PartialEq, Clone)] struct TestRow( bool, i64, f64, i64, i64, chrono::DateTime<chrono::FixedOffset>, std::string::String, std::vec::Vec<u8>, rusqlite::types::Value, ); impl TestRow { pub fn random() -> Self { StdRng::from_os_rng().sample(StandardUniform) } } impl From<TestRow> for Value { fn from(row: TestRow) -> Self { Value::record( record! { "somebool" => Value::bool(row.0, Span::unknown()), "someint" => Value::int(row.1, Span::unknown()), "somefloat" => Value::float(row.2, Span::unknown()), "somefilesize" => Value::filesize(row.3, Span::unknown()), "someduration" => Value::duration(row.4, Span::unknown()), "somedate" => Value::date(row.5, Span::unknown()), "somestring" => Value::string(row.6, Span::unknown()), "somebinary" => Value::binary(row.7, Span::unknown()), "somenull" => Value::nothing(Span::unknown()), }, Span::unknown(), ) } } impl TryFrom<&rusqlite::Row<'_>> for TestRow { type Error = rusqlite::Error; fn try_from(row: &rusqlite::Row) -> Result<Self, Self::Error> { let somebool: bool = row.get("somebool").unwrap(); let someint: i64 = row.get("someint").unwrap(); let somefloat: f64 = row.get("somefloat").unwrap(); let somefilesize: i64 = row.get("somefilesize").unwrap(); let someduration: i64 = row.get("someduration").unwrap(); let somedate: DateTime<FixedOffset> = row.get("somedate").unwrap(); let somestring: String = row.get("somestring").unwrap(); let somebinary: Vec<u8> = row.get("somebinary").unwrap(); let somenull: rusqlite::types::Value = row.get("somenull").unwrap(); Ok(TestRow( somebool, someint, somefloat, somefilesize, someduration, somedate, somestring, somebinary, somenull, )) } } impl Distribution<TestRow> for StandardUniform { fn sample<R>(&self, rng: &mut R) -> TestRow where R: rand::Rng + ?Sized, { let dt = DateTime::from_timestamp_millis(random_range(0..2324252554000)) .unwrap() .fixed_offset(); let rand_string = Alphanumeric.sample_string(rng, 10); // limit the size of the numbers to work around // https://github.com/nushell/nushell/issues/10612 let filesize = random_range(-1024..=1024); let duration = random_range(-1024..=1024); TestRow( rng.random(), rng.random(), rng.random(), filesize, duration, dt, rand_string, rng.random::<u64>().to_be_bytes().to_vec(), rusqlite::types::Value::Null, ) } } fn make_sqlite_db(dirs: &Dirs, nu_table: &str) -> AbsolutePathBuf { let testdir = dirs.test(); let testdb_path = testdir.join(testdir.file_name().unwrap().to_str().unwrap().to_owned() + ".db"); let testdb = testdb_path.to_str().unwrap(); let nucmd = nu!( cwd: testdir, format!("{nu_table} | into sqlite {testdb}") ); assert!(nucmd.status.success()); testdb_path } fn insert_test_rows(dirs: &Dirs, nu_table: &str, sql_query: Option<&str>, expected: Vec<TestRow>) { let sql_query = sql_query.unwrap_or("SELECT * FROM main;"); let testdb = make_sqlite_db(dirs, nu_table); let conn = rusqlite::Connection::open(testdb).unwrap(); let mut stmt = conn.prepare(sql_query).unwrap(); let actual_rows: Vec<_> = stmt .query_and_then([], |row| TestRow::try_from(row)) .unwrap() .map(|row| row.unwrap()) .collect(); assert_eq!(expected, actual_rows); } #[test] fn test_auto_conversion() { Playground::setup("sqlite json auto conversion", |_, playground| { let raw = "{a_record:{foo:bar,baz:quux},a_list:[1,2,3],a_table:[[a,b];[0,1],[2,3]]}"; nu!(cwd: playground.cwd(), format!("{raw} | into sqlite filename.db -t my_table")); let outcome = nu!( cwd: playground.cwd(), "open filename.db | get my_table.0 | to nuon --raw" ); assert_eq!(outcome.out, raw); }); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false