Custom command attributes (#14906)

# Description
Add custom command attributes.

- Attributes are placed before a command definition and start with a `@`
character.
- Attribute invocations consist of const command call. The command's
name must start with "attr ", but this prefix is not used in the
invocation.
- A command named `attr example` is invoked as an attribute as
`@example`
-   Several built-in attribute commands are provided as part of this PR
    -   `attr example`: Attaches an example to the commands help text
        ```nushell
        # Double numbers
        @example "double an int"  { 5 | double }   --result 10
        @example "double a float" { 0.5 | double } --result 1.0
        def double []: [number -> number] {
            $in * 2
        }
        ```
    -   `attr search-terms`: Adds search terms to a command
    -   ~`attr env`: Equivalent to using `def --env`~
- ~`attr wrapped`: Equivalent to using `def --wrapped`~ shelved for
later discussion
    -   several testing related attributes in `std/testing`
- If an attribute has no internal/special purpose, it's stored as
command metadata that can be obtained with `scope commands`.
- This allows having attributes like `@test` which can be used by test
runners.
-   Used the `@example` attribute for `std` examples.
-   Updated the std tests and test runner to use `@test` attributes
-   Added completions for attributes

# User-Facing Changes
Users can add examples to their own command definitions, and add other
arbitrary attributes.

# Tests + Formatting

- 🟢 toolkit fmt
- 🟢 toolkit clippy
- 🟢 toolkit test
- 🟢 toolkit test stdlib

# After Submitting
- Add documentation about the attribute syntax and built-in attributes
- `help attributes`

---------

Co-authored-by: 132ikl <132@ikl.sh>
This commit is contained in:
Bahex
2025-02-11 15:34:51 +03:00
committed by GitHub
parent a58d9b0b3a
commit 442df9e39c
57 changed files with 2028 additions and 987 deletions

View File

@ -58,6 +58,11 @@ pub fn load_standard_library(
("mod.nu", "std/util", include_str!("../std/util/mod.nu")),
("mod.nu", "std/xml", include_str!("../std/xml/mod.nu")),
("mod.nu", "std/config", include_str!("../std/config/mod.nu")),
(
"mod.nu",
"std/testing",
include_str!("../std/testing/mod.nu"),
),
];
for (filename, std_subdir_name, content) in std_submodules.drain(..) {

View File

@ -7,32 +7,16 @@
# Universal assert command
#
# If the condition is not true, it generates an error.
#
# # Example
#
# ```nushell
# >_ assert (3 == 3)
# >_ assert (42 == 3)
# Error:
# × Assertion failed:
# ╭─[myscript.nu:11:1]
# 11 │ assert (3 == 3)
# 12 │ assert (42 == 3)
# · ───┬────
# · ╰── It is not true.
# 13 │
# ╰────
# ```
#
# The --error-label flag can be used if you want to create a custom assert command:
# ```
# def "assert even" [number: int] {
# assert ($number mod 2 == 0) --error-label {
# text: $"($number) is not an even number",
# span: (metadata $number).span,
# }
# }
# ```
@example "This assert passes" { assert (3 == 3) }
@example "This assert fails" { assert (42 == 3) }
@example "The --error-label flag can be used if you want to create a custom assert command:" {
def "assert even" [number: int] {
assert ($number mod 2 == 0) --error-label {
text: $"($number) is not an even number",
span: (metadata $number).span,
}
}
}
export def main [
condition: bool, # Condition, which should be true
message?: string, # Optional error message
@ -52,32 +36,16 @@ export def main [
# Negative assertion
#
# If the condition is not false, it generates an error.
#
# # Examples
#
# >_ assert (42 == 3)
# >_ assert (3 == 3)
# Error:
# × Assertion failed:
# ╭─[myscript.nu:11:1]
# 11 │ assert (42 == 3)
# 12 │ assert (3 == 3)
# · ───┬────
# · ╰── It is not false.
# 13 │
# ╰────
#
#
# The --error-label flag can be used if you want to create a custom assert command:
# ```
# def "assert not even" [number: int] {
# assert not ($number mod 2 == 0) --error-label {
# span: (metadata $number).span,
# text: $"($number) is an even number",
# }
# }
# ```
#
@example "This assert passes" { assert (42 == 3) }
@example "This assert fails" { assert (3 == 3) }
@example "The --error-label flag can be used if you want to create a custom assert command:" {
def "assert not even" [number: int] {
assert not ($number mod 2 == 0) --error-label {
span: (metadata $number).span,
text: $"($number) is an even number",
}
}
}
export def not [
condition: bool, # Condition, which should be false
message?: string, # Optional error message
@ -95,14 +63,12 @@ export def not [
}
}
# Assert that executing the code generates an error
#
# For more documentation see the assert command
#
# # Examples
#
# > assert error {|| missing_command} # passes
# > assert error {|| 12} # fails
@example "This assert passes" { assert error {|| missing_command} }
@example "This assert fails" { assert error {|| 12} }
export def error [
code: closure,
message?: string
@ -120,12 +86,9 @@ export def error [
# Assert $left == $right
#
# For more documentation see the assert command
#
# # Examples
#
# > assert equal 1 1 # passes
# > assert equal (0.1 + 0.2) 0.3
# > assert equal 1 2 # fails
@example "This assert passes" { assert equal 1 1 }
@example "This assert passes" { assert equal (0.1 + 0.2) 0.3 }
@example "This assert fails" { assert equal 1 2 }
export def equal [left: any, right: any, message?: string] {
main ($left == $right) $message --error-label {
span: {
@ -143,12 +106,9 @@ export def equal [left: any, right: any, message?: string] {
# Assert $left != $right
#
# For more documentation see the assert command
#
# # Examples
#
# > assert not equal 1 2 # passes
# > assert not equal 1 "apple" # passes
# > assert not equal 7 7 # fails
@example "This assert passes" { assert not equal 1 2 }
@example "This assert passes" { assert not equal 1 "apple" }
@example "This assert fails" { assert not equal 7 7 }
export def "not equal" [left: any, right: any, message?: string] {
main ($left != $right) $message --error-label {
span: {
@ -162,12 +122,9 @@ export def "not equal" [left: any, right: any, message?: string] {
# Assert $left <= $right
#
# For more documentation see the assert command
#
# # Examples
#
# > assert less or equal 1 2 # passes
# > assert less or equal 1 1 # passes
# > assert less or equal 1 0 # fails
@example "This assert passes" { assert less or equal 1 2 }
@example "This assert passes" { assert less or equal 1 1 }
@example "This assert fails" { assert less or equal 1 0 }
export def "less or equal" [left: any, right: any, message?: string] {
main ($left <= $right) $message --error-label {
span: {
@ -185,11 +142,8 @@ export def "less or equal" [left: any, right: any, message?: string] {
# Assert $left < $right
#
# For more documentation see the assert command
#
# # Examples
#
# > assert less 1 2 # passes
# > assert less 1 1 # fails
@example "This assert passes" { assert less 1 2 }
@example "This assert fails" { assert less 1 1 }
export def less [left: any, right: any, message?: string] {
main ($left < $right) $message --error-label {
span: {
@ -207,11 +161,8 @@ export def less [left: any, right: any, message?: string] {
# Assert $left > $right
#
# For more documentation see the assert command
#
# # Examples
#
# > assert greater 2 1 # passes
# > assert greater 2 2 # fails
@example "This assert passes" { assert greater 2 1 }
@example "This assert fails" { assert greater 2 2 }
export def greater [left: any, right: any, message?: string] {
main ($left > $right) $message --error-label {
span: {
@ -229,12 +180,9 @@ export def greater [left: any, right: any, message?: string] {
# Assert $left >= $right
#
# For more documentation see the assert command
#
# # Examples
#
# > assert greater or equal 2 1 # passes
# > assert greater or equal 2 2 # passes
# > assert greater or equal 1 2 # fails
@example "This assert passes" { assert greater or equal 2 1 }
@example "This assert passes" { assert greater or equal 2 2 }
@example "This assert fails" { assert greater or equal 1 2 }
export def "greater or equal" [left: any, right: any, message?: string] {
main ($left >= $right) $message --error-label {
span: {
@ -253,11 +201,8 @@ alias "core length" = length
# Assert length of $left is $right
#
# For more documentation see the assert command
#
# # Examples
#
# > assert length [0, 0] 2 # passes
# > assert length [0] 3 # fails
@example "This assert passes" { assert length [0, 0] 2 }
@example "This assert fails" { assert length [0] 3 }
export def length [left: list, right: int, message?: string] {
main (($left | core length) == $right) $message --error-label {
span: {
@ -277,11 +222,8 @@ alias "core str contains" = str contains
# Assert that ($left | str contains $right)
#
# For more documentation see the assert command
#
# # Examples
#
# > assert str contains "arst" "rs" # passes
# > assert str contains "arst" "k" # fails
@example "This assert passes" { assert str contains "arst" "rs" }
@example "This assert fails" { assert str contains "arst" "k" }
export def "str contains" [left: string, right: string, message?: string] {
main ($left | core str contains $right) $message --error-label {
span: {

View File

@ -1,45 +1,34 @@
# run a piece of `nushell` code multiple times and measure the time of execution.
#
# this command returns a benchmark report of the following form:
# ```
# record<
# mean: duration
# std: duration
# times: list<duration>
# >
# ```
#
# > **Note**
# > `std bench --pretty` will return a `string`.
#
# # Examples
# measure the performance of simple addition
# > std bench { 1 + 2 } -n 10 | table -e
# ╭───────┬────────────────────╮
# │ mean 4µs 956ns │
# │ std │ 4µs 831ns │
# │ ╭───┬────────────╮ │
# │ times │ │ 0 │ 19µs 402ns │ │
# │ │ 1 │ 4µs 322ns │ │
# │ │ │ 2 │ 3µs 352ns │ │
# │ │ 3 │ 2µs 966ns │ │
# │ │ │ 4 │ 3µs │ │
# │ │ 5 │ 3µs 86ns │ │
# │ │ │ 6 │ 3µs 84ns │ │
# │ │ │ 7 │ 3µs 604ns │ │
# │ │ │ 8 │ 3µs 98ns │ │
# │ │ │ 9 │ 3µs 653ns │ │
# │ │ ╰───┴────────────╯ │
# ╰───────┴────────────────────╯
#
# get a pretty benchmark report
# > std bench { 1 + 2 } --pretty
# 3µs 125ns +/- 2µs 408ns
@example "measure the performance of simple addition" { bench { 1 + 2 } -n 10 } --result {
mean: (4µs + 956ns)
std: (4µs + 831ns)
times: [
(19µs + 402ns)
( 4µs + 322ns)
( 3µs + 352ns)
( 2µs + 966ns)
( 3µs )
( 3µs + 86ns)
( 3µs + 84ns)
( 3µs + 604ns)
( 3µs + 98ns)
( 3µs + 653ns)
]
}
@example "get a pretty benchmark report" { bench { 1 + 2 } --pretty } --result "3µs 125ns +/- 2µs 408ns"
export def main [
code: closure # the piece of `nushell` code to measure the performance of
--rounds (-n): int = 50 # the number of benchmark rounds (hopefully the more rounds the less variance)
--verbose (-v) # be more verbose (namely prints the progress)
--pretty # shows the results in human-readable format: "<mean> +/- <stddev>"
]: [
nothing -> record<mean: duration, std: duration, times: list<duration>>
nothing -> string
] {
let times: list<duration> = (
seq 1 $rounds | each {|i|

View File

@ -89,23 +89,23 @@ def borrow-second [from: record, current: record] {
}
# Subtract later from earlier datetime and return the unit differences as a record
# Example:
# > dt datetime-diff 2023-05-07T04:08:45+12:00 2019-05-10T09:59:12-07:00
# ╭─────────────┬────╮
# │ year │ 3 │
# │ month 11
# │ day 26
# │ hour 23
# │ minute │ 9 │
# │ second 33
# │ millisecond │ 0 │
# │ microsecond │ 0 │
# │ nanosecond │ 0 │
# ╰─────────────┴────╯
@example "Get the difference between two dates" {
dt datetime-diff 2023-05-07T04:08:45+12:00 2019-05-10T09:59:12-07:00
} --result {
year: 3,
month: 11,
day: 26,
hour: 23,
minute: 9,
second: 33,
millisecond: 0,
microsecond: 0,
nanosecond: 0,
}
export def datetime-diff [
later: datetime, # a later datetime
earlier: datetime # earlier (starting) datetime
] {
later: datetime, # a later datetime
earlier: datetime # earlier (starting) datetime
]: [nothing -> record] {
if $earlier > $later {
let start = (metadata $later).span.start
let end = (metadata $earlier).span.end
@ -162,10 +162,10 @@ export def datetime-diff [
}
# Convert record from datetime-diff into humanized string
# Example:
# > dt pretty-print-duration (dt datetime-diff 2023-05-07T04:08:45+12:00 2019-05-10T09:59:12+12:00)
# 3yrs 11months 27days 18hrs 9mins 33secs
export def pretty-print-duration [dur: record] {
@example "Format the difference between two dates into a human readable string" {
dt pretty-print-duration (dt datetime-diff 2023-05-07T04:08:45+12:00 2019-05-10T09:59:12+12:00)
} --result "3yrs 11months 27days 18hrs 9mins 33secs"
export def pretty-print-duration [dur: record]: [nothing -> string] {
mut result = ""
if $dur.year != 0 {
if $dur.year > 1 {

View File

@ -14,21 +14,12 @@
# > The closure also has to be valid for the types it receives
# > These will be flagged as errors later as closure annotations
# > are implemented
#
# # Example
# ```
# use std ["assert equal" "iter find"]
#
# let haystack = ["shell", "abc", "around", "nushell", "std"]
#
# let found = ($haystack | iter find {|e| $e starts-with "a" })
# let not_found = ($haystack | iter find {|e| $e mod 2 == 0})
#
# assert equal $found "abc"
# assert equal $not_found null
# ```
export def find [ # -> any | null
fn: closure # the closure used to perform the search
@example "Find an element starting with 'a'" {
["shell", "abc", "around", "nushell", "std"] | iter find {|e| $e starts-with "a" }
} --result "abc"
@example "Try to find an element starting with 'a'" { ["shell", "abc", "around", "nushell", "std"] | iter find {|e| $e mod 2 == 0} } --result null
export def find [
fn: closure # the closure used to perform the search
] {
filter {|e| try {do $fn $e} } | try { first }
}
@ -38,23 +29,14 @@ export def find [ # -> any | null
#
# # Invariant
# > The closure has to return a bool
#
# # Example
# ```nu
# use std ["assert equal" "iter find-index"]
#
# let res = (
# ["iter", "abc", "shell", "around", "nushell", "std"]
# | iter find-index {|x| $x starts-with 's'}
# )
# assert equal $res 2
#
# let is_even = {|x| $x mod 2 == 0}
# let res = ([3 5 13 91] | iter find-index $is_even)
# assert equal $res -1
# ```
export def find-index [ # -> int
fn: closure # the closure used to perform the search
@example "Find the index of an element starting with 's'" {
["iter", "abc", "shell", "around", "nushell", "std"] | iter find-index {|x| $x starts-with 's'}
} --result 2
@example "Try to find the index of an element starting with 's'" {
[3 5 13 91] | iter find-index {|x| $x mod 2 == 0}
} --result -1
export def find-index [
fn: closure # the closure used to perform the search
] {
enumerate
| find {|e| $e.item | do $fn $e.item }
@ -63,16 +45,11 @@ export def find-index [ # -> int
# Returns a new list with the separator between adjacent
# items of the original list
#
# # Example
# ```
# use std ["assert equal" "iter intersperse"]
#
# let res = ([1 2 3 4] | iter intersperse 0)
# assert equal $res [1 0 2 0 3 0 4]
# ```
export def intersperse [ # -> list<any>
separator: any # the separator to be used
@example "Intersperse the list with `0`" {
[1 2 3 4] | iter intersperse 0
} --result [1 0 2 0 3 0 4]
export def intersperse [
separator: any # the separator to be used
] {
reduce --fold [] {|e, acc|
$acc ++ [$e, $separator]
@ -89,20 +66,12 @@ export def intersperse [ # -> list<any>
# being the list element in the current iteration and the second
# the internal state.
# The internal state is also provided as pipeline input.
#
# # Example
# ```
# use std ["assert equal" "iter scan"]
# let scanned = ([1 2 3] | iter scan 0 {|x, y| $x + $y})
#
# assert equal $scanned [0, 1, 3, 6]
#
# # use the --noinit(-n) flag to remove the initial value from
# # the final result
# let scanned = ([1 2 3] | iter scan 0 {|x, y| $x + $y} -n)
#
# assert equal $scanned [1, 3, 6]
# ```
@example "Get a running sum of the input list" {
[1 2 3] | iter scan 0 {|x, y| $x + $y}
} --result [0, 1, 3, 6]
@example "use the `--noinit(-n)` flag to remove the initial value from the final result" {
[1 2 3] | iter scan 0 {|x, y| $x + $y} -n
} --result [1, 3, 6]
export def scan [ # -> list<any>
init: any # initial value to seed the initial state
fn: closure # the closure to perform the scan
@ -118,16 +87,10 @@ export def scan [ # -> list<any>
# Returns a list of values for which the supplied closure does not
# return `null` or an error. It is equivalent to
# `$in | each $fn | filter $fn`
#
# # Example
# ```nu
# use std ["assert equal" "iter filter-map"]
#
# let res = ([2 5 "4" 7] | iter filter-map {|e| $e ** 2})
#
# assert equal $res [4 25 49]
# ```
export def filter-map [ # -> list<any>
@example "Get the squares of elements that can be squared" {
[2 5 "4" 7] | iter filter-map {|e| $e ** 2}
} --result [4, 25, 49]
export def filter-map [
fn: closure # the closure to apply to the input
] {
each {|$e|
@ -143,16 +106,9 @@ export def filter-map [ # -> list<any>
}
# Maps a closure to each nested structure and flattens the result
#
# # Example
# ```nu
# use std ["assert equal" "iter flat-map"]
#
# let res = (
# [[1 2 3] [2 3 4] [5 6 7]] | iter flat-map {|e| $e | math sum}
# )
# assert equal $res [6 9 18]
# ```
@example "Get the sums of list elements" {
[[1 2 3] [2 3 4] [5 6 7]] | iter flat-map {|e| $e | math sum}
} --result [6, 9, 18]
export def flat-map [ # -> list<any>
fn: closure # the closure to map to the nested structures
] {
@ -160,18 +116,10 @@ export def flat-map [ # -> list<any>
}
# Zips two structures and applies a closure to each of the zips
#
# # Example
# ```nu
# use std ["assert equal" "iter iter zip-with"]
#
# let res = (
# [1 2 3] | iter zip-with [2 3 4] {|a, b| $a + $b }
# )
#
# assert equal $res [3 5 7]
# ```
export def zip-with [ # -> list<any>
@example "Add two lists element-wise" {
[1 2 3] | iter zip-with [2 3 4] {|a, b| $a + $b }
} --result [3, 5, 7]
export def zip-with [ # -> list<any>
other: any # the structure to zip with
fn: closure # the closure to apply to the zips
] {
@ -182,20 +130,9 @@ export def zip-with [ # -> list<any>
}
# Zips two lists and returns a record with the first list as headers
#
# # Example
# ```nu
# use std ["assert equal" "iter iter zip-into-record"]
#
# let res = (
# [1 2 3] | iter zip-into-record [2 3 4]
# )
#
# assert equal $res [
# [1 2 3];
# [2 3 4]
# ]
# ```
@example "Create record from two lists" {
[1 2 3] | iter zip-into-record [2 3 4]
} --result [{1: 2, 2: 3, 3: 4}]
export def zip-into-record [ # -> table<any>
other: list # the values to zip with
] {

View File

@ -15,6 +15,7 @@ export module std/log
export module std/math
export module std/xml
export module std/config
export module std/testing
# Load main dirs command and all subcommands
export use std/dirs main

View File

@ -0,0 +1,17 @@
# Mark command as a test
export alias "attr test" = echo
# Mark a test command to be ignored
export alias "attr ignore" = echo
# Mark a command to be run before each test
export alias "attr before-each" = echo
# Mark a command to be run once before all tests
export alias "attr before-all" = echo
# Mark a command to be run after each test
export alias "attr after-each" = echo
# Mark a command to be run once after all tests
export alias "attr after-all" = echo

View File

@ -1,29 +1,15 @@
# Add the given paths to the PATH.
#
# # Example
# - adding some dummy paths to an empty PATH
# ```nushell
# >_ with-env { PATH: [] } {
# std path add "foo"
# std path add "bar" "baz"
# std path add "fooo" --append
#
# assert equal $env.PATH ["bar" "baz" "foo" "fooo"]
#
# print (std path add "returned" --ret)
# }
# ╭───┬──────────╮
# │ 0 │ returned │
# │ 1 │ bar │
# │ 2 │ baz │
# │ 3 │ foo │
# │ 4 │ fooo │
# ╰───┴──────────╯
# ```
# - adding paths based on the operating system
# ```nushell
# >_ std path add {linux: "foo", windows: "bar", darwin: "baz"}
# ```
@example "adding some dummy paths to an empty PATH" {
with-env { PATH: [] } {
path add "foo"
path add "bar" "baz"
path add "fooo" --append
path add "returned" --ret
}
} --result [returned bar baz foo fooo]
@example "adding paths based on the operating system" {
path add {linux: "foo", windows: "bar", darwin: "baz"}
}
export def --env "path add" [
--ret (-r) # return $env.PATH, useful in pipelines to avoid scoping.
--append (-a) # append to $env.PATH instead of prepending to.
@ -82,11 +68,9 @@ export def ellie [] {
}
# repeat anything a bunch of times, yielding a list of *n* times the input
#
# # Examples
# repeat a string
# > "foo" | std repeat 3 | str join
# "foofoofoo"
@example "repeat a string" {
"foo" | std repeat 3 | str join
} --result "foofoofoo"
export def repeat [
n: int # the number of repetitions, must be positive
]: any -> list<any> {
@ -118,10 +102,9 @@ export const null_device = if $nu.os-info.name == "windows" {
}
# return a null device file.
#
# # Examples
# run a command and ignore it's stderr output
# > cat xxx.txt e> (null-device)
@example "run a command and ignore it's stderr output" {
cat xxx.txt e> (null-device)
}
export def null-device []: nothing -> path {
$null_device
}

View File

@ -14,43 +14,29 @@ def "nu-complete threads" [] {
# test and test-skip annotations may be used multiple times throughout the module as the function names are stored in a list
# Other annotations should only be used once within a module file
# If you find yourself in need of multiple before- or after- functions it's a sign your test suite probably needs redesign
def valid-annotations [] {
{
"#[test]": "test",
"#[ignore]": "test-skip",
"#[before-each]": "before-each"
"#[before-all]": "before-all"
"#[after-each]": "after-each"
"#[after-all]": "after-all"
}
const valid_annotations = {
"test": "test",
"ignore": "test-skip",
"before-each": "before-each"
"before-all": "before-all"
"after-each": "after-each"
"after-all": "after-all"
}
# Returns a table containing the list of function names together with their annotations (comments above the declaration)
def get-annotated [
file: path
]: nothing -> table<function_name: string, annotation: string> {
let raw_file = (
open $file
| lines
| enumerate
| flatten
)
$raw_file
| where item starts-with def and index > 0
| insert annotation {|x|
$raw_file
| get ($x.index - 1)
| get item
| str trim
}
| where annotation in (valid-annotations|columns)
| reject index
| update item {
split column --collapse-empty ' '
| get column2.0
}
| rename function_name
^$nu.current-exe -c $'
source `($file)`
scope commands
| select name attributes
| where attributes != []
| to nuon
'
| from nuon
| update attributes { get name | each {|x| $valid_annotations | get -i $x } | first }
| rename function_name annotation
}
# Takes table of function names and their annotations such as the one returned by get-annotated
@ -72,10 +58,6 @@ def create-test-record []: nothing -> record<before-each: string, after-each: st
let test_record = (
$input
| update annotation {|x|
valid-annotations
| get $x.annotation
}
| group-by --to-table annotation
| update items {|x|
$x.items.function_name

View File

@ -1,3 +1,4 @@
use std/testing *
use std/assert
def run [
@ -41,57 +42,57 @@ def "assert message short" [
assert str contains $output "test message"
}
#[test]
@test
def critical [] {
assert no message 99 critical
assert message CRITICAL critical CRT
}
#[test]
@test
def critical_short [] {
assert message short CRITICAL critical C
}
#[test]
@test
def error [] {
assert no message CRITICAL error
assert message ERROR error ERR
}
#[test]
@test
def error_short [] {
assert message short ERROR error E
}
#[test]
@test
def warning [] {
assert no message ERROR warning
assert message WARNING warning WRN
}
#[test]
@test
def warning_short [] {
assert message short WARNING warning W
}
#[test]
@test
def info [] {
assert no message WARNING info
assert message INFO info "INF" # INF has to be quoted, otherwise it is the `inf` float
}
#[test]
@test
def info_short [] {
assert message short INFO info I
}
#[test]
@test
def debug [] {
assert no message INFO debug
assert message DEBUG debug DBG
}
#[test]
@test
def debug_short [] {
assert message short DEBUG debug D
}

View File

@ -1,3 +1,4 @@
use std/testing *
use std/assert
use commons.nu *
@ -21,14 +22,14 @@ def run-command [
| complete | get --ignore-errors stderr
}
#[test]
@test
def errors_during_deduction [] {
assert str contains (run-command "DEBUG" "msg" "%MSG%" 25) "Cannot deduce log level prefix for given log level"
assert str contains (run-command "DEBUG" "msg" "%MSG%" 25 --ansi (ansi red)) "Cannot deduce log level prefix for given log level"
assert str contains (run-command "DEBUG" "msg" "%MSG%" 25 --level-prefix "abc") "Cannot deduce ansi for given log level"
}
#[test]
@test
def valid_calls [] {
use std/log *
assert equal (run-command "DEBUG" "msg" "%MSG%" 25 --level-prefix "abc" --ansi (ansi default) | str trim --right) "msg"
@ -37,7 +38,7 @@ def valid_calls [] {
assert equal (run-command "INFO" "msg" "%ANSI_START%%LEVEL% %MSG%%ANSI_STOP%" ((log-level).CRITICAL) | str trim --right) $"((log-ansi).CRITICAL)CRT msg(ansi reset)"
}
#[test]
@test
def log-level_handling [] {
use std/log *
assert equal (run-command "DEBUG" "msg" "%LEVEL% %MSG%" 20 | str trim --right) $"((log-prefix).INFO) msg"

View File

@ -1,3 +1,4 @@
use std/testing *
use std *
use std/log *
use std/assert
@ -40,7 +41,7 @@ def "assert formatted" [
assert equal ($output | str trim --right) (format-message $message $format $prefix $ansi)
}
#[test]
@test
def format_flag [] {
assert formatted "test" "25 %MSG% %ANSI_START% %LEVEL%%ANSI_STOP%" critical
assert formatted "test" "25 %MSG% %ANSI_START% %LEVEL%%ANSI_STOP%" error

View File

@ -1,8 +1,9 @@
use std/testing *
use std/assert
use std/log
use std/log *
#[test]
@test
def env_log-ansi [] {
assert equal (log-ansi).CRITICAL (ansi red_bold)
assert equal (log-ansi).ERROR (ansi red)
@ -11,7 +12,7 @@ def env_log-ansi [] {
assert equal (log-ansi).DEBUG (ansi default_dimmed)
}
#[test]
@test
def env_log-level [] {
assert equal (log-level).CRITICAL 50
assert equal (log-level).ERROR 40
@ -20,7 +21,7 @@ def env_log-level [] {
assert equal (log-level).DEBUG 10
}
#[test]
@test
def env_log-prefix [] {
assert equal (log-prefix).CRITICAL "CRT"
assert equal (log-prefix).ERROR "ERR"
@ -29,7 +30,7 @@ def env_log-prefix [] {
assert equal (log-prefix).DEBUG "DBG"
}
#[test]
@test
def env_log-short-prefix [] {
assert equal (log-short-prefix).CRITICAL "C"
assert equal (log-short-prefix).ERROR "E"
@ -38,7 +39,7 @@ def env_log-short-prefix [] {
assert equal (log-short-prefix).DEBUG "D"
}
#[test]
@test
def env_log_format [] {
assert equal $env.NU_LOG_FORMAT $"%ANSI_START%%DATE%|%LEVEL%|%MSG%%ANSI_STOP%"
}

View File

@ -1,7 +1,8 @@
use std/testing *
use std *
use std/assert
#[test]
@test
def assert_basic [] {
assert true
assert (1 + 2 == 3)
@ -9,7 +10,7 @@ def assert_basic [] {
assert error { assert (1 + 2 == 4) }
}
#[test]
@test
def assert_not [] {
assert not false
assert not (1 + 2 == 4)
@ -17,7 +18,7 @@ def assert_not [] {
assert error { assert not (1 + 2 == 3) }
}
#[test]
@test
def assert_equal [] {
assert equal (1 + 2) 3
assert equal (0.1 + 0.2 | into string | into float) 0.3 # 0.30000000000000004 == 0.3
@ -25,7 +26,7 @@ def assert_equal [] {
assert error { assert equal (1 + 2) 4 }
}
#[test]
@test
def assert_not_equal [] {
assert not equal (1 + 2) 4
assert not equal 1 "foo"
@ -33,7 +34,7 @@ def assert_not_equal [] {
assert error { assert not equal 1 1 }
}
#[test]
@test
def assert_error [] {
let failing_code = {|| missing_code_to_run}
assert error $failing_code
@ -43,39 +44,39 @@ def assert_error [] {
assert $assert_error_raised "The assert error should be false if there is no error in the executed code."
}
#[test]
@test
def assert_less [] {
assert less 1 2
assert error { assert less 1 1 }
}
#[test]
@test
def assert_less_or_equal [] {
assert less or equal 1 2
assert less or equal 1 1
assert error { assert less or equal 1 0 }
}
#[test]
@test
def assert_greater [] {
assert greater 2 1
assert error { assert greater 2 2 }
}
#[test]
@test
def assert_greater_or_equal [] {
assert greater or equal 1 1
assert greater or equal 2 1
assert error { assert greater or equal 0 1 }
}
#[test]
@test
def assert_length [] {
assert length [0, 0, 0] 3
assert error { assert length [0, 0] 3 }
}
#[ignore]
@ignore
def assert_skip [] {
assert true # This test case is skipped on purpose
}

View File

@ -1,3 +1,4 @@
use std/testing *
use std/assert
use std/log
@ -5,7 +6,7 @@ use std/log
# Each 'use' for that module in the test script will execute the def --env block.
# PWD at the time of the `use` will be what the export def --env block will see.
#[before-each]
@before-each
def before-each [] {
# need some directories to play with
let base_path = ($nu.temp-path | path join $"test_dirs_(random uuid)")
@ -17,7 +18,7 @@ def before-each [] {
{base_path: $base_path, path_a: $path_a, path_b: $path_b}
}
#[after-each]
@after-each
def after-each [] {
let base_path = $in.base_path
cd $base_path
@ -36,7 +37,7 @@ def cur_ring_check [expect_dir:string, expect_position: int scenario:string] {
assert equal $expect_position $env.DIRS_POSITION $"position in ring after ($scenario)"
}
#[test]
@test
def dirs_command [] {
# careful with order of these statements!
# must capture value of $in before executing `use`s
@ -87,7 +88,7 @@ def dirs_command [] {
assert equal $env.PWD $c.base_path "drop changes PWD (regression test for #9449)"
}
#[test]
@test
def dirs_next [] {
# must capture value of $in before executing `use`s
let $c = $in
@ -109,7 +110,7 @@ def dirs_next [] {
}
#[test]
@test
def dirs_cd [] {
# must capture value of $in before executing `use`s
let $c = $in
@ -134,7 +135,7 @@ def dirs_cd [] {
assert equal [$c.path_b $c.path_b] $env.DIRS_LIST "cd updated both positions in ring"
}
#[test]
@test
def dirs_goto_bug10696 [] {
let $c = $in
cd $c.base_path
@ -148,7 +149,7 @@ def dirs_goto_bug10696 [] {
assert equal $env.PWD $c.path_b "goto other, then goto to come back returns to same directory"
}
#[test]
@test
def dirs_goto [] {
let $c = $in
cd $c.base_path

View File

@ -1,44 +1,45 @@
use std/testing *
use std/assert
use std/dt *
#[test]
@test
def equal_times [] {
let t1 = (date now)
assert equal (datetime-diff $t1 $t1) ({year:0, month:0, day:0, hour:0, minute:0, second:0, millisecond:0, microsecond:0 nanosecond:0})
}
#[test]
@test
def one_ns_later [] {
let t1 = (date now)
assert equal (datetime-diff ($t1 + 1ns) $t1) ({year:0, month:0, day:0, hour:0, minute:0, second:0, millisecond:0, microsecond:0 nanosecond:1})
}
#[test]
@test
def one_yr_later [] {
let t1 = ('2022-10-1T0:1:2z' | into datetime) # a date for which one year later is 365 days, since duration doesn't support year or month
assert equal (datetime-diff ($t1 + 365day) $t1) ({year:1, month:0, day:0, hour:0, minute:0, second:0, millisecond:0, microsecond:0 nanosecond:0})
}
#[test]
@test
def carry_ripples [] {
let t1 = ('2023-10-9T0:0:0z' | into datetime)
let t2 = ('2022-10-9T0:0:0.000000001z' | into datetime)
assert equal (datetime-diff $t1 $t2) ({year:0, month:11, day:30, hour:23, minute:59, second:59, millisecond:999, microsecond:999 nanosecond:999})
}
#[test]
@test
def earlier_arg_must_be_less_or_equal_later [] {
let t1 = ('2022-10-9T0:0:0.000000001z' | into datetime)
let t2 = ('2023-10-9T0:0:0z' | into datetime)
assert error {|| (datetime-diff $t1 $t2)}
}
#[test]
@test
def pp_skips_zeros [] {
assert equal (pretty-print-duration {year:1, month:0, day:0, hour:0, minute:0, second:0, millisecond:0, microsecond:0 nanosecond:0}) "1yr "
}
#[test]
@test
def pp_doesnt_skip_neg [] { # datetime-diff can't return negative units, but prettyprint shouldn't skip them (if passed handcrafted record)
assert equal (pretty-print-duration {year:-1, month:0, day:0, hour:0, minute:0, second:0, millisecond:0, microsecond:0 nanosecond:0}) "-1yr "
}
}

View File

@ -1,4 +1,5 @@
# Test std/formats when importing module-only
use std/testing *
use std/assert
use std/formats *
@ -30,113 +31,113 @@ def test_data_multiline [--nuon] {
}
}
#[test]
@test
def from_ndjson_multiple_objects [] {
let result = test_data_multiline | from ndjson
let expect = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}]
assert equal $result $expect "could not convert from NDJSON"
}
#[test]
@test
def from_ndjson_single_object [] {
let result = '{"a": 1}' | from ndjson
let expect = [{a:1}]
assert equal $result $expect "could not convert from NDJSON"
}
#[test]
@test
def from_ndjson_invalid_object [] {
assert error { '{"a":1' | from ndjson }
}
#[test]
@test
def from_jsonl_multiple_objects [] {
let result = test_data_multiline | from jsonl
let expect = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}]
assert equal $result $expect "could not convert from JSONL"
}
#[test]
@test
def from_jsonl_single_object [] {
let result = '{"a": 1}' | from jsonl
let expect = [{a:1}]
assert equal $result $expect "could not convert from JSONL"
}
#[test]
@test
def from_jsonl_invalid_object [] {
assert error { '{"a":1' | from jsonl }
}
#[test]
@test
def to_ndjson_multiple_objects [] {
let result = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}] | to ndjson | str trim
let expect = test_data_multiline
assert equal $result $expect "could not convert to NDJSON"
}
#[test]
@test
def to_ndjson_single_object [] {
let result = [{a:1}] | to ndjson | str trim
let expect = "{\"a\":1}"
assert equal $result $expect "could not convert to NDJSON"
}
#[test]
@test
def to_jsonl_multiple_objects [] {
let result = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}] | to jsonl | str trim
let expect = test_data_multiline
assert equal $result $expect "could not convert to JSONL"
}
#[test]
@test
def to_jsonl_single_object [] {
let result = [{a:1}] | to jsonl | str trim
let expect = "{\"a\":1}"
assert equal $result $expect "could not convert to JSONL"
}
#[test]
@test
def from_ndnuon_multiple_objects [] {
let result = test_data_multiline | from ndnuon
let expect = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}]
assert equal $result $expect "could not convert from NDNUON"
}
#[test]
@test
def from_ndnuon_single_object [] {
let result = '{a: 1}' | from ndnuon
let expect = [{a:1}]
assert equal $result $expect "could not convert from NDNUON"
}
#[test]
@test
def from_ndnuon_invalid_object [] {
assert error { '{"a":1' | formats from ndnuon }
}
#[test]
@test
def to_ndnuon_multiple_objects [] {
let result = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}] | to ndnuon | str trim
let expect = test_data_multiline --nuon
assert equal $result $expect "could not convert to NDNUON"
}
#[test]
@test
def to_ndnuon_single_object [] {
let result = [{a:1}] | to ndnuon | str trim
let expect = "{a: 1}"
assert equal $result $expect "could not convert to NDNUON"
}
#[test]
@test
def to_ndnuon_multiline_strings [] {
let result = "foo\n\\n\nbar" | to ndnuon
let expect = '"foo\n\\n\nbar"'
assert equal $result $expect "could not convert multiline string to NDNUON"
}
#[test]
@test
def from_ndnuon_multiline_strings [] {
let result = '"foo\n\\n\nbar"' | from ndnuon
let expect = ["foo\n\\n\nbar"]

View File

@ -1,13 +1,14 @@
use std/testing *
use std/assert
use std/help
#[test]
@test
def show_help_on_commands [] {
let help_result = (help alias)
assert ("item not found" not-in $help_result)
}
#[test]
@test
def show_help_on_error_make [] {
let help_result = (help error make)
assert ("Error: nu::shell::eval_block_with_input" not-in $help_result)

View File

@ -1,7 +1,8 @@
use std/testing *
use std *
use std/assert
#[test]
@test
def iter_find [] {
let hastack1 = [1 2 3 4 5 6 7]
let hastack2 = [nushell rust shell iter std]
@ -20,7 +21,7 @@ def iter_find [] {
assert equal $res null
}
#[test]
@test
def iter_intersperse [] {
let res = ([1 2 3 4] | iter intersperse 0)
assert equal $res [1 0 2 0 3 0 4]
@ -41,7 +42,7 @@ def iter_intersperse [] {
assert equal $res [4]
}
#[test]
@test
def iter_scan [] {
let scanned = ([1 2 3] | iter scan 0 {|x, y| $x + $y} -n)
assert equal $scanned [1, 3, 6]
@ -56,7 +57,7 @@ def iter_scan [] {
assert equal $scanned ["a" "ab" "abc" "abcd"]
}
#[test]
@test
def iter_filter_map [] {
let res = ([2 5 "4" 7] | iter filter-map {|it| $it ** 2})
assert equal $res [4 25 49]
@ -68,7 +69,7 @@ def iter_filter_map [] {
assert equal $res [3 42 69]
}
#[test]
@test
def iter_find_index [] {
let res = (
["iter", "abc", "shell", "around", "nushell", "std"]
@ -84,7 +85,7 @@ def iter_find_index [] {
assert equal $res 0
}
#[test]
@test
def iter_zip_with [] {
let res = (
[1 2 3] | iter zip-with [2 3 4] {|a, b| $a + $b }
@ -111,7 +112,7 @@ def iter_zip_with [] {
]
}
#[test]
@test
def iter_flat_map [] {
let res = (
[[1 2 3] [2 3 4] [5 6 7]] | iter flat-map {|it| $it | math sum}
@ -122,7 +123,7 @@ def iter_flat_map [] {
assert equal $res [11 22 33]
}
#[test]
@test
def iter_zip_into_record [] {
let headers = [name repo position]
let values = [rust github 1]

View File

@ -1,6 +1,7 @@
use std/testing *
use std/assert
#[test]
@test
def banner [] {
use std/prelude
assert ((prelude banner | lines | length) == 16)

View File

@ -1,28 +1,29 @@
use std/testing *
use std/log
use std/assert
#[before-each]
@before-each
def before-each [] {
log debug "Setup is running"
{msg: "This is the context"}
}
#[after-each]
@after-each
def after-each [] {
log debug $"Teardown is running. Context: ($in)"
}
#[test]
@test
def assert_pass [] {
log debug $"Assert is running. Context: ($in)"
}
#[ignore]
@ignore
def assert_skip [] {
log debug $"Assert is running. Context: ($in)"
}
#[ignore]
@ignore
def assert_fail_skipped_by_default [] {
# Change test-skip to test if you want to see what happens if a test fails
log debug $"Assert is running. Context: ($in)"

View File

@ -1,4 +1,5 @@
# Test std/formats when importing `use std *`
use std/testing *
use std *
def test_data_multiline [--nuon] {
@ -30,113 +31,113 @@ def test_data_multiline [--nuon] {
}
}
#[test]
@test
def from_ndjson_multiple_objects [] {
let result = test_data_multiline | formats from ndjson
let expect = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}]
assert equal $result $expect "could not convert from NDJSON"
}
#[test]
@test
def from_ndjson_single_object [] {
let result = '{"a": 1}' | formats from ndjson
let expect = [{a:1}]
assert equal $result $expect "could not convert from NDJSON"
}
#[test]
@test
def from_ndjson_invalid_object [] {
assert error { '{"a":1' | formats from ndjson }
}
#[test]
@test
def from_jsonl_multiple_objects [] {
let result = test_data_multiline | formats from jsonl
let expect = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}]
assert equal $result $expect "could not convert from JSONL"
}
#[test]
@test
def from_jsonl_single_object [] {
let result = '{"a": 1}' | formats from jsonl
let expect = [{a:1}]
assert equal $result $expect "could not convert from JSONL"
}
#[test]
@test
def from_jsonl_invalid_object [] {
assert error { '{"a":1' | formats from jsonl }
}
#[test]
@test
def to_ndjson_multiple_objects [] {
let result = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}] | formats to ndjson | str trim
let expect = test_data_multiline
assert equal $result $expect "could not convert to NDJSON"
}
#[test]
@test
def to_ndjson_single_object [] {
let result = [{a:1}] | formats to ndjson | str trim
let expect = "{\"a\":1}"
assert equal $result $expect "could not convert to NDJSON"
}
#[test]
@test
def to_jsonl_multiple_objects [] {
let result = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}] | formats to jsonl | str trim
let expect = test_data_multiline
assert equal $result $expect "could not convert to JSONL"
}
#[test]
@test
def to_jsonl_single_object [] {
let result = [{a:1}] | formats to jsonl | str trim
let expect = "{\"a\":1}"
assert equal $result $expect "could not convert to JSONL"
}
#[test]
@test
def from_ndnuon_multiple_objects [] {
let result = test_data_multiline | formats from ndnuon
let expect = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}]
assert equal $result $expect "could not convert from NDNUON"
}
#[test]
@test
def from_ndnuon_single_object [] {
let result = '{a: 1}' | formats from ndnuon
let expect = [{a:1}]
assert equal $result $expect "could not convert from NDNUON"
}
#[test]
@test
def from_ndnuon_invalid_object [] {
assert error { '{"a":1' | formats from ndnuon }
}
#[test]
@test
def to_ndnuon_multiple_objects [] {
let result = [{a:1},{a:2},{a:3},{a:4},{a:5},{a:6}] | formats to ndnuon | str trim
let expect = test_data_multiline --nuon
assert equal $result $expect "could not convert to NDNUON"
}
#[test]
@test
def to_ndnuon_single_object [] {
let result = [{a:1}] | formats to ndnuon | str trim
let expect = "{a: 1}"
assert equal $result $expect "could not convert to NDNUON"
}
#[test]
@test
def to_ndnuon_multiline_strings [] {
let result = "foo\n\\n\nbar" | formats to ndnuon
let expect = '"foo\n\\n\nbar"'
assert equal $result $expect "could not convert multiline string to NDNUON"
}
#[test]
@test
def from_ndnuon_multiline_strings [] {
let result = '"foo\n\\n\nbar"' | formats from ndnuon
let expect = ["foo\n\\n\nbar"]

View File

@ -1,11 +1,12 @@
use std/testing *
use std/assert
export use std *
#[test]
@test
def std_post_import [] {
assert length (scope commands | where name == "path add") 1
assert length (scope commands | where name == "ellie") 1
assert length (scope commands | where name == "repeat") 1
assert length (scope commands | where name == "formats from jsonl") 1
assert length (scope commands | where name == "dt datetime-diff") 1
}
}

View File

@ -1,6 +1,7 @@
use std/testing *
use std/assert
#[test]
@test
def std_pre_import [] {
# These commands shouldn't exist without an import
assert length (scope commands | where name == "path add") 0
@ -8,4 +9,4 @@ def std_pre_import [] {
assert length (scope commands | where name == "repeat") 0
assert length (scope commands | where name == "from jsonl") 0
assert length (scope commands | where name == "datetime-diff") 0
}
}

View File

@ -1,6 +1,7 @@
use std/testing *
use std *
#[test]
@test
def path_add [] {
use std/assert
@ -44,7 +45,7 @@ def path_add [] {
}
}
#[test]
@test
def path_add_expand [] {
use std/assert
@ -70,7 +71,7 @@ def path_add_expand [] {
rm $real_dir $link_dir
}
#[test]
@test
def repeat_things [] {
use std/assert
assert error { "foo" | repeat -1 }

View File

@ -1,6 +1,7 @@
use std/testing *
use std/util *
#[test]
@test
def path_add [] {
use std/assert
@ -44,7 +45,7 @@ def path_add [] {
}
}
#[test]
@test
def path_add_expand [] {
use std/assert
@ -70,7 +71,7 @@ def path_add_expand [] {
rm $real_dir $link_dir
}
#[test]
@test
def repeat_things [] {
use std/assert
assert error { "foo" | repeat -1 }

View File

@ -1,7 +1,8 @@
use std/testing *
use std/xml *
use std/assert
#[before-each]
@before-each
def before-each [] {
{sample_xml: ('
<a>
@ -17,7 +18,7 @@ def before-each [] {
}
}
#[test]
@test
def xml_xaccess [] {
let sample_xml = $in.sample_xml
@ -28,7 +29,7 @@ def xml_xaccess [] {
assert equal ($sample_xml | xaccess [* * * {|e| $e.attributes != {}}]) [[tag, attributes, content]; [c, {a: b}, []]]
}
#[test]
@test
def xml_xupdate [] {
let sample_xml = $in.sample_xml
@ -37,7 +38,7 @@ def xml_xupdate [] {
assert equal ($sample_xml | xupdate [* * * {|e| $e.attributes != {}}] {|x| $x | update content ['xml']}) {tag: a, attributes: {}, content: [[tag, attributes, content]; [b, {}, [[tag, attributes, content]; [c, {a: b}, [xml]]]], [c, {}, []], [d, {}, [[tag, attributes, content]; [e, {}, [[tag, attributes, content]; [null, null, z]]], [e, {}, [[tag, attributes, content]; [null, null, x]]]]]]}
}
#[test]
@test
def xml_xinsert [] {
let sample_xml = $in.sample_xml