nushell/crates/nu-command/tests/commands/with_env.rs
Stefan Holderbach c9e9b138eb
Improve with-env robustness (#12523)
# Description
Work for #7149

- **Error `with-env` given uneven count in list form**
- **Fix `with-env` `CantConvert` to record**
- **Error `with-env` when given protected env vars**
- **Deprecate list/table input of vars to `with-env`**
- **Remove examples for deprecated input**

# User-Facing Changes

## Deprecation of the following forms

```
> with-env [MYENV "my env value"] { $env.MYENV }
my env value

> with-env [X Y W Z] { $env.X }
Y

> with-env [[X W]; [Y Z]] { $env.W }
Z
```

## recommended standardized form

```
# Set by key-value record
> with-env {X: "Y", W: "Z"} { [$env.X $env.W] }
╭───┬───╮
│ 0 │ Y │
│ 1 │ Z │
╰───┴───╯
```

## (Side effect) Repeated definitions in an env shorthand are now
disallowed

```
> FOO=bar FOO=baz $env
Error: nu:🐚:column_defined_twice

  × Record field or table column used twice: FOO
   ╭─[entry #1:1:1]
 1 │ FOO=bar FOO=baz $env
   · ─┬─     ─┬─
   ·  │       ╰── field redefined here
   ·  ╰── field first defined here
   ╰────
```
2024-04-16 19:08:58 +08:00

73 lines
1.5 KiB
Rust

use nu_test_support::nu;
#[test]
fn with_env_extends_environment() {
let actual = nu!("with-env { FOO: BARRRR } {echo $env} | get FOO");
assert_eq!(actual.out, "BARRRR");
}
#[test]
fn with_env_shorthand() {
let actual = nu!("FOO=BARRRR echo $env | get FOO");
assert_eq!(actual.out, "BARRRR");
}
#[test]
fn shorthand_doesnt_reorder_arguments() {
let actual = nu!("FOO=BARRRR nu --testbin cococo first second");
assert_eq!(actual.out, "first second");
}
#[test]
fn with_env_shorthand_trims_quotes() {
let actual = nu!("FOO='BARRRR' echo $env | get FOO");
assert_eq!(actual.out, "BARRRR");
}
#[test]
fn with_env_and_shorthand_same_result() {
let actual_shorthand = nu!("FOO='BARRRR' echo $env | get FOO");
let actual_normal = nu!("with-env { FOO: BARRRR } {echo $env} | get FOO");
assert_eq!(actual_shorthand.out, actual_normal.out);
}
#[test]
fn test_redirection2() {
let actual =
nu!("let x = (FOO=BAR nu --testbin cococo niceenvvar); $x | str trim | str length");
assert_eq!(actual.out, "10");
}
#[test]
fn with_env_hides_variables_in_parent_scope() {
let actual = nu!(r#"
$env.FOO = "1"
print $env.FOO
with-env { FOO: null } {
echo $env.FOO
}
print $env.FOO
"#);
assert_eq!(actual.out, "11");
}
#[test]
fn with_env_shorthand_can_not_hide_variables() {
let actual = nu!(r#"
$env.FOO = "1"
print $env.FOO
FOO=null print $env.FOO
print $env.FOO
"#);
assert_eq!(actual.out, "1null1");
}